我写了一个 JLabel 的子类,并重写paintComponent(Graphics)
了方法来制作渐变背景色。
这是 JLabel 的子类:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
public class DLabel extends JLabel
{
Dimension size = new Dimension(70, 80);
public DLabel()
{
this.setPreferredSize(size);
this.setBorder(BorderFactory.createBevelBorder(TOP, Color.white, Color.black));
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = new Color(226, 218, 145);
Color color2 = color1.brighter();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
当我创建此标签的实例时,它会正确显示,但是当我使用setText(String)
文本时不会呈现任何内容。
DLabel label = new DLabel();
label.setText("I am"); //No text displayed.
设置文本后,我尝试了这些方法的不同编译:
label.setOpaque(true);
label.revalidate();
label.repaint();
但什么也没发生