Java 更改 GridLayout 内的 JTextField 大小

标签 java swing awt layout-manager grid-layout

我有一个 GridLayout(3,2),如下所示,带有 2 个 JLabels、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);

最佳答案

这就是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);

关于Java 更改 GridLayout 内的 JTextField 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391049/

相关文章:

java - 连接字符串的自定义方法与不使用该方法

java - 如果找到的值超过最大值,则使用 DocumentFilter 自动设置为最大值的 JTextField

java - 使用多个自定义表格模型避免重复代码

java - 无法理解和解决此程序的方法覆盖错误

java - 用于 JavaFX Scene Builder 拖放的 IntelliJ IDEA 插件停止工作

java - 错误 : Client does not support authentication protocol requested by server; consider upgrading MySQL client

java - SqlExceptionHelper : Cursors are not supported on a table which has a clustered columnstore index

java - 我如何使用这个 Java GUI API 来绘制东西?

java - 让另一个类在 actionListener 中工作

java - 每次其他选择框发生变化时,如何更新我的选择框?