将动作侦听器添加到RadioPanel

时间:2019-02-14 16:00:25

标签: java swing actionlistener jcheckbox

我当前正在尝试为我的JCheckBox实现一个动作监听器,以便在选择它时会打开一个JFileChooser供用户选择他们希望GUI使用的文件。首先,我如何使控制台打印出“单击框!”用户何时选中该框?

自从我在Swing中编程以来已经有一段时间了,所以任何建议都可以帮忙!

public class RadioPanel extends JPanel implements ActionListener
{

    private static final long serialVersionUID = -1890379016551779953L;
    private JCheckBox box;
    private JLabel label;

public RadioPanel(String message)
{
    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.WEST;
    c.gridx = 0;
    c.gridy = 0;
    box =  new JCheckBox();
    this.add(box,c);
    c.gridx = 1;
    c.gridy = 0;
    label = new JLabel(message);
    this.add(label, c);
}

2 个答案:

答案 0 :(得分:1)

ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
        boolean selected = abstractButton.getModel().isSelected();
        System.out.println("Is selected :" + selected);
      }
    };
box.addActionListener(actionListener);

答案 1 :(得分:1)

我认为这是因为代码没有事件监听器。 请参阅下面的代码。

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


class RadioPanel extends JPanel implements ActionListener {
    private static final long serialVersionUID = -1890379016551779953L;
    private JCheckBox box;
    private JLabel label;

    public RadioPanel(String message) {
        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.WEST;
        c.gridx = 0;
        c.gridy = 0;
        box = new JCheckBox();

        // here
        box.addActionListener(event -> {
            JCheckBox checkBox = (JCheckBox) event.getSource();
            if (checkBox.isSelected()) {
                System.out.println("Box clicked!");
            }
        });

        this.add(box, c);
        c.gridx = 1;
        c.gridy = 0;
        label = new JLabel(message);
        this.add(label, c);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
    }
}