【问题标题】:Frame does not show Panels using MigLayout框架不显示使用 MigLayout 的面板
【发布时间】:2012-02-14 02:35:52
【问题描述】:

这可能是一个简单的错误,但我不知道出了什么问题。我有一个创建框架(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");

    }
}

谢谢!!

【问题讨论】:

    标签: swing jframe jpanel miglayout


    【解决方案1】:

    在 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);
    

    【讨论】:

    • 老实说,你的建议拯救了我的一天! :) 我不知道如何将面板拉伸到框架上,但是一旦我使用您的建议省略了那些嵌套面板,一切都变得清晰明了:)。非常感谢!
    猜你喜欢
    • 2016-04-26
    • 2016-09-14
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多