问题描述
以下是代码:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TestGrid {
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 panel = new JPanel();
panel.setLayout(new GridLayout(4, 9));
panel.setMaximumSize(new Dimension(9*30-20,4*30));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 30));
panel.add(btn);
}
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 10));
panel.add(btn);
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 30));
panel.add(btn);
}
}
mainPanel.add(panel);
frame.add(mainPanel);
frame.setSize(450,950);
frame.setVisible(true);
}
}
我想有一个4行按钮表和9列。中间列应该比其他列窄。我试过 Dimension(30,10)
和 Dimension(30,10)
都对宽度没有影响中间栏。为什么?
I suppose to have a table of buttons with 4 rows and 9 columns. And the middle column should be narrower that other columns. I tried Dimension(30, 10)
and Dimension(30, 10)
both have no effect on the width of the middle column. Why?
推荐答案
布局管理员可以自由地忽略首选大小。具体来说, GridLayout
将始终使网格中的每个单元格大小完全相同(因为这个原因,它是一个非常无用的布局管理器)。
Layout managers are free to ignore the preferred size. Specifically, GridLayout
will always make each cell in the grid exactly the same size (it's a pretty useless layout manager for that reason).
您必须使用不同的布局管理器,例如嵌套 BoxLayout
或 GroupLayout
。
You'll have to use a different layout manager, such as nested BoxLayout
or a GroupLayout
.
这篇关于为什么setPreferredSize不会改变按钮的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!