Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bring a component on a JPanel to front (Java)

In VB, you can use zOrder. In .Net, it's .SetChildIndex.

Before you ask, no I'm not using a layout manager in this case. If you have two components on top of each other, how do you change the order after they have already been displayed?

I have a button that slightly overlaps on top of another component (label), due to the lack of space. I added the JLabel to the form before the button, and when the form loads, it looks fine. However when the user clicks the button, the JLabel goes to the back, making a chunk of it disappear. Is there a way to keep it to the front? I have tried putting label.grabFocus() in the button's ActionListener but it did not work.

like image 530
David Avatar asked Aug 10 '11 12:08

David


3 Answers

When compnents overlap on the panel then you need to tell the panel so it can make sure it repaints the components in their proper ZOrder:

You do this by overriding the isOptimizedDrawingEnabled() method of the JPanel to return false.

like image 100
camickr Avatar answered Oct 10 '22 00:10

camickr


you can also use the LayeredPane of your JFrame. With JFrame.getLayeredPane() you get a reference of the pane in use.

the add method of LayeredPane has up to 2 additional int parameters. the first specified the Layer of the component you'd add and the second contols the order inside this layer.

You can find more infos at http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html#layeredpane

like image 29
Dragon8 Avatar answered Oct 09 '22 23:10

Dragon8


Firstly, this appears to be a poor design. Though label.repaint() works, its not the way you should do it. You are not specifying explicitly how these components overlap one on the other. For that a better approach would be Layered Panes. The java's counterpart for zOrder is Layered Pane. This link should help you: http://download.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

just tell me if you have any problem.

like image 20
sasidhar Avatar answered Oct 10 '22 00:10

sasidhar