5

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

但什么也没发生

4

3 回答 3

7

如果你在方法的最后调用 super.paintComponent(g) ,让标签在绘制渐变之后绘制文本:

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);
}
于 2013-01-12T20:09:47.927 回答
4

JLabel在方法中呈现其文本内容paintComponent

正确地,您正在调用super.paintComponent,但随后会立即使用fillRect

尝试将调用移动到super.paintComponent方法的末尾(fillRect调用之后)并将标签保留为透明

于 2013-01-12T20:11:46.683 回答
4

当您进行绘画时,它会在文本上绘画。看看SwingX项目。它有一个 JxLabel 类,可以完全满足您的要求。

于 2013-01-12T20:13:33.703 回答