【问题标题】:Add a gridLayout(2,2) in CENTER在 CENTER 中添加一个 gridLayout(2,2)
【发布时间】:2016-07-25 09:26:28
【问题描述】:

我想创建一个 gridLayout,在我的布局中心有 4 个按钮,以及一个用于 PAGE_END、PAGE_START、LINE_END、LINE_START 的按钮。我的代码确实显示了我告诉你的最后一个按钮,但没有显示网格按钮。

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Hello World!");
    frame.setSize(400,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    JPanel p = new JPanel(new BorderLayout());

    GridLayout grid = new GridLayout(2,2);
    p.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    JButton bg1 = new JButton("Button 1");
    p.add(bg1, c);
    JButton bg2 = new JButton("Button 2");
    p.add(bg2, c);
    JButton bg3 = new JButton("Button 3");
    p.add(bg3, c);
    JButton bg4 = new JButton("Button 4");
    p.add(bg4, c);

    frame.setLayout(new BorderLayout());        

    JButton b1 = new JButton("TOP");
    JButton b2 = new JButton("LEFT");
    JButton b3 = new JButton("RIGHT");
    JButton b4 = new JButton("BOTTOM");       

    frame.add(b1,BorderLayout.PAGE_START);
    frame.add(b2,BorderLayout.LINE_START);
    frame.add(b3,BorderLayout.LINE_END);
    frame.add(b4,BorderLayout.PAGE_END);
  }    
}

【问题讨论】:

    标签: java layout grid


    【解决方案1】:

    您已创建面板p,但尚未将其添加到框架中。

    在您的代码中添加这一行:

    frame.add(p,BorderLayout.CENTER);
    

    另外,如果你想要网格中的按钮,你必须使用这条线:

    p.setLayout(grid);
    

    而不是p.setLayout(new GridBagLayout());

    【讨论】:

    • 首先感谢您的帮助。我确实添加了这一行,但网格按钮/面板仍然没有显示。我还添加了p.setVisible(true);,但仍然无法正常工作。
    • @iraklis.s 你在哪里添加了这一行?
    • JPanel p = new JPanel(new BorderLayout()); frame.add(p,BorderLayout.CENTER); p.setVisible(true);
    • @iraklis.s 我在您添加其他组件(b1、b2...)之前正好添加了这一行。它工作正常。
    • 哦,是的!谢谢!!那么现在,如何使这些按钮在顶部为 2,在底部为 2?因为现在他们在排队。我想要 2 行 2 个按钮。
    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多