如何将长字符串放入JLabel中

Tob*_*sen 9 java swing

正如标题所说:我需要将JLabel放入JFrame中,但JLabel中的文本太长,所以我需要添加一些换行符.JLabel中的文本是从在线XML文件中获取的,因此我只能将文本更改为包含换行符.

此代码从XML文件中提取数据

Element element = (Element)nodes1.item(i);
            String vær = getElementValue(element,"body");
            String v = vær.replaceAll("<.*>", "" );  
            String forecast = "Vær: " + v;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,字符串我想在字符串v中添加一些换行符.字符串v包含来自xml文件的已解析数据.返回String预测并将其设置为JLabel的文本.

只要问一下有什么东西未清除,提前谢谢!

tsk*_*zzy 12

我建议使用JTextArea替代和转动包装.在a中执行此操作的唯一方法JLabel是设置换行符<br />,如果您事先不知道文本,则会在您的情况下无效(至少不容易).

JTextArea更灵活.默认情况下它看起来不同,但你可以摆弄一些显示属性,使它看起来像一个JLabel.


一个简单的修改使用示例取自" 如何使用文本区域"教程 -

public class JTextAreaDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {         
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        JTextArea textArea = new JTextArea(
                "If there is anything the nonconformist hates worse " +
                "than a conformist, it's another nonconformist who " +
                "doesn't conform to the prevailing standard of nonconformity.", 
                6, 
                20);
        textArea.setFont(new Font("Serif", Font.ITALIC, 16));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setOpaque(false);
        textArea.setEditable(false);

        panel.add(textArea);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Tho*_*mas 5

JLabel能够显示HTML文本,即如果用<html>your text<html>它包装文本可能能够包装文本.虽然没有经过测试,所以YMMV.