How to reset my GUI in Java with a JMenuItem?

294 views Asked by At

I have a public JFrame with a CardLayout, this JFrame includes some JPanels for different stages of analysis, I want to return to the main panel and erase all data stored in the objects to start a new analysis using a JMenuItem, but I don't know which function could do that. Any suggestion?

I have tried with this code, a jMenuItem1ActionPerformed which just backs to that jpanel but doesn't reset the gui. "Seleccion" is the main jpanel, the main menu of the application

panelPrincipal.removeAll();
panelPrincipal.revalidate();
panelPrincipal.repaint();

panelPrincipal.add(seleccion);
panelPrincipal.revalidate();
panelPrincipal.repaint();
2

There are 2 answers

0
Hovercraft Full Of Eels On

There is no "one-size-fits-all" solution, and there is no core Java "function" that you can call for this since it all depends on the structure of your program. In other words, you will have to create your own reset mechanism. Hopefully, your program structure is built around an Model-View-Control (MVC) type of pattern, and if so, then your JMenuItem's listener would notify the Control of the user's wish to reset, the Control would call reset() on the Model (a method which you would have to create of course) which would reset the Model to the initial state. The View which should have listeners attached to the Model will then change its display accordingly.

0
user3437460 On

From your codes you probably tried every means you can think of to reset everything to initial state.

Personally, I do not think it is a good idea to remove all Components and add it back simply just because you want to reset it. You have to write your own codes to specifically tell Java what things need to change (reset).

For example if you have 3 text fields, you can do it in your action listener:

public void actionPerformed(ActionEvent e){
    txtField1.setText("");
    txtField2.setText("");
    txtField3.setText("");
}

Doing this works, but it looks pretty much hard-coded and it is hard to maintain. Image if you have 999 textfields to deal with. You can always improve your program structure for example like:

input --> update database --> text fields read from database

Input updates database. The fields just read from the database. If you want to reset everything, just clear of the data in the database.

public void actionPerformed(ActionEvent e){
    //Delete records from database
    //Instead of updating all 999 fields.
}

This is just an example. It is up to you to decide how your program shall be structured.

repaint() basically just inform the paintManager to call the paintComponent() method, you probably won't see any difference in your UI appearance for calling that unless you have been doing things like overriding paintComponent() and making changes to the look and feel of the JComponents or using Graphics for drawing.