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.
By default Swing assumes components don't overlap so components can be repainted more efficiently. That is when you change a property on a component, only that component needs to be repainted.
When components overlap on the panel then you need to tell the panel so it can make sure all components are repainted in their proper ZOrder:
You do this by overriding the isOptimizedDrawingEnabled()
method of the JPanel to return false
.
JPanel panel = new JPanel()
{
@Override
public boolean isOptimizedDrawingEnabled()
{
return false;
}
}