JFrame实例不可视化添加的组件

时间:2014-11-20 17:57:42

标签: java swing jframe jcomponent

我创建了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();

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

我更改了代码并放了:

public 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);
  }

现在它在另一个框架中打开它,但只显示添加的最后一个组件。太奇怪了..

1 个答案:

答案 0 :(得分:1)

您没有正确实施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();

它避免创建多个类的实例。