问题
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 ?
回答1:
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.
来源:https://stackoverflow.com/questions/14376216/how-to-highlight-part-of-a-jlabel-at-runtime