Format JLabel text with different colors

2

How can I format a JLabel and its contents with different "properties"?

For example, I'd like to be able to set a color for the text of my JLabel , and another for string that is concatenated with it. It's possible?

In my case, it only got a "way", and the% w_that I tried to use did not work either.

What I've tried:

import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Teste extends JFrame {

    public static void main(String[] args) {
        new Teste().setVisible(true);
    }

    private JPanel painel = new JPanel();

    private Font fonte = new Font("SansSerif", Font.BOLD, 15);
    private JLabel label = new JLabel();

    private String string = "string";

    public Teste() {

        setSize(500, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        painel.add(label);
        add(painel);

        label.setText("Label + " + "<html><font color=#166B44> " + string + " </font></html>");
        label.setFont(fonte);
        label.setForeground(Color.red);

    }
}
    
asked by anonymous 06.08.2017 / 04:42

2 answers

2

Can not do this using JLabel , this component is for plain text. Of course, it accepts HTML tags for text formatting, but in addition to "smearing" the code, it will make it very difficult to maintain later.

Fortunately there are component alternatives for this purpose, which is the case for JTextPane or JEditorPane , which accept stylization of text, even if fragmented, as you need.

See this example:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class JTextPaneExample {

    public void createAndShowGUI() {
        JFrame f = new JFrame("JTextPaneExample");

        // cria um StyleContext e um Document para o jtextpane
        StyleContext sc = new StyleContext();
        final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
        JTextPane pane = new JTextPane(doc);
        pane.setEditable(false);

        // cria um estilo e adiciona atributos personalizados nele
        final Style redStyle = sc.addStyle("RED", null);
        redStyle.addAttribute(StyleConstants.Foreground, Color.red);
        redStyle.addAttribute(StyleConstants.FontSize, new Integer(16));

        final Style blueStyle = sc.addStyle("BLUE", null);
        blueStyle.addAttribute(StyleConstants.Foreground, Color.blue);
        blueStyle.addAttribute(StyleConstants.FontSize, new Integer(14));
        blueStyle.addAttribute(StyleConstants.Bold, new Boolean(true));

        try {
            // insere um texto inicial com uma style
            doc.insertString(0, "Texto inicial ", redStyle);
            // insere texto concatenado com outra style
            doc.insertString(pane.getText().length(), "texto concatenado", blueStyle);
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }

        f.getContentPane().add(new JScrollPane(pane));
        f.setSize(400, 300);
        f.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            new JTextPaneExample().createAndShowGUI();;
        });
    }
}

That results in:

A StyleContext is nothing more than a pool styles, where we'll add the styles we'll use in the component. DefaultStyledDocument is the class that will interpret these styles and will apply to the text, as we concatenate and pass the styles to the text fragments. The Style interface is the style itself, where we set up details such as the color, size, and type of font we want from text.

References :

06.08.2017 / 05:36
2

For that purpose you want to work. All text of JLabel must be within <html>...</html> . Anything you put out of it will go wrong.

For example:

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TesteCor {

    public static void main(String[] args) {
        EventQueue.invokeLater(TesteCor::executar);
    }

    public static void executar() {
        JFrame frame = new JFrame();
        JPanel painel = new JPanel();

        Font fonte = new Font("SansSerif", Font.BOLD, 15);
        JLabel label = new JLabel();

        frame.setSize(500, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        painel.add(label);
        frame.add(painel);

        label.setText(""
                + "<html>"
                + "Cor padrão "
                + "<font color=\"red\">Vermelho</font> "
                + "<font color=\"blue\">Azul</font> "
                + "<font color=\"green\">Verde</font> "
                + "<font color=\"yellow\">Amarelo</font> "
                + "</html>");
        label.setFont(fonte);
        label.setForeground(Color.pink);
        frame.setVisible(true);
    }
}

Note that I put Color.pink as the foreground of the label.

As for EventQueue.invokeLater , see my other answer that explains .

Here's the result:

    
06.08.2017 / 05:35