简体   繁体   English

如何让 jButton 的文本跨越多行

[英]How to have text span multiple lines for a jButton

I have buttons in NetBeans which I had tried to find code to allow the text of the button to be on two lines.我在 NetBeans 中有按钮,我试图找到代码以允许按钮的文本位于两行。

The current code that to change the label of FC1box is:目前修改FC1box的label的代码是:

String text = "";
text=(displayedSets.get(0)).getNameOfSet()+"\\n By:"+(displayedSets.get(0)).getSetCreator();
FC1box.setText("<html>" + text.replaceAll("\\n","<br>") + "</html>");

However, this displays the text like this:但是,这会显示如下文本:

在此处输入图像描述

I have tried using different syntax doing the same thing, but I could not get it to work and I was wondering if this is even possible?我曾尝试使用不同的语法做同样的事情,但我无法让它工作,我想知道这是否可能?

As a side note, you are escaping the slash by typing a double slash.作为旁注,您是 escaping 通过键入双斜杠的斜杠。 For new line, it should be just "\n".对于新行,它应该只是“\n”。

If you need to have multiline text in a Swing Component, you should try using a text area or use HTML.如果您需要在 Swing 组件中包含多行文本,您应该尝试使用文本区域或使用 HTML。 In your case, don't use "\n" and then try to convert.在你的情况下,不要使用 "\n" 然后尝试转换。 Just create the HTML string from the get go.只需从 get go 中创建 HTML 字符串。

In most cases, you'll want to make use of Swing's (limited) HTML support, for example...在大多数情况下,您需要使用 Swing 的(有限)HTML 支持,例如...

给我看按钮

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(50, 50, 50, 50));
            add(new JButton("<html>All your base<br>belong to us"));
        }

    }
}

So, the double escaping probably isn't what you want to use (unless you want to display \n所以,双 escaping 可能不是你想要使用的(除非你想显示\n

For example...例如...

String text = "Test 2" + "\n By:" + "your name here";

setLayout(new GridBagLayout());
setBorder(new EmptyBorder(50, 50, 50, 50));
add(new JButton("<html>" + text.replaceAll("\n", "<br>") + "</html>"));

works out fine for me对我来说很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM