开发者

Customize JButton style

I'm workin开发者_开发问答g 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.


Why not use a JToolbar instead of a JPanel?


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


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.


Extend JButton and:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜