我正在制作一个得分保持计划,但我遇到了一个问题.我试图做的是在顶部有一个包含两个JPanel的JPanel,而JPanel又包含两个团队名称.我很困惑为什么程序顶部的两个JLabel没有集中在它们所包含的JPanels中.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScoreFrame extends JFrame {
private static final Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
private static final int WIDTH = SCREEN_SIZE.width;
private static final int HEIGHT = SCREEN_SIZE.height;
private final JTextField[] nameField = new JTextField[] { new JTextField(), new JTextField() };
private final JLabel[] nameLabel = new JLabel[] { new JLabel("Team 1"), new JLabel("Team 2") };
private final GridBagLayout gridBag = new GridBagLayout();
private final GridBagConstraints constraints = new GridBagConstraints();
private final JPanel topPanel …Run Code Online (Sandbox Code Playgroud) 我想创建具有困难级别的简单菜单
接下来的几行代码是构造函数。
super();
setMinimumSize(new Dimension(600, 300));
setMaximumSize(new Dimension(600, 300));
setPreferredSize(new Dimension(600, 300));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
addButtons();
Run Code Online (Sandbox Code Playgroud)
方法addButtons()添加按钮,您可以在屏幕截图中看到:
add(Box.createVerticalGlue());
addLabel("<html>Current level <b>" + Game.instance()
.getLevelString() +
"</b></html>");
add(Box.createVerticalGlue());
addButton("Easy");
add(Box.createVerticalGlue());
addButton("Normal");
add(Box.createVerticalGlue());
addButton("Hard");
add(Box.createVerticalGlue());
addButton("Back");
add(Box.createVerticalGlue());
Run Code Online (Sandbox Code Playgroud)
方法addButton()
private void addButton(String text)
{
JButton button = new JButton(text);
button.setAlignmentX(JButton.CENTER_ALIGNMENT);
button.setFocusable(false);
add(button);
}
Run Code Online (Sandbox Code Playgroud)
和addLabel()
private void addLabel(String text)
{
JLabel label = new JLabel(text, JLabel.CENTER);
add(label);
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何将所有元素对齐到中心。这对我来说是个问题。另一个问题是,当我将困难级别文本更改JLabel为简单的“当前级别简单”时。然后JButtons向右移动很多像素,我不知道为什么。