Domanda

Okay, so here is the problem.

g.setColor(Color.WHITE);
g.drawString("all your base belong to us",x,y);

The follow code makes it so that the string displayed is white and fully white.

My aim is to make a certain section of the string, say for example, I want the word "base" in that string to be a different color, yellow in this case.

The code that I would most likely use would be:

g.drawString("all your #ffd700base belong to us",x,y);

That code attempts to set the text to be yellow from 'base' all the way to the end of the sentence.

Though the output of that is:

https://i.stack.imgur.com/lB2WC.png

Ignore the background, just look at the string. The "#ffd700" becomes a part of the string which is then displayed.

This doesn't work, I cannot find a solution that does.

È stato utile?

Soluzione

Same problem is solved here. Please have a look at below posts:

Sample code after some changes in code mentioned at above link:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.CellRendererPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class PaintComponentTest extends JPanel {

    private static final String s = "<html>all your <font color=\"#ffd700\">base</font> belong to us</html>";
    private JLabel renderer = new JLabel(s);
    private CellRendererPane crp = new CellRendererPane();
    private Dimension dim;

    public PaintComponentTest() {
        this.setBackground(Color.lightGray);
        dim = renderer.getPreferredSize();
        this.add(crp);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        renderer.setForeground(Color.WHITE);
        crp.paintComponent(g, renderer, this, 10, 10, dim.width, dim.height);
    }

    private void display() {
        JFrame f = new JFrame("PaintComponentTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(this);
        f.pack();
        f.setSize(200, 70);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new PaintComponentTest().display();
            }
        });
    }
}

screenshot:

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top