【问题标题】:Auto resizing a JFrame with pack() without collapsing its jPanels使用 pack() 自动调整 JFrame 的大小而不折叠其 jPanel
【发布时间】:2015-03-31 13:30:52
【问题描述】:

我正在尝试设计一个包含 2 个不同 JPanel 的 JFrame,一个在左侧带有 AbsoluteLayout,一个在右侧带有可变尺寸的 GridLayout。

在将一些组件添加到 JPanel 之后,我将它们添加到 JFrame contentPane 并使用方法 JFrame.pack() 希望获得一个可以显示其所有组件的最小尺寸的 JFrame,但我得到了什么是用 GridLayout 仅显示右侧的 JPanel 的最小尺寸,左侧的 JPanel 与右侧的 JPanel 重叠。

有什么好的方法可以使用 JFrame.pack() 方法,它仍然可以完整地显示两个 JPanel?

代码如下:

public class GameGUI extends JFrame{

   private int labSize;
   private JFrame mainFrame;
   private JPanel labPanel;
   private JPanel choicesPanel;
   private JButton exitButton;
   private JButton replayButton;

   public GameGUI(int n) {

        labSize=n;    
        mainFrame = new JFrame("Maze Game");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.getContentPane().setLayout(new GridLayout(1, 0));
        mainFrame.setVisible(false);    
        labPanel=new JPanel(new GridLayout(labSize,labSize));    
        choicesPanel=new JPanel(new GridLayout(0, 1));
        choicesPanel.setLayout(null);           
        replayButton=new JButton("Replay");
        replayButton.setBounds(10, 11, 80, 30);         
        exitButton=new JButton("Exit");
        exitButton.setBounds(10, 51, 80, 30);    
        choicesPanel.add(replayButton);
        choicesPanel.add(exitButton);           
        mainFrame.getContentPane().add(choicesPanel);
        mainFrame.getContentPane().add(labPanel);
    }

    public void refreshLabShowing(char[][] lab){

        labPanel.removeAll();    
        for(int i=0;i<labSize;i++){
            for(int u=0;u<labSize;u++){
                labPanel.add(new JLabel(String.valueOf(lab[i][u])));
            }
        }           
        mainFrame.pack();
        mainFrame.setVisible(true);
    }
}

【问题讨论】:

  • 不要使用null 布局。这就是问题的根源(以后可能会成为更多问题的根源)。 null 布局的面板没有合理的首选大小,因为计算通常是布局管理器的工作。你也可以覆盖getPreferredSize(),但在这种情况下你不应该使用布局管理器。
  • 请注意,使用GridLayoutEmptyBorder 的单列可以轻松布置两个绝对定位的按钮。为确保它们只占用所需的糊状空间,请将(面板)网格布局添加到具有FlowLayout 的另一个面板。这比尝试解决尝试绝对定位会导致的无数问题要容易得多。

标签: java swing layout-manager null-layout-manager


【解决方案1】:

pack() 仅适用于布局管理器,因为pack() 本身会向布局管理器查询所需的尺寸,所以在这里,您不能使用绝对布局和pack()

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2015-01-10
    • 2012-05-16
    • 2012-09-01
    相关资源
    最近更新 更多