我正在为我的迷你游戏添加一个按钮,但我不知道如何创建一个换行符。我想在按钮和文本之间留一个空格,代码如下:
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Welcome to the Wall Game!");
JLabel label2 = new JLabel("Click the button to read the instructions!");
JLabel space = new JLabel("");
JButton button1 = new JButton("Start");
button1.setText("Start!");
label1.setFont(font1);
panel1.add(label1); //adds in all the labels to panels
panel1.add(label2);
panel1.add(space);
panel1.add(button1);
this.add(panel1); //adds the panel
欢迎信息中单独显示的内容,但出于某种原因,该按钮位于 label2
旁边 有人知道怎么做吗?
顺便说一句,如果您还不知道的话,您需要在开始时输入 import javax.swing.*;
。
感谢任何知道的人。
最佳答案
JPanel
默认使用 FlowLayout
,这显然不能满足您的需求。您可以改用 GridBagLayout
。
看看Laying Out Components Within a Container和 How to Use GridBagLayout了解更多详情
有点像...
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Welcome to the Wall Game!");
JLabel label2 = new JLabel("Click the button to read the instructions!");
JButton button1 = new JButton("Start");
button1.setText("Start!");
Font font1 = label1.getFont().deriveFont(Font.BOLD, 24f);
label1.setFont(font1);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel1.add(label1, gbc); //adds in all the labels to panels
panel1.add(label2, gbc);
gbc.insets = new Insets(30, 0, 0, 0);
panel1.add(button1, gbc);
举个例子
关于Java - 如何在 swings 中添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35189906/