我对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空间?
答案 0 :(得分:2)
看看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
,因为这会调整窗口大小,以便尊重内容大小