Reputation: 796
So I have a gui where the layout is set to Null, and I put JLabels ontop of JButtons since the JButtons have icons and adding text to the button makes the button look distorted, so instead I am using JLabels ontop of the JButtons. Every time the mouse goes over the JButton when I test it, the JLabel disappears. How can I fix that so JLabels always appear above JButtons.
Edit: it distorts the button so the icon is taking up most the space and the button label is cut off by the opposite edge of the button.
Upvotes: 0
Views: 6539
Reputation: 3870
There is almost no cases when you will need to use null layout. You just need to do a little practice with the LayoutManagers
You can do the thing you wish to do with a JLayeredPane. Like this:
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(jLabelOnJButton());
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static JComponent jLabelOnJButton(){
JLayeredPane layers = new JLayeredPane();
JLabel label = new JLabel("label");
JButton button = new JButton("button");
label.setBounds(40, 20, 100, 50);
button.setBounds(20, 20, 150, 75);
layers.add(label, new Integer(2));
layers.add(button, new Integer(1));
return layers;
}
}
This is not a good solution I think. Only do it if you have no better solution.
Upvotes: 1
Reputation: 2196
If you're using a JFrame, as I assume you must be, you could add the labels to a JLayered pane that sits on top of the content pane.
Upvotes: 3