在使用 paintComponent 绘制的图形上显示 JLabel

Show JLabel on a graphic drawn with paintComponent

我有一个 class 扩展 JLabel。这个 JLabel 有一个特殊的形状,我在方法 paintComponent 中绘制了它。我想在 jLabel 的中心显示一个文本,但未显示该文本。谁能帮帮我

我的简单 HLabel class 如下:

private class Scudetto extends JLabel {

    private static final long serialVersionUID = 1L;

    public Scudetto(String line_point)
    {
        super(line_point, SwingUtilities.CENTER);
        this.setOpaque(true);
        this.setBackground(Color.BLACK);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension d = this.getSize();

        int[] x = { 0, d.width,      d.width, d.width / 2,             0 };
        int[] y = { 0,       0, d.height / 2,     d.height, d.height / 2 };

        g.setColor(Color.WHITE);
        g.fillPolygon(x, y, 5);

        g.setColor(Color.BLACK);

    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(10, 20);
    }

}

I want to show a text in the center of the jLabel but this text is not shown.

super.paintComponent() 将绘制文本,但随后您的自定义绘制将在文本顶部绘制多边形。

不要覆盖 JLabel。相反,您可以创建 PolygonIcon。然后将图标和文本添加到 JLabel。

您可以使用以下方法使文本居中显示:

JLabel label = new JLabel("your text");
label.setIcon( polygonIcon );
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);

下面是创建矩形图标的简单示例:

import java.awt.*;
import javax.swing.*;

public class ColorIcon implements Icon
{
    private Color color;
    private int width;
    private int height;

    public ColorIcon(Color color, int width, int height)
    {
        this.color = color;
        this.width = width;
        this.height = height;
    }

    public int getIconWidth()
    {
        return width;
    }

    public int getIconHeight()
    {
        return height;
    }

    public void paintIcon(Component c, Graphics g, int x, int y)
    {
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public static void createAndShowGUI()
    {
        JPanel panel = new JPanel( new GridLayout(2, 2) );

        for (int i = 0; i < 4; i++)
        {
            Icon icon = new ColorIcon(Color.RED, 50, 50);
            JLabel label = new JLabel( icon );
            label.setText("" + i);
            label.setHorizontalTextPosition(JLabel.CENTER);
            label.setVerticalTextPosition(JLabel.CENTER);
            panel.add(label);
        }

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.setSize(200, 200);
        f.setLocationRelativeTo( null );
        f.setVisible(true);
    }
}

我会让你修改多边形的代码。

您还可以查看 Playing With Shapes 以了解一些创建不同形状图标的有趣方法。