我正在尝试制作一个布局,其中有 4 个正方形,形成一个更大的正方形,下面有一个按钮横跨整个正方形。
我尝试了 GridLayout
,完美地创建了正方形,但按钮没有拉伸(stretch)到屏幕上。
我也尝试过GridBagLayout
,但是有间距,而且正方形很小,这很糟糕。
PS:按钮为button1、button2、button3、button4,对于正方形,start对于底部按钮。
此外,我希望正方形为 400x400。
我的代码与GridLayout
:
this.setLayout(new GridLayout(3,2));
button1 = new JButton();
//button1.setBackground(Color.green);
button1.setBounds(0, 0, 200, 200);
button2 = new JButton();
//button2.setBounds(0, 200, 200, 200);
button2.setBackground(Color.red);
button3 = new JButton();
//button3.setBackground(Color.yellow);
button3.setBounds(200, 0, 200, 200);
button4 = new JButton();
//button4.setBounds(200, 200, 200, 200);
button4.setBackground(Color.blue);
start = new JButton("Start");
//start.setBounds(300, 300, 100, 100);
this.add(button1);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(start);
最佳答案
尝试使用组件布局...BorderLayout
和 GridLayout
的组合应该可以为您提供所需的结果。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FourSquare {
public static void main(String[] args) {
new FourSquare();
}
public FourSquare() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel squarePane = new JPanel(new GridLayout(2, 2));
JPanel controlPane = new JPanel(new BorderLayout());
squarePane.add(new JButton("1"));
squarePane.add(new JButton("2"));
squarePane.add(new JButton("3"));
squarePane.add(new JButton("4"));
controlPane.add(squarePane);
controlPane.add(new JButton("Bottom"), BorderLayout.SOUTH);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(controlPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
关于java - Swing:需要 FourSquare 和底部按钮布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093685/