Java – how to merge long strings into jlabel

As the title shows: I need to install jlabel into JFrame, but the text in jlabel is too long, so I need to add some line breaks The text in jlabel is obtained from an online XML file, so I can't change the text to include line breaks

This code extracts data from an XML file

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

In this case, I want to add some linebreaks to the string v. string V contains the data parsed from the XML file String prediction will return and set to jlabel text

Just ask something is not clear, thank you in advance!

Solution

I suggest using jtextarea instead and unpacking The only way to do this in jlabel is to set the newline character < br / >. If you don't know the text, you won't work properly (at least not easy)

Jtextarea is more flexible By default, it looks different, but you can make it look like a jlabel around some display properties

A simple modification example is taken from the how to use text areas tutorial –

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);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>