在Java / Swing中更改按钮位置

时间:2017-07-26 19:25:07

标签: java swing jframe

我正在尝试使用Java中的Gridbagconstraints中的LayoutManager在我的GUI中添加按钮。无论坐标如何,按钮的位置始终位于 center 中。

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

public class Gui {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    frame.add(panel);
    panel.setLayout(new GridBagLayout());
    frame.setSize(600,600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);

    GridBagConstraints gbc = new GridBagConstraints();

    JButton b = new JButton("Hello");
    gbc.gridx=1;
    gbc.gridy=1;
    panel.add(b,gbc);

    JButton v = new JButton("exit");
    gbc.gridx=1;
    gbc.gridx=0;
    panel.add(v,gbc);

}
}

输出

enter image description here

问题

如何定义按钮的坐标并将它们放在所需的位置?

1 个答案:

答案 0 :(得分:2)

您需要为weightx对象设置weightyGridBagConstraints

  

除非您为weightx或weighty指定至少一个非零值,否则所有组件在其容器的中心聚集在一起。这是因为当权重为0.0(默认值)时,GridBagLayout会在其单元格网格与容器边缘之间放置任何额外空间。   How to Use GridBagLayout

如果您希望继续使用Java中的GUI,我建议您仔细阅读本教程以及其他swing布局管理器上的GUI,因为它们需要很高的熟练程度才能正常使用。

相关问题