简体   繁体   English

JFrame 使用 JComboBox 冻结

[英]JFrame is frozen by using a JComboBox

I am trying to remove a component from a Frame once a JComboBox is selected.选择 JComboBox 后,我试图从框架中删除一个组件。 But when I select one of the boxes the whole Frame freezes and you can't do anything other then resize or move it.但是当我 select 中的一个框时,整个框架冻结,除了调整大小或移动它之外你不能做任何事情。

        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.似乎 EventQueue 线程根本没有停止。 Why is this happening?为什么会这样?

This is because frame.remove(frame.getComponents().length - 1);这是因为frame.remove(frame.getComponents().length - 1); removes the JRootPane , so you are removing the root container.删除JRootPane ,因此您要删除根容器。

Having frame.getContentPane().remove(comboBox);frame.getContentPane().remove(comboBox); instead will remove the combobox.相反,将删除 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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