我對Java中的圖形用戶界面相當陌生。我想知道的是,有沒有辦法取兩個JPanels
並將它分成JFrame
,即。面板1爲70%,面板2爲30%?如何填充整個Jframe?
這是從我創造我的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空間的其餘部分?
我認爲MigLayout或瘋狂的回答 – nachokk
不要過度使用'static'你應該依靠
pack
而不是setSize
,因爲這樣會調整窗口大小,有沒有必要進行任何的您的代碼中存在'static'參考,因爲它們都是'private' ... – MadProgrammer