简体   繁体   中英

JFrame is frozen by using a JComboBox

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM