简体   繁体   中英

Remove panel from frame in thread

In my program, there is a MainFrame (just a JFrame) and a MainView (just a JPanel). In the timer-section you can see, that I want to remove the panel from the frame on editing the file, but nothing happens. The panel just stays on the frame and doesn't disappear.

public class MainClass {
private static String gesture;
private static MainFrame mainFrame;
private static MainView mainView;

public static void main(String[] args) {
    mainFrame = new MainFrame();
    mainFrame.setVisible(false);

    mainView = new MainView();
    mainFrame.add(mainView);

    mainFrame.setVisible(true);

    Timer gestureControl = new Timer();
    gestureControl.schedule(new TimerTask() {
        public void run() {
            String gestureNew = Filereader.getLines("/Users/alexanderjeitler-stehr/Desktop/widget.txt")[0];
            if(!gestureNew.equals(gesture)) {
                gesture = gestureNew;
                System.out.println(gesture);

                if(gesture.equals("1")) {
                    mainFrame.getContentPane().remove(mainView);
                    mainFrame.invalidate();
                    mainFrame.validate();
                }
            }
        }
    }, 0, 1000);
}
}

Change section like this:

if(gesture.equals("1")) {
    SwingUtilities.invokeLater() -> {
                mainFrame.getContentPane().remove(mainView);
                mainFrame.invalidate();
                mainFrame.validate();
                mainFrame.repaint();
    });
}

Or you might use invokeAndWait() of SwingUtilities.

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