Change JButton Shape while respecting Look And Feel
Asked Answered
A

1

2

I know this question has been asked a million times, and can be done by overriding paintComponent(), but what I want to know is how to change the shape while respecting the current Look And Feel. If I want to change the shape to a circle, I also want the button to look like a button, just with a different shape.

I tried making a JButton, the overriding paintComponent, then clipping it to a circle, but I didn't get the border effects on Nimbus LAF.

Is there a better way? Or is there a method in JButton?

Afterburner answered 23/10, 2011 at 2:31 Comment(3)
PieceButton has a round Icon that may get you started on your sscce.Gaultiero
A component is unique for every LAF. So the shape/size/color/font is unique for every LAF. If you want to change the shape of a component then you need to rewrite the UI for the given LAF. Unless your LAF supports a Circle Border then you won't be able to do this. There is no shortcut. You need to write all the code.Trunk
@Trunk How do you do that without knowing the current LAF???Afterburner
S
1

For drawing components a ComponentUI is used. This UI class has a paint method and is used to paint the component. The paint method uses the settings of the L&F which are stored as properties in the UIManager.

To create your own component RoundButton extending from e.g. AbstractButton you can create your own RoundButtonUI (maybe extending from ButtonUI). Here you can create your own paint method using the properties of a normal button like Button.font or Button.foreground to draw your own component with the same L&F values as a normal button.

In your RoundButton class you should implement the method getUIClassID() which will return the string "RoundButtonUI". This causes your RoundButtonUI to be used.

A good example is JButton itself.

Sumac answered 27/10, 2011 at 7:57 Comment(3)
I guess this could be it although it still doesn't make the shaped button look perfectAfterburner
I used it a lot when we made a new L&f, you have to take care all the border and insets etc. are correct, to make the LayoutManager handle the component correctly. Maybe you can post your code.Sumac
Thanks, I got it with some tweaking. I think it look nice, and it still keeps the border effects thanks to how Nimbus is written!Afterburner

© 2022 - 2024 — McMap. All rights reserved.