所以我有两个类 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);
}
}
测试框架:
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();
}
}