简体   繁体   中英

Add Action Listener to RadioPanel

I am currently trying to implement an action listener to my JCheckBox so that when it is selected, it will open a JFileChooser for the user to pick a file they want the GUI to use. For starters how would I get the console to print out "Box clicked!" when a user checks the box?

It has been a while since I've programmed in Swing so any advice helps!

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

I think it's because the code does not have an event listener. See my code below.

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) {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM