我想在Java Swing中构建一个MVC应用程序。我有一个包含四个JComboBox的JPanel,并且这个JPanel嵌入到父JPanel中。父JPanel除了子JPanel之外还有其他控件。当孩子JPanel中的组件被更新时如何在父JPanel中触发一个动作(Java Swing)
只要我更改JComboBoxes的值(它基本上是一个日期选择器,每个年份,月份,月份中的某一天以及每个小时都有一个组合框),就可以正确更新子项JPanel的模型。我无法弄清楚的是,只要其中一个JComboBox发生更改,我就可以触发父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?");
}
}
}
父母应该在孩子的模型上有一个监听器。 – 2012-02-19 05:10:39
或者您可以将事件转发给父代,如[此处](http://stackoverflow.com/q/2159803/230513)所示。 – trashgod 2012-02-19 05:18:21