Java在GridLayout中更改JTextField大小

时间:2014-12-09 23:51:05

标签: java swing awt layout-manager grid-layout

我有一个GridLayout(3,2),如下所示,包含2个JLabel,2个JTextField和一个JButton。我按照图片或代码中的说明添加它们。一切都很好,但JTextField的尺寸太大了,我希望它如我绘制的红线所示。我试过说jtf3.setPreferredSize( new Dimension( x, y ) );,但它根本没有改变维度。另一个解决方案是使GridLayout稍微GridLayout(3,2,1,50)(通过添加50),但这也使JLabels的方式也移动到顶部......我只想完全如图所示......任何想法?非常感谢

enter image description here

JPanel copying_panel = new JPanel();
copying_panel.setLayout(new GridLayout(3, 2));
copying_panel.setBackground(new Color(200, 221, 242));
JLabel jl4 = new JLabel("From:", SwingConstants.CENTER);
JTextField jtf3 = new JTextField();
JLabel jl5 = new JLabel("To:", SwingConstants.CENTER);
JTextField jtf4 = new JTextField();
JLabel jl6 = new JLabel();
JButton jb2 = new JButton("Go");

copying_panel.add(jl4);
copying_panel.add(jtf3);
copying_panel.add(jl5);
copying_panel.add(jtf4);
copying_panel.add(jl6);
copying_panel.add(jb2);

1 个答案:

答案 0 :(得分:3)

这就是GridLayout的工作原理,它为所有组件提供了相等的空间。相反,请考虑改为使用GridBagLayout

有关详细信息,请参阅How to Use GridBagLayout

JPanel copying_panel = new JPanel();
copying_panel.setLayout(new GridBagLayout());
copying_panel.setBackground(new Color(200, 221, 242));
JLabel jl4 = new JLabel("From:", SwingConstants.CENTER);
JTextField jtf3 = new JTextField(10);
JLabel jl5 = new JLabel("To:", SwingConstants.CENTER);
JTextField jtf4 = new JTextField(10);
JButton jb2 = new JButton("Go");

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
copying_panel.add(jl4, gbc);

gbc.gridy++;
copying_panel.add(jl5, gbc);

gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx++;
gbc.gridy = 0;
copying_panel.add(jtf3, gbc);

gbc.gridy++;
copying_panel.add(jtf4, gbc);

gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.NONE;
gbc.gridy++;
copying_panel.add(jb2, gbc);