向RadioPanel添加动作侦听器

问题描述 投票:1回答:2

我目前正在尝试为我的JCheckBox实现一个动作监听器,这样当它被选中时,它将打开一个JFileChooser,供用户选择他们想要GUI使用的文件。对于初学者,如何让控制台打印出“Box clicked!”当用户选中该框时?

自从我在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);
}
java swing actionlistener jcheckbox
2个回答
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) {
    }
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.