一个ActionListener从另一个类添加到一个JButton [英] Add an actionListener to a JButton from another class
问题描述
所以我有两个类パ和testFrame。所有的按钮都在パ类。我想的ActionListeners在testFrame类添加到Jbuttons中。我怎么会去这样做?
so I have two classes testPanel and testFrame. All the buttons are in the testPanel class. I want to add ActionListeners to the Jbuttons in the testFrame class. How do I go about doing this?
パ:
public class testPanel extends JPanel{
JLabel codeLbl = new JLabel("Code");
JLabel titleLbl = new JLabel("Title");
JLabel priceLbl = new JLabel("Price");
JTextField codeTxt = new JTextField(20);
JTextField titleTxt = new JTextField(20);
JTextField priceTxt = new JTextField(20);
JButton addBtn = new JButton("Add");
JButton updateBtn = new JButton("Update");
JButton delBtn = new JButton("Delete");
JButton exitBtn = new JButton("Exit");
JButton firstBtn = new JButton("First");
JButton prevBtn = new JButton("Previous");
JButton nextBtn = new JButton("Next");
JButton lastBtn = new JButton("Last");
JPanel info = new JPanel();
JPanel buttons = new JPanel();
public testPanel(){
info.setLayout(new GridLayout(3,2));
info.add(codeLbl);
info.add(codeTxt);
info.add(titleLbl);
info.add(titleTxt);
info.add(priceLbl);
info.add(priceTxt);
buttons.setLayout(new GridLayout(2,4));
buttons.add(addBtn);
buttons.add(updateBtn);
buttons.add(delBtn);
buttons.add(exitBtn);
buttons.add(firstBtn);
buttons.add(prevBtn);
buttons.add(nextBtn);
buttons.add(lastBtn);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(BorderLayout.CENTER, info);
container.add(BorderLayout.SOUTH, buttons);
add(container);
}
}
testFrame:
testFrame:
public class testFrame extends JFrame{
JPanel p = new testPanel();
public testFrame(){
super("BLAH");
this.getContentPane().add(p);setVisible(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new testFrame();
}
}
推荐答案
首先,我将不是简单地提供给面板按钮公共访问,这会导致与管理和责任范围的问题太多。恕我直言..
First of all, I would be opposed to simply providing public access to the button in the panel, this leads to too many issues with management and scope of responsibility ... IMHO
您需要某种参考 testPane
,那么这将提供的功能附加一个的ActionListener
。然后,它是由 testPane
管理,获取如何做。
You need some kind of reference to the testPane
, which would then provide functionality to attach a ActionListener
. Then it's up to testPane
to manage how that gets done.
这篇关于一个ActionListener从另一个类添加到一个JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!