如何填充按钮中的其余部分?

sap*_*Pro 0 java swing paint jbutton

我一直在尝试圆形按钮,但这里有一个问题.目前我得到一个这样的按钮:

在此输入图像描述

我想要做的是填充按钮方块中的其余部分.我该怎么做呢 ?这是绘制此按钮的代码.

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

class Tester extends JButton {

        public Tester(String label) {
            super(label);
            setContentAreaFilled(false);
            Dimension size = this.getPreferredSize();
            size.width = size.height = Math.max(size.width,size.height);
            this.setPreferredSize(size);

        }

        @Override
        public void paintComponent(Graphics g) {System.out.println("Inside the paintComponent method");
            if (getModel().isArmed()) {
                g.setColor(Color.lightGray);
            } else {
                g.setColor(getBackground());
            }
            g.fillOval(0,0,getSize().width-1,getSize().height-1);
            System.out.println(getSize().width);
            System.out.println(getSize().height);
            super.paintComponent(g);
        }


        public static void main(String args[]) {
            JFrame fr = new JFrame();
            JPanel p = new JPanel();
            JButton button = new Tester("Click Me !");
            button.setBackground(Color.GREEN);
            p.add(button);
            fr.add(p);
            fr.setVisible(true);
            fr.setSize(400,400);    
            fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
}
Run Code Online (Sandbox Code Playgroud)

如何填充按钮中的其余部分?

Vin*_*nay 5

您可以fillrect()在致电之前使用该方法填充剩余部分fillOval()

    @Override
    public void paintComponent(Graphics g) {
        System.out.println("Inside the paintComponent method");
        g.setColor(Color.red); // here
        g.fillRect(0, 0, this.getWidth(), this.getHeight()); //here

        if (getModel().isArmed()) {
            g.setColor(Color.lightGray);
        } else {
            g.setColor(getBackground());
        }

        g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
        System.out.println(getSize().width);
        System.out.println(getSize().height);
        super.paintComponent(g);
    }
Run Code Online (Sandbox Code Playgroud)

如上所述,我会得到

在此输入图像描述

希望这可以帮助.