JPanelを拡張するカスタムクラスCustomFieldがあります。私はしばしば同じパターンを再利用しなければならないので、私のカスタムクラスは2つのJLabelsと2つのJComboBoxで作られています。 これはとても簡単です。最初のJComboBoxにはON/OFFの選択肢があり、2番目のJComboBoxは最初の「ON」に設定されている場合にのみ表示されます。私はこの部分を管理することができます。 しかし、誰がそれをうまく設計するかわからない部分は、CustomFieldインスタンスがメインのJFrameである別のクラスにあり、このJFrameでは、CustomFieldクラスのJComboBoxが "に"。私はMouseAdapterの使用について考えましたが、それは良い習慣であるかどうかわかりません。リスナーをJPanelに追加する
は、ここに私た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がvisibilyたCustomFieldの設定に応じて変化することにしたいです。それが行われる方法で、私はcustomFieldクラスにlabelTestを配置できません。
私がしたいことをするためのきれいな方法はありますか?私は実際のものを再設計し、すべてのフィールドを同じクラスに入れるべきですか?
ありがとうございます!あなたは様々なスイングのドキュメントにメソッドのシグネチャを見ることで行われている状態のリスニング方法についてのアイデアを得ることができます
public boolean isOn() {
return testCB.getSelectedIndex() == 1;
}
:
カスタムコンポーネントの状態が変更されたことを関係者に通知できる 'ChaneListener'または' ActionListener'を実装します。 – MadProgrammer
"最初のJComboBoxにはON/OFFの選択肢があります"なぜJToggleButtonを使用しないのですか? –