编程语言
首页 > 编程语言> > Java – 如何在swing中添加换行符

Java – 如何在swing中添加换行符

作者:互联网

我正在为我的迷你游戏添加一个按钮,但我不知道如何换行.我想在按钮和文本之间有一个空格,这里是代码:

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.*;在一开始,如果你还不知道.
感谢任何知道的人.

解决方法:

JPanel默认使用FlowLayout,显然不能满足您的需求.您可以使用GridBagLayout.

有关详细信息,请查看Laying Out Components Within a ContainerHow to Use GridBagLayout

就像是…

Welcome

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,line-breaks,swing
来源: https://codeday.me/bug/20190608/1201519.html