从另一个类向JButton添加actionListener

所以我有两个类testPanel和testFrame。 所有按钮都在testPanel类中。 我想将ActionListeners添加到testFrame类的Jbuttons中。 我该怎么做呢?

パ:

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:

  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(); } 

}

首先,我反对简单地提供公共访问面板中的按钮,这导致管理和责任范围太多问题…恕我直言

您需要对testPane某种引用,然后它将提供附加ActionListenerfunction。 然后由testPane来管理如何完成。

这是你可以做的:

1.首先创建一个扩展JPanel的类

2.在该类中,定义一个setActionListener方法,如下所示:

 public void setButtonsActionListener(ActionListener listener){ // and in here set your buttons action listeners button1.addActionListener(listener); button2.addActionListener(listener); ... } 

3,在JFrame类中,使用ActionLister接口的匿名实现调用面板的setButtonsActionListener方法:

  thePanel.setButtonsActionListener(new ActionListener(){ @Override void actionPerformed(ActionEvent e){ // here do what you gotta do when the button is clicked } }); 

那么你可以尝试这个(这需要你有一个testPanel类的实例和button1设置为public:

 testFrame.button1.setActionListener(new ActionListener(@Override public void actionPerformed(ActionEvent event){}}); 

或者你可以在testPanel中创建一个设置动作监听器的函数。