1

我覆盖了 JButton 的绘制组件,但是现在当我单击它时它不会变暗。我搜索了谷歌和堆栈溢出,但似乎没有答案。那么如何使按钮在单击时变暗,然后在单击完成后恢复正常?

这是我的代码:

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D)g.create();
    RenderingHints qualityHints =
          new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  g2.setRenderingHints(qualityHints);
    g2.setPaint(new GradientPaint(
            new Point(0, 0), 
            BUTTON_TOP_GRADIENT, 
            new Point(0, getHeight()), 
            BUTTON_BOTTOM_GRADIENT));
    g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
    g2.dispose();


}
4

1 回答 1

3

底部的这段代码片段对我有用。以下是它的工作原理:

我检查按钮的模型以查看是否单击了按钮。单击它时,它会以不同的方式绘制自己。

package com.sandbox;

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

public class SwingSandbox {

    public static void main(String[] args) {

        JFrame frame = buildFrame();
        frame.add(new MyButton());
    }

    private static class MyButton extends JButton {


        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Color color;

            if (getModel().isPressed()) {
                color = new Color(0, 0, 0);
            } else {
                color = new Color(0, 0, 255);
            }

            Graphics2D g2 = (Graphics2D) g.create();
            RenderingHints qualityHints =
                    new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2.setRenderingHints(qualityHints);
            g2.setPaint(new GradientPaint(
                    new Point(0, 0),
                    color,
                    new Point(0, getHeight()),
                    new Color(255, 255, 0)));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
            g2.dispose();


        }
    }


    private static JFrame buildFrame() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
        return frame;
    }


}
于 2013-05-31T19:28:01.107 回答