0

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);
}
}
  • Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Jan 04 '18 at 12:02
  • *"Remove panel from frame in thread"* - Don't. Swing is NOT thread safe and any modification to the UI should only be done from within the context of the Event Dispatching Thread. If you need to use a thread and need to interact with the UI, you're better off using a `SwingWorker`. You should also be focusing on revalidating and repainting the container you've changed and not it's parent – MadProgrammer Jan 04 '18 at 12:04

1 Answers1

1

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.

brummfondel
  • 1,202
  • 1
  • 8
  • 11