jpanel和ActionLister不起作用



我可以使用两个ActionLister执行相同的操作,但我使用该实施来制作代码凝结,但它不起作用。当我选择B1时,Textfield上没有文字。

public Radio_Button() {
        setSize(600, 400);
        panel = new JPanel();
        tf = new JTextField("                ");
        group = new ButtonGroup();
        b1 = new JRadioButton("1");
        b2 = new JRadioButton("2");
        b1.setActionCommand("you choose one");
        b2.setActionCommand("you choose two");
        group.add(b1);
        group.add(b2);
        panel.add(b1);
        panel.add(b2);
        panel.add(tf);
        add(panel);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        tf.setText(e.getActionCommand());
    }
}

您忘记了为无线电按钮注册听众。

setActionCommand()之后添加此。

b1.addActionListener(this);
b2.addActionListener(this);

如果您有不同的按钮

 JButton button1 = new JButton("Some Text");
 JButton button2 = new JButton("Some Other Text");
  button1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "I was clicked !");
        } });
   button2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Second button was clicked!");
        } });

最新更新