我写了一个 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();
但是什么都没发生
最佳答案
如果您在方法的末尾 调用 super.paintComponent(g),标签会在 绘制渐变之后绘制文本: p>
public void paintComponent(Graphics g) {
// super.paintComponent(g); // *** commented
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);
super.paintComponent(g); // *** added
}
此外,作为一个不相关的旁白,我更愿意改变这个:
Dimension size = new Dimension(70, 80);
public DLabel()
{
this.setPreferredSize(size);
this.setBorder(BorderFactory.createBevelBorder(TOP, Color.white,
Color.black));
}
为此:
public static final Dimension PREF_SIZE = new Dimension(70, 80);
public DLabel()
{
this.setBorder(BorderFactory.createBevelBorder(TOP, Color.white,
Color.black));
}
@Override
public Dimension getPreferredSize() {
Dimension superDim = super.getPreferredSize();
int width = Math.max(superDim.getWidth(), PREF_SIZE.getWidth());
int height = Math.max(superDim.getHeight(), PREF_SIZE.getHeight());
return new Dimension(width, height);
}
关于java - JLabel:重写 paintComponent() 之后。如何让 setText() 呈现文本字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297448/