我创建了SelectMethodFrame,它扩展了只能具有一个实例的JFrame:

public class SelectMethodFrame extends JFrame {

  private JSplitPane mainWindow = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

  public JSplitPane getMainWindow() {
    return mainWindow;
  }

  public void setMainWindow(JSplitPane mainWindow) {
    this.mainWindow = mainWindow;
  }

  private static SelectMethodFrame instance = null;



  public static SelectMethodFrame getInstance() {
    if (instance == null)
        instance = new SelectMethodFrame();
    return instance;
 }


  public void setTab(JComponent panelConsumption, JComponent panelCpu,
        JComponent panelMemo, JComponent panelScreen,
        JComponent panelMobile, JComponent panelWifi) {

    TabbedView tab = new TabbedView(panelConsumption, panelCpu, panelMemo,
            panelScreen, panelMobile, panelWifi);


    mainWindow.setRightComponent(tab);


}

  public void setTree(JTree tree) {

    mainWindow.setLeftComponent(new JScrollPane(tree));

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    getContentPane().add(mainWindow, java.awt.BorderLayout.CENTER);
    setExtendedState(MAXIMIZED_BOTH);
    setMinimumSize(new Dimension(800, 500));
    this.setTitle(Constants.APP_CHECKBOXTREE);
  }

}


我以这种方式在一类中创建框架:

SelectMethodFrame frame = new SelectMethodFrame();

frame.setTree(treeSelection);


一切正常,但是当我想在另一个类的框架中添加另一个组件时:

SelectMethodFrame.getInstance().setTab(panelConsumption, panelCpu,
    panelMemo, panelScreen, panelMobile, panelWifi);


它没有显示出来。我尝试过

SelectMethodFrame.getInstance().repaint();
SelectMethodFrame.getInstance().revalidate();


但这不起作用。仅在构造函数中创建时才显示组件。问题出在哪里?

我更改了代码并放入:

公共SelectMethodFrame(){

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    getContentPane().add(mainWindow, java.awt.BorderLayout.CENTER);
    setExtendedState(MAXIMIZED_BOTH);
    setMinimumSize(new Dimension(800, 500));
    this.setTitle(Constants.APP_CHECKBOXTREE);

}


代替在

public void setTree(JTree tree) {

    mainWindow.setLeftComponent(new JScrollPane(tree));

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    getContentPane().add(mainWindow, java.awt.BorderLayout.CENTER);
    setExtendedState(MAXIMIZED_BOTH);
    setMinimumSize(new Dimension(800, 500));
    this.setTitle(Constants.APP_CHECKBOXTREE);
  }


现在,它在另一个框架中将其打开,但仅显示最后添加的组件。好奇怪

最佳答案

您没有正确实现singleton模式。

SelectMethodFrame类中,将构造函数设置为private:

public class SelectMethodFrame extends JFrame {
    private SelectMethodFrame (){}
    ...
}


在类中对单例的所有引用(而不是this)中,请使用instance变量,例如:

instance.pack();
instance.setLocationRelativeTo(null);
instance.setVisible(true);
//etc...


这样,您将无法从外部呼叫new SelectMethodFrame()。所以与其:

SelectMethodFrame frame = new SelectMethodFrame();


您应该使用:

SelectMethodFrame frame = SelectMethodFrame.getInstance();


它避免了创建一个以上的类实例。

07-27 13:43