本文介绍了重写JButton paintComponent()不工作的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制我自己的JButton版本,所以我重写了 paintComponent()方法,并绘制了一个渐变roundRect。这是有效的,但在此之后,我想在其上绘制Button的String,并且在编译时,我没有收到任何错误消息。但是在运行时,我只能看到roundRect,渐变,就像我想要的那样(我也可以点击它),但是字符串是不可见的...

I wanted to paint my own version of JButton, so I have overridden the paintComponent() method, and drew a gradient roundRect. This works, but after that, I want to draw the String of the Button over it, and at compile-time, I got no error messages. But at runtime, I only see the roundRect, gradient, just as I intended it to be (I can click on it too), but the String is invisible...

这里是我的代码:

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

public class JIconButton extends JButton implements MouseListener
{
    private boolean mouseInside;
    public JIconButton(String file, String text)
    {
        super(text, new ImageIcon(file));
        setBorder(new LineBorder(Color.LIGHT_GRAY, 0, true));
        setContentAreaFilled(false);
        setFocusPainted(false);
        addMouseListener(this);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e)
    {

    }

    public void mouseEntered(MouseEvent e)
    {

    }

    public void mouseExited(MouseEvent e)
    {

    }

    public void mousePressed(MouseEvent e)
    {

    }

    public void mouseReleased(MouseEvent e)
    {

    }

    @Override
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setPaint(Color.BLACK);
        g2.drawString(getText(), 0, 0);
        g2.setPaint(new GradientPaint(
                new Point(0, 0),
                Color.WHITE,
                new Point(0, getHeight()),
                Color.PINK.darker()));
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
        g2.dispose();

        //super.paintComponent(g);
    }
}


推荐答案

根据我的评论,它为我工作....


例如:

As per my comment, "it worked for me...."
For example:

   @Override
   protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D) g.create();
      g2.setPaint(new GradientPaint(new Point(0, 0), Color.WHITE, new Point(0,
            getHeight()), Color.PINK.darker()));
      g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
      g2.setPaint(Color.BLACK);
      g2.drawString(getText(), 30, 12);
      g2.dispose();

      // super.paintComponent(g);
   }

这篇关于重写JButton paintComponent()不工作的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:22