Java-如何在秋千中添加换行符
我正在给我的小游戏添加一个按钮,但我不知道如何换行。我想在按钮和文本之间留一个空格,下面是代码:Java-如何在秋千中添加换行符,java,swing,line-breaks,Java,Swing,Line Breaks,我正在给我的小游戏添加一个按钮,但我不知道如何换行。我想在按钮和文本之间留一个空格,下面是代码: 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 b
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
旁边,有人知道怎么做吗
顺便说一下,您需要导入javax.swing.*如果您还不知道,请在开始时使用code>。
感谢所有知道的人。JPanel
默认使用FlowLayout
,这显然不能满足您的需要。您可以使用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);