jjyao
jjyao

Reputation: 315

Customize JButton style

I'm working on a project. I want to add a toolbar to the software so I put some buttons in a panel . However the default button style doesn't meet my need. I want the button to have the following effects:

  1. When the mouse doesn't hover over the button, the button should looks like a JLabel. The icon in the button just looks like an image on the panel, i.e. all we can see is the icon in the button and other things are transparent.
  2. When the mouse hovers over the button, the button's border appears. It looks like a real button.

Example: Just like the buttons on the eclipse's toolbar.

Upvotes: 1

Views: 6018

Answers (4)

jjyao
jjyao

Reputation: 315

I got it. The answer to my question is the setContentAreaFilled() method. When the mouse hovers over the button, call the setContentAreaFilled(true). Otherwise call the setContentAreaFilled(false). Here is a relative code: link text

Upvotes: 2

Mark Peters
Mark Peters

Reputation: 81054

Why not use a JToolbar instead of a JPanel?

Upvotes: 2

jzd
jzd

Reputation: 23629

Extend JButton and:

  • Just add an Icon instead of Text to the button.
  • Add MouseMotionListener to capture hovering to show/hide border.

Upvotes: 1

Riduidel
Riduidel

Reputation: 22292

So, you want to customize your JButton renderings ?

First, for an all-inclusive soluition, you can take a look at existing LnF like Substance (obviously, it's a far too powerful solution for your need, however it may give you some inspiration).

Then, if you want to solve that by yourself, you'll have to override the paintComponent method.

For that, the first move is to subclass JButton.

Then, in your subclass, start by redefining the paintComponent(Graphics) method.

Notice that if all that is overcomplicated to you, you can also take a look at setBorderPainted(boolean) method.

Upvotes: 1

Related Questions