Adding a child component to a JButton
-
16-09-2019 - |
Question
Is it possible to place a child component inside a JButton
and make it transparent to a subset of mouse events so that:
- The child component receives
MouseMotionEvent
s (so it can respond by modifying a displayed image) - Clicking still depresses the
JButton
"behind" the child component
If you add the child component to the button but make no other changes, clicking in the area occupied by the child does not activate the button.
I know this can be achieved by creating a new class that extends JButton
but I would prefer to use a child component which has already been written.
Note: this is purely for cosmetic reasons. The child component only changes its own appearance. It does not perform any other actions in response to clicks. There is just one Action
, triggered by the button in the normal way.
Solution
Yes, it is possible but probably there are better ways to change the appearance of a JButton on mouse over. You can extend a ButtonUI to do that. However, if you want to drop a component over a JButton, you should pass other mouse events (e.g clicks) to the underlying JButton.
OTHER TIPS
JXLayer is just the thing you need. Check out https://jxlayer.dev.java.net/ The project site has several good articles about JXLayer's usage for many different use cases.