Java GridBagConstraints gridx and gridy not working?

落爺英雄遲暮 提交于 2019-12-02 08:11:03

问题


I am trying to use the gridx and gridy constraints to position my button. But they do not work! If I change the gridx and gridy variables, nothing happens. If I change the fill to GridBagConstraints to NONE, it still does not work.

Am I missing something here?

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);    
    }
}

If that is hard to read, here is where the problem lies:

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);

回答1:


It's been a while since I've done swing layouts, but don't gridX and gridY only have effects if you have more than one JComponent in your JPanel? It seems you only have a JButton, so the GridBagLayout doesn't have any layout to do.



来源:https://stackoverflow.com/questions/8401367/java-gridbagconstraints-gridx-and-gridy-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!