本文介绍了Java GridBagConstraints gridx 和 gridy 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我错过了什么吗?

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

推荐答案

好久没做swing layout了,难道gridX和gridY不是只有在你的JPanel中有多个JComponent的时候才有效果吗?看来你只有一个 JButton,所以 GridBagLayout 没有任何布局可做.

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.

这篇关于Java GridBagConstraints gridx 和 gridy 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 11:02