【问题标题】:How to organize my JPanel inside a JFrame?如何在 JFrame 中组织我的 JPanel?
【发布时间】:2016-06-15 13:42:14
【问题描述】:

我无法在 JFrame 中组织 JPanel。

我有 3 个JPanels,需要按如下方式组织它们:

面板 1 面板 2

面板__3333333

但是,只能水平对齐panel1和panel2如下:

 groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
        .addComponent(PANEL1)
        .addComponent(PANEL2));
    groupLayout.setVerticalGroup(groupLayout.createParallelGroup()
        .addComponent(PANEL1)
        .addComponent(PANEL2));  

谢谢。

【问题讨论】:

    标签: java swing layout-manager grouplayout


    【解决方案1】:

    实现这一点的最简单方法是将您的 JPanel 放在其他 JPanel 中。

    下面是一个你可以做的例子:

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    //this is the main JPanel that will house all of your child JPanels
    JPanel mainPanel= (JPanel)frame.getContentPane();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    //this JPanel will house "panel1" and "panel2" on top and will go inside the main panel
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
    
    //add panel1 and panel2 to topPanel here
    
    mainPanel.add(topPanel);
    
    //add panel3 to mainPanel here
    
    frame.pack();
    frame.setVisible(true);
    

    有很多不同的方法,但我发现这是最简单的。希望这会有所帮助!

    【讨论】:

    • 此解决方案有效并且面包对齐。还有一个疑问,我可以调整每个面板的大小吗?
    • 究竟为什么要调整 JPanel @bbariotti 的大小?我不知道手动调整 JPanel 大小的方法,如果有办法,当用户调整窗口大小时,它会弄乱 JPanel 的方向。如果您想更改 GUI 组件的位置和大小,我会尝试不同的布局并包含更多 JPanel。
    【解决方案2】:

    我认为您应该使用 GridBagLayout 而不是 grouplayout。 它符合您的需求

    See the oracle doc on gridbag layout here

    【讨论】:

      猜你喜欢
      • 2019-07-07
      • 2014-02-22
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 2011-09-22
      相关资源
      最近更新 更多