-2

我有一个表格,当我点击保存按钮时,“是”字符串应该显示在我的控制台上!

(我使用“是”字符串进行测试!)

但点击时不起作用。我的代码:

public final class NewUserFrame1 extends JFrame implements ActionListener {

UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;

public NewUserFrame1() {
    add(rowComponent(), BorderLayout.CENTER);
    setLocation(200, 40);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
}

public JPanel rowComponent() {

    JPanel panel = new JPanel();
    fnamelbl = new JLabel("First name");
    lnamelbl = new JLabel("Last Name");
    JLabel fntemp = new JLabel();
    JLabel lntemp = new JLabel();
    fntf = new JTextField(10);
    lntf = new JTextField(10);
    gndlnl = new JLabel("Gender");
    malerb = new JRadioButton("Male");
    femalerb = new JRadioButton("Female");
    bgroup = new ButtonGroup();
    bgroup.add(malerb);
    bgroup.add(femalerb);
    registnm = new JLabel("Registration ID is:");
    showreglbl = new JLabel("");
    JLabel regtemp = new JLabel();
    savebt = new JButton("Save");
    cancelbt = new JButton("Cancell");
    JLabel buttontemp = new JLabel();

    panel.add(fnamelbl);
    panel.add(fntf);
    panel.add(fntemp);
    panel.add(lnamelbl);
    panel.add(lntf);
    panel.add(lntemp);
    panel.add(gndlnl);

    JPanel radiopanel = new JPanel();
    radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    radiopanel.add(malerb);
    radiopanel.add(femalerb);
    panel.add(radiopanel);
    panel.add(new JLabel());
    panel.add(registnm);
    panel.add(showreglbl);
    panel.add(regtemp);
    panel.add(savebt);
    panel.add(cancelbt);
    panel.add(buttontemp);

    panel.setLayout(new SpringLayout());
    SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
    return panel;
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            NewUserFrame1 newUserFrame1 = new NewUserFrame1();
        }
    });
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == savebt) {
        System.out.print("Yes");
    }
}

}
4

2 回答 2

4

您需要像这样向按钮添加 ActionListener:

savebt.addActionListener(this);

或使用匿名类,如下所示:

savebt.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
           // your code.
    }
});

使用匿名类(或内部类)会更好,因为在给定类中不能有多个 actionPerformed() 方法。

于 2013-04-10T16:44:46.403 回答
3

您需要告诉按钮调用ActionListener

savebt = new JButton("Save");
savebt.addActionListener(this);

请注意,如果您打算对保存和取消按钮使用相同的方法,则需要区分,也许通过比较ActionEvent两个按钮的来源。

于 2013-04-10T16:43:10.703 回答