我正在创建一个包含带有按钮网格的JPanel
的JFrame
。一切正常,但我想在按钮面板上方添加一个JLabel
,但标签从未出现。不过,如果我不使用BoxLayout
,它确实会出现。任何帮助,不胜感激。
下面的第一个代码部分是我的JFrame
类:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame {
private static final long serialVersionUID = 1L;
Panel panel = new Panel();
Dimension frameDim = new Dimension(1000, 1000);
Dimension labelDim = new Dimension(100, 20);
Box box = new Box(BoxLayout.Y_AXIS);
JLabel label = new JLabel("Tic Tac Toe");
JPanel pane = new JPanel();
public Frame() {
pane.add(label);
pane.setPreferredSize(labelDim);
pane.setMinimumSize(labelDim);
add(pane);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
add(box);
setTitle("Tic Tac Toe");
setSize(frameDim);
setMinimumSize(frameDim);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
下面的代码是我带按钮的JPanel
类:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel extends JPanel {
private static final long serialVersionUID = 2L;
private int i;
JButton[] button = new JButton[9];
GridLayout layout = new GridLayout(3, 3);
Dimension dim = new Dimension(500, 500);
public Panel() {
for (i = 0; i<9; i++) {
button[i] = new JButton();
add(button[i]);
}
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
setLayout(layout);
}
}
下面的最后一个代码部分是Main
类:
public class RunGame {
public static void main(String[] args) {
new Frame();
}
}
add(box);
这是将标签直接添加到JFrame
,其内容窗格使用BorderLayout
进行布局。在没有任何约束的情况下将组件添加到边框布局时,默认值为 CENTER
,它只能显示单个组件。要修复它,请使用:
pane.add(box);
您可以将
标签添加到窗格中到框架中并删除该框内容时使用边框布局,如下所示
public Frame()
{
//create label and add it to the frame
JLabel label = new JLabel("Tic Tac Toe");
label.setHorizontalAlignment( JLabel.CENTER );
add(label, BorderLayout.NORTH);
//create buttonsPanel and add it to the frame
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout(3, 3));
for (int i = 0; i < 9; i++)
{
buttons.add(new JButton(""+i));
}
add(buttons, BorderLayout.CENTER);
//setup the title, other properties for the frame etc..
setTitle("Tic Tac Toe");
setSize(1000, 1000);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
希望这有助于更好的:)