Question

enter image description here

Hi i am trying to make java desktop application where i am using JLabel I wrote some test on JLabel I want to set text from the top and I am using multiple line in JLabel I want to set different different color for every line.

Here is my code:

JLabel label = new JLabel("<html>Case &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CaseNum<br>Party1<br>Party2</html>");

How can I achieve this?

Was it helpful?

Solution

You can try using the html tables for new lines as below,

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * @author JayaPrasad
 * 
 */
public class SwingHtml {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JLabel label = new JLabel(
                "<html>Case &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CaseNum<table><tr><font color=blue>Party1</font></tr><tr><font color=red>Party2</font></tr></table></html>");
        frame.add(label);
        frame.setSize(new Dimension(250, 130));
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

OTHER TIPS

Use a JTable for this, rendered the same way as in the Nimbus PLAF.

You can do something like this:

 <html><p><font color="green">line 1</font></p><br /><p><font color="red">line2</font></p></html>

if you want to change the line 1 text colour and add a new line 2 with a new colour

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top