Search code examples
javaswingjbuttonpaint

How do I fill the remaining portions in the button?


I have been trying the round button but there is a problem here. Currently I am getting a button like this :

enter image description here

What I want to do is fill the remaining portions in the button square. How do I do this ? This is the code that painted this button.

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

How do I fill the remaining portions in the button ?


Solution

  • You can just use the fillrect() method to fill the remaining portion before you call 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);
        }
    

    Doing like above I'll get

    enter image description here

    Hope this helps.