[英]Make a JCheckBox unable to be checked
我是Java的初学者,我在Java中有一个GUI,其中包含2行3个复选框! 我想根据第一行中的复选框启用第二行! 例如,如果我选中第一行的第一复选框,然后启用sexond第一行的复选框!换句话说,除非第二行的复选框被选中,否则我希望第二行的复选框无法被选中! 我已经尝试了oracle文档中的几乎所有方法,但是没有任何效果! 任何想法都会有所帮助!
编辑:
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);
}
}
});
您可以将ItemListener
添加到JCheckBox
。 每当(取消)选择JTextBox
,都会触发此事件。 然后,您可以检查更改了哪个JTextBox
及其新值,然后在另一行上启用JTextBox
(使用JCheckBox.setEnabled(true/false)
)。
在此处查看更多信息: http : //docs.oracle.com/javase/tutorial/uiswing/events/itemlistener.html
听起来您想要做的是在第一行的每个复选框上添加一个项目侦听器,并让该侦听器在第二行中启用或禁用相应的复选框。
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;
}
作为使用侦听器的任何方法的替代方法,可以对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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.