[英]Java Swing - how to update GUI Objects ie. JTextField value from sub class in same package
我有一個在Swing中設計的GUI,其中包含了所有組件。 例如,我有一個帶有JList和JTextField的JComboBox,
當我從JComboBox中選擇一個不同的項時,我試圖使用ListSelectionListener來調用子類中的方法來根據選擇更新JTextField,
我將如何正確地做到這一點? 如何調用子類,然后從子類更新GUI對象的值?
public class Parent {
private void init() {
// ...
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = combo.getSelectedItem();
textField.setText(getTextBasedOnSelection(selected));
}
});
// ...
}
/**
* Returns the text to display when the given object is selected.
* Subclasses may override this method to display what they want
*/
protected String getTextBasedOnSelection(Object selected) {
return selected.toString();
}
// ...
}
我希望我能解決你的問題。 您有一個包含多個子視圖的視圖組件,並且您希望更新一個子視圖,因為在另一個子視圖中進行了更改。
因此,您可以在主視圖中為組合框編寫一個動作偵聽器:
comboBox.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
textField.setText(comboBox.getSelectedItem());
}
});
我建議不要直接互連組件,而是應用Mediator模式 :創建一個JPanel的子類(例如XyzPane),放置所有組件。此類成為Mediator。 它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.