如何填充整个Jframe



我对Java中的gui相当陌生。我想知道的是,是否有一种方法可以取两个JPanels并将其分成JFrame,即。面板1 70%,面板2 30% ?

下面是我创建GUI的代码片段:

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
public class ButtonGrid extends Game
{
private static JFrame frame = new JFrame();
private static JPanel panel1 = new JPanel();
private static JPanel panel2 = new JPanel();
private static JPanel panel3 = new JPanel();
private static JPanel panel4 = new JPanel();
private static JLabel lblP1 = new JLabel("Player 1: ");
private static JLabel lblP2 = new JLabel("Player 2: ");
private static JLabel P1Score = new JLabel("0");
private static JLabel P2Score = new JLabel("0");
public static JButton grid[][];
public ButtonGrid(int width, int length)
{
    frame.setLayout(new GridLayout(width, length));

    panel1.setLayout(new GridLayout(width, length));
    panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
    panel3.setLayout(new BoxLayout(panel3, BoxLayout.X_AXIS));
    panel4.setLayout(new BoxLayout(panel4, BoxLayout.X_AXIS));
    lblP1.setForeground(Color.blue);
    lblP2.setForeground(Color.red);
    grid = new JButton[width][length];
    for(int x=0; x<length; x++)
    {
        for(int y=0; y<width; y++)
        {
            grid[x][y] = new JButton();
            grid[x][y].addActionListener(actionListener);
            grid[x][y].setName("[" + x + ',' +y + "]");
            //grid[x][y].setText(grid[x][y].getName());
            //frame.add(grid[x][y]);
            panel1.add(grid[x][y]);
        }
    }
    grid[0][0].setBackground(Color.blue);
    grid[width-1][length-1].setBackground(Color.red);
    panel3.add(lblP1);
    panel3.add(P1Score);
    panel4.add(lblP2);
    panel4.add(P2Score);
    panel2.add(panel3);
    panel2.add(panel4);

    frame.add(panel2);
    frame.add(panel1);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setVisible(true);
    frame.setResizable(false);
}

我想要的是按钮的大小均匀,填充到底部,现在有大约2/3的空白空间在框架中。我如何用按钮填充框架中剩下的2/3的空间?

看看GridBagLayout,它允许您指定应该应用于每个组件的权重。

例如…

JPanel top = new JPanel();
top.setBorder(new LineBorder(Color.RED));
JPanel bottom = new JPanel();
bottom .setBorder(new LineBorder(Color.BLUE));
JPanel parent = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0.7;
gbc.fill = GridBagConstraints.BOTH;
parent.add(top, gbc);
gbc.gridy++;
gbc.weighty = 0.3;
parent.add(bottom, gbc);

指出:

  • 不要过度使用static,在你的代码中不需要任何static引用,因为它们都是private
  • 不要在JPanel(或任何其他类型的容器)中创建框架。组件不应该关心它可能被使用的地方,这是一个外部决定…
  • 使用setResizable将改变可视区域的大小,应该在设置窗口大小之前完成。你应该依靠pack而不是setSize,因为这将调整窗口的大小,使内容大小被尊重

相关内容

  • 没有找到相关文章

最新更新