Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

java - how to highlight part of a JLabel at runtime?

I have a JLabel inside a JPanel. I'm using Netbeans IDE for the GUI of my java program (free design, and no Layout Manager).

At runtime I need to highlight a part of my JLabel. Highlighting a part of JLabel can be done as said here : How to highlight part of a JLabel?

I don't know how to do that in run time, I mean I already have a JLabel, now how can I override it's paintComponent() method for that purpose ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is an illustrative example of the answer given by Tikhon Jelvis in the post you mentioned, all you need is to add some fields (in this example start and end) to indicate the regions to be highlighted, and use a method (highlightRegion in this example) to set these fields:

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;

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

public class Main
{
    public static void main(String[] argv)
    {
        JFrame frame = new JFrame("Highlighting");
        frame.setSize(300, 100);

        Label label = new Label();
        label.setText("Money does not buy happiness");
        label.setVerticalAlignment(JLabel.TOP);
        label.highlightRegion(3, 15);

        frame.add(label);
        frame.setVisible(true);
    }

    static class Label extends JLabel
    {
        private static final long serialVersionUID = 1L;
        private int start;
        private int end;

        @Override
        public void paint(Graphics g)
        {
            FontMetrics fontMetrics = g.getFontMetrics();

            String startString = getText().substring(0, start);
            String text = getText().substring(start, end);

            int startX = fontMetrics.stringWidth(startString);
            int startY = 0;

            int length = fontMetrics.stringWidth(text);
            int height = fontMetrics.getHeight();

            g.setColor(new Color(0x33, 0x66, 0xFF, 0x66));
            g.fillRect(startX, startY, length, height);

            super.paint(g);
        }

        public void highlightRegion(int start, int end)
        {
            this.start = start;
            this.end = end;
        }
    }

}

Notice the use of label.setVerticalAlignment(JLabel.TOP); to simplify things. If you don't use it then you need to do extra computations to determine the exact vertical location of the region to be highlighted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...