views:

330

answers:

3

I am disabling a JCheckbox and then enabling it with the help of setEnabled(...) method.

But the problem is if I disable a unselected checkbox, then it becomes selected after I enable it.

I want all of them to have the same state after being enabled that they had before being disabled.

+1  A: 

Are you enabling/disabling the JCheckBox using an ActionListener? If so, then that is normal because when you click on the checkbox, the isSelected() status changes.

What you can do is to add checks using isSelected() and the setSelected() methods.

Coding District
I didn't get your answer. Anyway, I am disabling/enabling the checkbox through an `xxxxActionPerformed()` method of a Start button.
Yatendra Goel
styx777 is trying to say that you should call the `setSelected()` method after calling `setEnabled()`. So you can select the component you wish.
Ham
+1  A: 

Hi,

The below code works as you describe:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CheckboxTest implements ActionListener{
    private JCheckBox checkbox = new JCheckBox();
    private JButton btn = new JButton("Enable");
    public CheckboxTest(){
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.getContentPane().add(panel);      
        checkbox.setEnabled(false);
        btn.addActionListener(this);
        panel.add(checkbox);
        panel.add(btn);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    }

    public static void main(String[] args){
        new CheckboxTest();
    }

    public void actionPerformed(ActionEvent e) {
        checkbox.setEnabled(!checkbox.isEnabled());
        btn.setText(checkbox.isEnabled()?"Disable":"Enable");       
    } 
}
Suresh Kumar
+1  A: 

If you call setEnabled that should not affect the selected state. If it is, then I suggest you reexamine your code to see if there is anything that can account for this behaviour. As someone else suggested, maybe if you post a code sample that may be helpful.

Update: To make it perfectly clear, there are only two ways the selected state of a checkbox can be changed.

  1. A call to setSelected
  2. User clicks on the checkbox

A call to setEnabled does not change the selected state. Thus, there must be something odd in your code that is causing this.

Avrom