【问题标题】:Java GridBagConstraints gridx and gridy not working?Java GridBagConstraints gridx 和 gridy 不起作用?
【发布时间】:2012-01-14 03:23:00
【问题描述】:

我正在尝试使用gridxgridy 约束来定位我的按钮。但他们不工作!如果我更改 gridxgridy 变量,什么也不会发生。如果我将填充更改为GridBagConstraintsNONE,它仍然不起作用。

我错过了什么吗?

import java.awt.*;
import javax.swing.*;

public class Window extends JFrame{
    private static final long serialVersionUID = 1L;

    JFrame frame = new JFrame("GUI");
    JTextField username = new JTextField(20);

    public void CreateWindow(){
        JPanel pane = new JPanel();
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.NONE;

        JButton button = new JButton("Button 1");
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.gridx = 3;   //Has no effect
        c.gridy = 5;   //Has no effect
        c.anchor = GridBagConstraints.NORTHWEST;//If I remove this, it still does not work.
        pane.add(button, c);                    
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setSize(400, 600);
        frame.setResizable(true);           
        frame.setLocationRelativeTo(null);          
        frame.add(pane);
        frame.setVisible(true);    
    }
}

如果这很难阅读,问题就出在这里:

JPanel pane = new JPanel();
            pane.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();

            c.fill = GridBagConstraints.NONE;

            JButton button = new JButton("Button 1");
            c.weightx = 1.0;
            c.weighty = 1.0;
            c.gridx = 3;   //Has no effect
            c.gridy = 5;   //Has no effect
            c.anchor = GridBagConstraints.NORTHWEST;    //If I remove this, it still does not work.
            pane.add(button, c);

【问题讨论】:

  • ._. gridx 和 gridy 不影响按钮。你甚至读过这个问题吗?
  • @Ken,您能给我们提供所需布局的可视化表示吗?也许那时我们可以建议不同的(更合适的)布局管理器......
  • gridx和gridy不改变按钮位置。

标签: java swing awt jframe jpanel


【解决方案1】:

我已经有一段时间没有做 Swing 布局了,但是 gridX 和 gridY 不是只有在 JPanel 中有多个 JComponent 时才有效果吗?看来你只有一个 JButton,所以 GridBagLayout 没有任何布局可做。

【讨论】:

  • 我相信凯恩是正确的。尝试在其他位置添加一些空的 JLabel,看看是否能得到更好的结果。还要阅读 weightx 和 weighty 设置。如果没有这些,您的组件将在框架的中心组合在一起。
  • 我不太确定。所以你是说我必须添加另一个 JComponent?我正在学习一个教程,它在那里工作。
  • 你能发布你正在使用的教程吗?
  • 嘘!很高兴我们能提供帮助。您应该接受答案,让阅读它的其他人知道解决方案。
  • Kane,我遇到了同样的问题,但是这次我的面板中有多个 Jcomponents 并且网格 x 和网格 y 无法正常工作,也没有反映任何变化。还有一点,我在渲染这个 UI 时使用了 swixml。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多