小编典典

Java GridBagConstraints gridx和gridy无法正常工作?

java

我正在尝试使用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);

阅读 529

收藏
2020-11-26

共1个答案

小编典典

自从我完成了挥杆布局以来已经有一段时间了,但是如果您的JPanel中有多个JComponent,则gridX和gridY不会仅具有效果吗?看来您只有一个JButton,所以GridBagLayout没有任何布局。

2020-11-26