JPanel和ActionLister无法正常工作

时间:2017-03-15 04:24:47

标签: java swing actionlistener

我可以使用两个ActionLister来执行相同的操作,但是我使用工具来使代码压缩,但它只是不起作用。 当我选择b1时,文本字段中没有文字。

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

    }
}

1 个答案:

答案 0 :(得分:0)

您忘记为单选按钮注册一个监听器。

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!");
        } });