JPanel:需要布局帮助

聚合

我想构建这个布局:

它由一个标签、一个文本字段、2 个按钮和一个可变高度的文本区域(从 1 行到 40 多行)组成。我正在尝试使用 aGridBagLayout没有成功。按钮在彼此之上,我不知道如何设置每个元素的大小并且它们之间没有空间。这是到目前为止的代码:

    GridBagLayout gridbag = new GridBagLayout();
    this.setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    gridbag.setConstraints(lblGuidelines, c);
    this.add(lblGuidelines);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 4;
    gridbag.setConstraints(txtNumberInput, c);
    this.add(txtNumberInput);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 2;
    c.weightx = 0.5;
    gridbag.setConstraints(btnCheck, c);
    this.add(btnCheck);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 2;
    c.weightx = 0.5;
    gridbag.setConstraints(btnClear, c);
    this.add(btnClear);

    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 4;
    gridbag.setConstraints(textArea, c);
    this.add(textArea);
疯狂程序员

就像是...

就像是

基本上,您需要gridx将第二个按钮位置设置1而不是0此外,指定gridwidth列不存在的位置毫无意义,它可能会导致问题,但大多数情况下,这些列的虚拟宽度为0,因此不会有太多意义

GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;

JLabel lblGuidelines = new JLabel("Please neter a telephone number and check if it's valid or not");
JTextField txtNumberInput = new JTextField(12);
JButton btnCheck = new JButton("Check");
JButton btnClear = new JButton("Clear");
JTextArea textArea = new JTextArea(20, 12);

c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.insets = new Insets(8, 8, 8, 8);
c.weightx = 1;
this.add(lblGuidelines, c);

c.gridx = 0;
c.gridy = 1;
this.add(txtNumberInput, c);

c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.weightx = 0.5;
this.add(btnCheck, c);

c.gridx = 1;
c.gridy = 2;
this.add(btnClear, c);

c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.weightx = 1;
this.add(new JScrollPane(textArea), c);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章