Reputation: 11
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);
}
Upvotes: 1
Views: 112
Reputation: 1037
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) {
}
}
Upvotes: 1
Reputation: 4574
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);
Upvotes: 1