In my application I have a list of 6 Jlabels
, which are added to the contentPane
in a for
loop. After that I add 2 JButtons
- one for removing all the labels and the second one for adding them again:
public class Test {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 960, 620);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.getContentPane().setLayout(null);
frame.getContentPane().setBackground(new Color(30, 30, 30));
LinkedList<JLabel> labels = new LinkedList<>();
for(int i = 0 ; i < 6 ; i++) {
labels.get(i).setSize(280, 50);
labels.setBackground(new Color(75, 75, 75));
labels.setOpaque(true);
}
Button buttonAdd = new JButton("Add");
buttonAdd.setBounds(310, 15, 150, 50);
buttonAdd.addMouseListener(new MouseAdapter() {
@Override
public final void mouseClicked(MouseEvent event) {
for(int i = 0 ; i < 6 ; i++) {
labels.get(i).setLocation(15, 15+50*i);
frame.getContentPane().add(labels.get(i));
}
}
});
Button buttonRemove = new JButton("Remove");
buttonRemove.setBounds(310, 15, 150, 50);
buttonRemove.addMouseListener(new MouseAdapter() {
@Override
public final void mouseClicked(MouseEvent event) {
for(int i = 0 ; i < 6 ; i++) {
frame.getContentPane().remove(labels.get(i));
}
}
});
}
}
When I added the 6 labels outside of linsteners they were properly added to the ContentPane
and displayed. Yet, when I try to do this via the buttons, upon clicking the buttonAdd
nothing happens. They do not get displayed.
I tried messing with the hierarchy, setting the indices manually but nothing worked. I suspect the MouseListeners but I have no idea why this doesn't work.