将JLabel添加到使用BoxLayout的JFrame

问题描述 投票:2回答:2

我正在创建一个JFrame,其中包含带有按钮网格的JPanel。一切正常,但我想在按钮面板上方添加一个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();
    }
}
java swing jframe jpanel boxlayout
2个回答
1
投票

将标签添加到框架中时,您可以使用BorderLayout并删除该框,如下所示

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);
  }

希望这有助于更好:)


4
投票
add(box);

这是将标签直接添加到JFrame,其内容窗格使用BorderLayout进行布局。将组件添加到没有任何约束的边框布局时的默认设置是CENTER,它只能显示单个组件。要修复它,请使用:

pane.add(box);
© www.soinside.com 2019 - 2024. All rights reserved.