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

时间:2013-03-31 08:04:11

标签: java swing jbutton paint

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

enter image description here

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

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

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

2 个答案:

答案 0 :(得分: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);
    }

如上所述我会得到

enter image description here

希望这有帮助。

答案 1 :(得分:2)

只需使用类似Graphics#fillRect的内容填充矩形区域

public void paintComponent(Graphics g) {
    System.out.println("Inside the paintComponent method");
    // Or what ever background color you want...
    g.setColor(Color.RED);
    g.fillRect(0, 0, getWidth(), getHeight());
    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);
}
相关问题