Java中的三态复选框 [英] Tristate Checkboxes in Java
问题描述
我真的可以在Java中使用一个三重复选框。这听起来像一个简单的事情,但我只看到了真正的丑陋的实现 [note:link now broken]。
I could really use a tri-stated checkbox in Java. It sounds like a simple thing, but I've only seen really ugly implementations [note: link now broken].
三个单选按钮占用了太多的房地产,可能会让我的用户感到困惑。它基本上是一个搜索对话框。我需要真,假或不关心选项。有人使用不同的技术吗?
Three radio buttons just take up too much real estate and will probably be confusing for the users in my case. It's basically for a search dialog. I need true, false or "don't care" options. Is there a different technique that people use?
推荐答案
我发现了一个方法来通过简单地添加一个监听器:
I found a way to make a tri-state checkbox by simply adding a listener:
public class TriStateActionListener implements ActionListener{
final protected Icon icon;
public TriStateActionListener(Icon icon){
this.icon=icon;
}
public static Boolean getState(javax.swing.JCheckBox cb){
if (cb.getIcon()==null) return null;
if (cb.isSelected()) return true;
else return false;
}
public void actionPerformed(ActionEvent e) {
javax.swing.JCheckBox cb=(javax.swing.JCheckBox)e.getSource();
if (!cb.isSelected()){
cb.setIcon(icon);
}
else if (cb.getIcon()!=null){
cb.setIcon(null);
cb.setSelected(false);
}
}
}
然后在应用程序代码中,它只是一行:
Then in the application code, it's just a single line:
jCheckBox1.addActionListener(new TriStateActionListener(getResourceMap().getIcon("TriStateIcon")));
经过所有反馈,我认为下拉菜单可能是更好的选择。但是,我想在这里为其他人分享我的代码。
After all the feedback, I'm thinking a drop-down may be a better choice. But, I wanted to share my code here for everyone else.
这篇关于Java中的三态复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!