我正在尝试使用此代码,出于某种原因,它出现在中间。这是我的代码:
String errormsg = "Something went wrong.";
final String title = "Wall Game";
this.setSize(400, 500); //sets the screen
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle(title);
this.setVisible(true);
this.setSize(401,501);
try {
Font font1 = new Font("Comic Sans MS", Font.BOLD, 15);
JPanel panel1 = new JPanel(new GridBagLayout()); //makes all the panels
JLabel label1 = new JLabel("Welcome to the Wall Game!"); //labels
JLabel label2 = new JLabel("Click the button to read instructions!");
JButton button1 = new JButton("Start");//buttons
button1.setText("Start!");
label1.setFont(font1);
button1.setLayout(new BoxLayout(button1, BoxLayout.Y_AXIS));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,10,10,10);
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(label1, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
panel1.add(label2, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
panel1.add(button1, gbc);
this.add(panel1);
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Something went wrong. Try restarting.", "Sorry", JOptionPane.INFORMATION_MESSAGE);
}
}
文字显示的位置在中间。不是从顶部开始。这是一个很小的例子:
有谁知道如何从顶部开始?感谢任何能提供帮助的人。在尝试帮助之前,请先尝试代码。你,肯定需要import "javax.swing.*"
FYI。
竖起大拇指,如果你喜欢我做过的绘画作品lol:D我在Window的画中画了它。
答案 0 :(得分:3)
阅读How to Use GridBag Layout上的Swing教程中的部分,尤其是关于weightx / y约束的部分。
您需要为其中一个组件设置非零值,否则组件将居中。