简体   繁体   中英

How to make Java GUI settext recognize new lines for a 2 dimensional array input

I have a char[xSize][ySize] being sent to my GUI. The GUI prints the long string as one long line without recognizing the new lines in it. What method or code could I use? The code I currently use is:

            JFrame frame1 = new JFrame("Start Screen");
            JLabel label = new JLabel();
            frame1.setVisible(true);
            frame1.setSize(500, 500);
            frame1.setLayout(new BorderLayout());
            frame1.add(label, BorderLayout.NORTH);

            //Code to recieve from other program:

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            String Sentence = new String(receivePacket.getData());  

            //Print received text to GUI:
            label.setText(Sentence);

Thanks in advance

For something JLabel , you would need to first replace the new lines ( \\n ) with <br> and wrap the text in <html>...</html>

String Sentence = new String(receivePacket.getData());  

//Print received text to GUI:
label.setText("<html>" + Sentence.replaceAll("\n", "<br>") + "</html>");

Or you might be able to use a non-editable JTextArea instead...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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