如何解决无法跨越和左对齐 GridBagLayout 中的文本字段
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public test() {
setLocationByPlatform(true);
setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationByPlatform(true);
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.LINE_START;
constraints.insets = new Insets(5,5,5);
JRadioButton button1 = new JRadioButton("Aaaaaaaaa");
JRadioButton button2 = new JRadioButton("Bbbb");
JRadioButton button3 = new JRadioButton("cccccC");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(new JLabel("Test"),createConstraints(0,0));
panel.add(button1,1));
panel.add(button2,createConstraints(1,1));
panel.add(button3,createConstraints(2,1));
JTextField text = new JTextField();
GridBagConstraints c = createConstraints(0,2);
c.gridwidth = 3;
panel.add(text,c);
add(panel,BorderLayout.PAGE_START);
setSize(350,360);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokelater(() -> {
Test frame = new test();
frame.setVisible(true);
});
}
private GridBagConstraints createConstraints(int x,int y) {
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(5,5);
c.gridx = x;
c.gridy = y;
return c;
}
}
它创建:
但我需要文本字段始终跨越 2 列并且所有内容都要左对齐:
我该怎么做?
解决方法
c.gridwidth = 3;
必须:
c.gridwidth = 2; // unless it should fill all THREE columns!
c.fill = GridBagConstraints.HORIZONTAL;
结果:
编辑
顺便说一句。 “跨越两个单元格”似乎是一种完全随意调整文本字段大小的方法。最好在构建时指定多列(大致转换为字符数),将其放在自己的一行中(跨越 3 个单元格宽度),不要指定它来填充行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。