Home > Mobile >  JFrame is frozen by using a JComboBox
JFrame is frozen by using a JComboBox

Time:03-04

I am trying to remove a component from a Frame once a JComboBox is selected. But when I select one of the boxes the whole Frame freezes and you can't do anything other then resize or move it.

        JFrame frame = new JFrame();
        frame.setSize(800 , 800);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane() , BoxLayout.Y_AXIS));
        Gui gui = new Gui();

        JComboBox<ParabolaType> comboBox = new JComboBox<>(ParabolaType.values());
        comboBox.addActionListener(e -> {
            System.out.println("started");

            frame.remove(frame.getComponents().length - 1);
            frame.revalidate();

            System.out.println("finished");
        });

        frame.add(gui);
        frame.add(comboBox);
started
finished

It seems the EventQueue thread doesn't get stopped at all. Why is this happening?

CodePudding user response:

This is because frame.remove(frame.getComponents().length - 1); removes the JRootPane, so you are removing the root container.

Having frame.getContentPane().remove(comboBox); instead will remove the combobox.

Here you have a working example

JFrame frame = new JFrame();
frame.setSize(800, 800);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JLabel gui = new JLabel("okokok");
JComboBox<String> comboBox = new JComboBox<String>(new String[]{"Someting1", "Something2"});
comboBox.addActionListener(e -> {
    System.out.println("started");
    frame.getContentPane().remove(comboBox);
    frame.repaint();
    System.out.println("finished");
});
frame.add(gui);
frame.add(comboBox);
frame.setVisible(true);
  • Related