簡體   English   中英

在用paintComponent繪制的圖形上顯示JLabel

[英]Show JLabel on a graphic drawn with paintComponent

我有一個擴展JLabel的課程。 這個JLabel具有奇異的形狀,我在paintComponent方法中進行繪制。 我想在jLabel的中心顯示一個文本,但是未顯示該文本。 誰能幫我。

我的簡單HLabel類如下:

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

}

我想在jLabel的中心顯示一個文本,但是未顯示該文本。

super.paintComponent()將繪制文本,但是您的自定義繪制將在文本上方繪制多邊形。

不要重寫JLabel。 相反,您可以創建PolygonIcon 然后,將Icon和文本添加到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);
    }
}

我將讓您修改多邊形的代碼。

您還可以查看“ 使用形狀玩”以獲得一些有趣的方式來創建不同形狀的圖標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM