有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java GridBagLayout在JPanel中,组件不会改变x | | y位置

我正在尝试创建自己的GUI,尝试将playerWinsJLabel移到最右边。我尝试过改变x和y坐标,但JLabel保持不变。我想知道这是否与以JPanel为中心有关

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

public class DieIntGUI extends JFrame {

    public DieIntGUI(String title) {
        super(title);
        setSize(700, 700);
        getContentPane().setBackground(Color.white);
        setLayout(new BorderLayout());
        initComponents();
        add(panel);
        add(errorMessages, BorderLayout.SOUTH);
        setLocationRelativeTo(null);

   }

    public static void main(String[] args) {
        DieIntGUI frame = new DieIntGUI("Dice Game");
        frame.setVisible(true);
    }

    private void initComponents() {
        panel = new JPanel();
        errorMessages = new JLabel("T");
        playerWins = new JLabel("F");
        computerWins = new JLabel("S");

        drawComponents();
    }


    private void drawComponents() {

        GridBagConstraints gbc = new GridBagConstraints();

        panel.setLayout(new GridBagLayout());
        panel.setSize(700, 700);

        panel.setBackground(Color.white);

        gbc.gridx = 2;
        gbc.gridy = 17;

        panel.add(playerWins, gbc);

    }

    private JPanel panel;
    private JLabel errorMessages;
    public JLabel playerWins, computerWins;


}

共 (2) 个答案

  1. # 1 楼答案

    使用GridBagLayout的解决方案是

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.weightx=1; //Fill all space
    gbc.anchor=GridBagConstraints.EAST; //align component to the EAST
    

    我把x,y设为1。重要的是要理解这些是相对于您添加的其他对象的索引。(如果只有一个组件,则没有意义,没有不可见的网格位置

  2. # 2 楼答案

    这将把标签移到最右边

    public DieIntGUI(String title) {
        super(title);
        setSize(700, 700);
        getContentPane().setBackground(Color.white);
        setLayout(new BorderLayout());
        initComponents();
        add(panel, BorderLayout.EAST); // Move to right
        add(errorMessages, BorderLayout.SOUTH);
        setLocationRelativeTo(null);
    }
    

    输出:

    enter image description here

    是的,panel被设置为CENTER,因为在BorderLayout中,如果不指定位置,默认情况下,它被设置为BorderLayout.CENTER