Java 如何提醒配电盘它';在卡片布局中切换面板时,s可见

Java 如何提醒配电盘它';在卡片布局中切换面板时,s可见,java,swing,cardlayout,Java,Swing,Cardlayout,在我的程序框架内的JPanel的卡片布局中有两个JPanel(扩展JFrame),它们是ChooserPanel和ShowPanel 在ChooserPanel中,我选择一个数字显示在ShowPanel中,然后单击按钮更改程序框架中的面板,从ChooserPanel切换到ShowPanel。但是我如何才能优雅地通知按钮点击程序框架,这样它就可以切换JPanel,并将选择的号码传达给ShowPanel 我在选择器面板中放置了一个侦听器以通知按钮单击程序框架。如果这是最好的方式,那么我只需要知道如何

在我的程序框架内的JPanel卡片布局中有两个JPanel(扩展JFrame),它们是ChooserPanelShowPanel

ChooserPanel中,我选择一个数字显示在ShowPanel中,然后单击按钮更改程序框架中的面板,从ChooserPanel切换到ShowPanel。但是我如何才能优雅地通知按钮点击程序框架,这样它就可以切换JPanel,并将选择的号码传达给ShowPanel

我在选择器面板中放置了一个侦听器以通知按钮单击程序框架。如果这是最好的方式,那么我只需要知道如何将选择的号码传达到ShowPanel

我想做以下几件事:

public class ProgramFrame extends JFrame implements SwitchThePanelListener {

    private JPanel cardPanel;

    public ProgramFrame() {
        this.cardPanel = new JPanel();

        ChooserPanel chooser = new ChooserPanel(this); // passing the listener
        ShowPanel show = new ShowPanel();

        cardPanel.add(chooser, "chooser");
        cardPanel.add(show, "show");

        CardLayout layout = (CardLayout) cardPanel.getLayout();
        layout.show(cardPanel, "chooser");

        /** Code to set and show the layout **/
    }

    public void switchThePanelListener() {
        CardLayout layout = (CardLayout) cardPanel.getLayout();
        layout.show(cardPanel, "chooser");
    }

}
侦听器的代码:

选择器面板

public class ChooserPanel extends JPanel {

    public ChooserPanel(SwitchThePanelListener listener) {
        /** Code to set the layout and button to fire the listener **/
    }

}
public class ChooserPanel extends JPanel {

    public ChooserPanel() {
        /** Code to set the layout to show the number (how?) **/
    }

}
以及展示面板

public class ChooserPanel extends JPanel {

    public ChooserPanel(SwitchThePanelListener listener) {
        /** Code to set the layout and button to fire the listener **/
    }

}
public class ChooserPanel extends JPanel {

    public ChooserPanel() {
        /** Code to set the layout to show the number (how?) **/
    }

}

所以你有视图和控制器。现在你需要一个模型。在JGoodies库中,您可以找到一个很好的接口:ValueModel。看起来像

public interface ValueModel {
   Object getValue();
   void setValue(Object o);
   void addPropertyChangeListener(PropertyChangeListener pl);
   void removePropertyChangeListener(PropertyChangeListener pl);
}
控制器实例化一个ValueModel(JGoodies中的标准实现是ValueHolder)并将(集合)传输到两个面板。单击按钮并显示面板注册侦听器以获取有关值更改的通知后,ChooserPanel将值设置到模型中。如果要在面板之间传输多个属性(只需将所有这些值合并到一个对象中,并将其设置为ValueModel),或进行双向通信,请使用相同的方法