【发布时间】:2012-02-19 05:07:46
【问题描述】:
我正在尝试在 Java Swing 中构建一个 MVC 应用程序。我有一个包含四个 JComboBoxes 的 JPanel,这个 JPanel 嵌入到父 JPanel 中。父 JPanel 除了子 JPanel 之外还有其他控件。
每当我更改 JComboBoxes 的值时,子 JPanel 的模型都会正确更新(它基本上是一个日期选择器,每个组合框分别用于年、月、月中的某天和某天的某个小时)。我想不通的是,每当其中一个 JComboBoxes 发生更改时,我如何触发父 JPanel 的模型更新自身以匹配存储在子 JPanel 模型中的值。
下面是我目前所拥有的结构的精简 SSCCE。谢谢。
import java.awt.event.*;
import javax.swing.*;
public class Example extends JFrame {
public Example() {
super();
OuterView theGUI = new OuterView();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
add(theGUI);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Example();
}
});
}
}
class OuterView extends JPanel {
public OuterView() {
super();
InnerView innerPanel = new InnerView();
JButton button = new JButton("display OuterView's model");
button.addActionListener(new ButtonListener());
add(innerPanel);
add(button);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("button was clicked");
}
}
}
class InnerView extends JPanel {
public InnerView() {
super();
String[] items = new String[] {"item 1", "item 2", "item 3"};
JComboBox comboBox = new JComboBox(items);
comboBox.addActionListener(new ComboBoxListener());
add(comboBox);
}
private class ComboBoxListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
String text = ((JComboBox) ae.getSource()).getSelectedItem().toString();
System.out.println("store " + text + " in InnerView's model");
System.out.println("now how do I cause OuterView's model to be updated to get the info from InnerView's model?");
}
}
}
【问题讨论】:
-
父级应该在子级模型上有一个监听器。
-
或者您可以将事件转发给父级,如图here。
标签: java swing jpanel jcombobox propertychangelistener