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;
}
# 1 楼答案
使用
GridBagLayout
的解决方案是我把x,y设为1。重要的是要理解这些是相对于您添加的其他对象的索引。(如果只有一个组件,则没有意义,没有不可见的网格位置)
# 2 楼答案
这将把标签移到最右边
输出:
是的,
panel
被设置为CENTER
,因为在BorderLayout中,如果不指定位置,默认情况下,它被设置为BorderLayout.CENTER