Java更改GridLayout中的JTextField大小 [英] Java change JTextField size inside a GridLayout

查看:505
本文介绍了Java更改GridLayout中的JTextField大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有2个JLabel,2个JTextField和一个JButton的GridLayout(3,2).我将它们添加为图片或代码中所示.一切都很好,但是JTextField的大小太大了,我希望它能像我画的红线所示.我试过说jtf3.setPreferredSize( new Dimension( x, y ) );,但它根本没有改变尺寸.另一种解决方案是例如使GridLayout稍微GridLayout(3,2,1,50)(通过添加50),但这也将JLabels移到顶部.我只想完全如图片所示...有什么想法吗?非常感谢

I have a GridLayout(3,2) as follows with 2 JLabels, 2 JTextFields and a JButton. I add them as shown in the pic or code. Everything is just fine but the JTextField size is too big and I want it to be as shown by the red lines I've drawed. I have tried saying jtf3.setPreferredSize( new Dimension( x, y ) ); but it didn't change the dimension at all. One other solution was to make the GridLayout somewhat GridLayout(3,2,1,50) for example (by adding 50) but that moves the JLabels way top too... I just want to be exactly as shown in the pic... Any ideas? Thanks a lot

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.

That's how GridLayout works, it provides equal space to all the components. Instead, consider using a GridBagLayout instead.

有关更多详细信息,请参见如何使用GridBagLayout >

See How to Use GridBagLayout for more details

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大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆