如何设置按钮的大小?
2022-09-01 06:45:25
我把我的按钮放在带有GridLayout的JPane中。然后我把JPanel放到另一个带有BoxLayout.Y_AXIS的JPanel中。我希望 GridLayout 中的按钮是方形的。我使用tmp.setSize(30,30),它不起作用。我也尝试使用,但我无法弄清楚X和Y是什么。那么,做这些事情的正确方法是什么?new GridLayout(X, Y, 4, 4)
添加:
我仍然无法解决问题。以下是我正在尝试执行的操作的代码:
import javax.swing.*;
import java.awt.*;
public class PanelModel {
public static void main(String[] args) {
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(100, 100));
firstPanel.add(btn);
}
}
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
secondPanel.add(btn);
}
}
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.add(mainPanel);
frame.setSize(400,600);
frame.setVisible(true);
}
}
问题是Java试图使宽度等于和!此外,Java试图填充窗口的所有高度。如何删除此行为?firstPanel
secondPanel