Reputation: 67
I'm a beginner in java and I have a gui in java that has two rows of 3 checkboxes ! I want to enable the second row according to the checkboxes that are check in the first ! For example if I check the first row first checkbox , then the sexond row first checkbox to be enabled !In other words I want the checkboxes in the second row to be unable to be checked unless a checkbox from the first row is checked ! I have tried almost every method from the oracle's documentation but nothing works ! Any idea will be helpful !
EDIT :
GetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!cEntertainment.isSelected() && !cEducation.isSelected() && !cFood.isSelected()){
textArea.setText("Error ! Please select a Category and THEN a Type !");
cDrink.setEnabled(false);
}
}
});
Upvotes: 0
Views: 1152
Reputation: 5435
As an alternative to any approach that uses listeners, you could use a "read-only" model for the JCheckBox:
import java.awt.*;
import javax.swing.*;
import javax.swing.JToggleButton.*;
public class ReadOnlyJCheckBoxDemo implements Runnable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new ReadOnlyJCheckBoxDemo());
}
public void run()
{
JCheckBox choice1 = new JCheckBox("Red");
choice1.setModel(new ReadOnlyToggleButtonModel(true));
choice1.setFocusable(false);
JCheckBox choice2 = new JCheckBox("Green");
choice2.setModel(new ReadOnlyToggleButtonModel(false));
choice2.setFocusable(false);
JPanel buttonPanel = new JPanel(new GridLayout(2,1));
buttonPanel.add(choice1);
buttonPanel.add(choice2);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttonPanel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public class ReadOnlyToggleButtonModel extends ToggleButtonModel
{
public ReadOnlyToggleButtonModel()
{
super();
}
public ReadOnlyToggleButtonModel(boolean selected)
{
super();
super.setSelected(selected);
}
@Override
public void setSelected(boolean b)
{
// intentionally do nothing
}
}
}
Upvotes: 0
Reputation: 1936
You could add an ItemListener
to the JCheckBox
. Whenever you (un)select a JTextBox
, this event will be triggered. Then, you can check which JTextBox
was changed and it's new value, and then enable the JTextBox
on the other row (with JCheckBox.setEnabled(true/false)
).
See more info here: http://docs.oracle.com/javase/tutorial/uiswing/events/itemlistener.html
Upvotes: 1
Reputation: 16364
It sounds like what you want to do is to add a item listener on each checkbox in the first row, and have that listener enable or disable the corresponding checkbox in the second row.
JCheckBox[] checkPair(String top, String bottom) {
final JCheckBox[] ret = { new JCheckBox(top), new JCheckBox(bottom) };
ret[0].addItemListener(new ItemListener() {
void itemStateChanged(ItemEvent e) {
ret[1].setEnabled(ret[0].isSelected());
ret[1].setSelected(ret[1].isSelected() && ret[0].isSelected());
}
});
return ret;
}
Upvotes: 0