Reputation: 30097
Why can't I set button model for JCheckBox
?
The following code works and draws a window with one single check box in the center. Check box is operational:
public class JCheckButton_Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ButtonModel buttonModel = new DefaultButtonModel();
JCheckBox checkBox = new JCheckBox();
checkBox.setText("Check Box");
//checkBox.setModel(buttonModel);
JPanel controlPanel = new JPanel();
controlPanel.add(checkBox);
JFrame frame = new JFrame();
frame.add(controlPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(640, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
But if I add a model to the box (uncomment line) check box become non-operational (does not change if clicked).
Why?
Upvotes: 3
Views: 555
Reputation: 3141
Cause it is the default button model implementation for buttons and reacts to your actions as button. If You still want to use ButtonModel
then You should implement check box behaviour for it.
For example You can use the following implementation
......
final ButtonModel buttonModel = new DefaultButtonModel();
buttonModel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonModel.setSelected(!buttonModel.isSelected());
}
});
......
Upvotes: 2
Reputation: 168825
// this is more than just a standard button..
ButtonModel buttonModel = new JToggleButton.ToggleButtonModel();
Upvotes: 4