0

可能这是一个简单的错误,但我无法弄清楚出了什么问题。我有一个创建框架(MainFrame)并使用方法来更改面板的类。我有另一个类,其中描述了面板。但是,由于某种原因,我只能看到没有面板的框架。有人可以帮我吗?我是 MigLayout 的新手,如果您能解释我的错误,那就太好了。

public class MainFrame extends JFrame
{
private JPanel panel;

//getting dimensions
public static  Dimension dim = Toolkit.getDefaultToolkit().getScreenSize() ;

public MainFrame()
{
    getContentPane().setLayout(new MigLayout());
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.setTitle("Title");
    this.setLocation((int)dim.getWidth()/3,(int)dim.getHeight()/4);
    this.setSize(500, 500);     

    setNewPanel(new MainWindowPanel());
    this.validate();
}

public final void setNewPanel(JPanel newPanel)
{
    //to change the panel, old one has to be deleted
    if (panel != null) remove(panel);

    getContentPane().setLayout(new MigLayout());
    add(newPanel);

    //pack();
    panel = newPanel;
    this.setVisible(true);  
}
}

我的面板类

   public class MainWindowPanel  extends JPanel
   {
//Label
JLabel greeting = new JLabel("Welcome:");

//Buttons
JButton helpButton = new JButton("Help?");

public MainWindowPanel() 
{

    // the layout of the main screen
    JPanel p = new JPanel(new MigLayout("fill", "[center]"));

    p.setBackground(Color.lightGray);
    p.add(greeting,  "skip 1, gaptop 40, wrap");
    greeting.setFont(times20);

    p.add(helpButton, "bottom, span, tag help");

    }
}

谢谢!!

4

1 回答 1

2

在 MainWindowPanel 的构造函数中,您创建一个新面板并将按钮/标签添加到其中 - 无需添加新创建的面板。添加以下行:

 add(p);

实际上,我不太明白你想用那些深度嵌套的面板达到什么目的,为什么不呢?

 public MainWindowPanel() {
      setLayout(new MigLayout( ... contraints);
      add(greetings);
      add(button);
 }

当您使用它时:考虑扩展 JPanel 而是使用它:

 JComponent mainWindowPanel = new JPanel(new MigLayout(...));
 JLabel greetings = ... // create and configure
 mainWindowPanel.add(greetings); 
 JButton button = ... // create and configure
 mainWindowPanel.add(button);
于 2012-01-19T12:54:39.137 回答