JLabel:重写paintComponent()之后。如何使setText()呈现文本字符串?

时间:2013-01-12 20:05:49

标签: java swing override jlabel paintcomponent

我写了一个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();

但没有发生任何事情

3 个答案:

答案 0 :(得分:7)

如果你在方法的 end 调用super.paintComponent(g),那么标签在之后绘制文本它会绘制gradiant:

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);
}

答案 1 :(得分:4)

JLabelpaintComponent方法中呈现其文字内容。

你是正确的,正在调用super.paintComponent,然后使用fillRect

立即在上面绘画

尝试将通话移至super.paintComponent至方法的最后(fillRect通话后),并将标签保持为透明

答案 2 :(得分:4)

当你画完它在画面上画的时候。看看SwingX项目。它有一个JxLabel类,可以完全按照你想要的那样完成。