【发布时间】:2016-05-20 19:26:59
【问题描述】:
我有一个扩展 JPanel 的自定义类 CustomField。由于我经常不得不重用相同的模式,因此我的自定义类由 2 个 JLabels 和 2 个 JComboBox 组成。 这很简单;第一个 JComboBox 有 ON/OFF 选项,第二个 JComboBox 只有在第一个设置为“ON”时才可见。我可以管理这部分。 然而,我不知道谁来设计它的部分是 CustomField 实例位于另一个主 JFrame 类中,并且在这个 JFrame 中,某些部分只有在 CustomField 类中的 JComboBox 设置为“ON”时才可见”。我考虑过使用 MouseAdapter,但我不知道这是一个好习惯。
这是我的 CustomField 类:
public class CustomField extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel text, portText;
JComboBox<String> testCB, option;
public CustomField(String text, String opt, String tst) {
this.text = new JLabel(text);
String[] onOffOpt= {"OFF", "ON"};
this.option = new JComboBox<String>(onOffOpt);
this.option.setSelectedItem(opt);
this.option.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent ie) {
portText.setVisible(option.getSelectedIndex() == 1);
testCB.setVisible(option.getSelectedIndex() == 1);
}
});
this.portText = new JLabel("Test:");
String[] testChoices = {"Test", "Test2"};
this.testCB = new JComboBox<String>(testChoices);
this.testCB.setSelectedItem(tst);
this.setLayout(new FlowLayout());
add(this.text);
add(this.option);
add(this.portText);
add(this.testCB);
}
}
这是主要的 JFrame:
public class Main {
CustomField cf = new CustomField("test", "ON, "Test2");
public static void main(String s[]) {
JFrame frame = new JFrame("Application");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(cf);
JLabel labelTest = new JLabel("Label that should be visible or not");
panel.add(labelTest);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
基本上,我希望 labelTest 根据 CustomField 设置明显变化。在它的制作方式上,我无法将 labelTest 放在 CustomField 类中。
有没有一种干净的方式来做我想做的事?我应该重新设计实际的东西并将所有字段放在同一个类中吗?
谢谢!
【问题讨论】:
-
实现
ChaneListener或ActionListener可以通知相关方您的自定义组件的状态已更改 -
"第一个 JComboBox 有 ON/OFF 选项" 为什么不使用 JToggleButton?