Marko Marinkovic
Marko Marinkovic

Reputation: 126

How to make a JButton have a border only when active

I'm making a painting tool with Java Swing. I have a panel on the right side which displays all the colors and lets the user choose between them. I'm trying to make a border appear around the button of the currently chosen color.

As it is I'm creating a permanent border around the button when I choose the color.

What I'm struggling with is making the border temporary. I mean I want it to go away when that color is no longer being used IE when the user presses another button. This is how my code looks

 final JButton blueKnapp = new JButton();
 blueKnapp.setBackground(Color.BLUE);
 blueKnapp.setSize(20, 30 );
 this.add(blueKnapp);

 blueKnapp.addActionListener(new ActionListener(){
    @Override

    public void actionPerformed(ActionEvent arg0) {
         blueKnapp.setBorder(new LineBorder(Color.BLACK, 3));

        parent.changeColor(Color.BLUE);
    }
 });

Upvotes: 0

Views: 596

Answers (1)

Ben
Ben

Reputation: 1695

As pointed out by Andrew Thompson it is bad practice to override the paint() method and instead should be done using the paintComponent() method. Also just using the focus painting does the same job probably better.


What you could do is override the paintComponent-method of your button and add a check for focus of the button. If it has focus set the border to drawn, else set it to not be drawn. Could look like this:

JButton blueKnapp = new JButton()
{
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        this.setBorderPainted(this.hasFocus());
    }
};

blueKnapp.addActionListener((evt) -> {
    // set the border to either black or blue randomly.
    // replace this with your "color picker color" probably.
    blueKnapp.setBorder(new LineBorder(Math.random() < 0.5 ? Color.BLACK : Color.BLUE, 3));
});

Upvotes: 1

Related Questions