Reputation: 313
I need to refresh my GUI each time a function is triggered. This is how I defined the skeleton of the GUI:
public class GUI {
private JFrame frame;
/**
* Launch the application.
*/
public static void runGui() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setSize(800, 600);
window.frame.setTitle("My Title");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//CODE
}
So, the GUI.runGui() function is called in a function like:
public void myFunction()
{
//CODE
GUI.runGui();
}
The problem is the following: every time this function is called, it generates a new instance of the GUI, so I end up having multiple instances. This is not what I want, since I just need to refresh the content of the GUI that must be only one. I believe the problem is architectural. Is there a way to solve this?
Upvotes: 0
Views: 1398
Reputation: 1
The solution is to get the content pane from the frame
and then use .repaint()
. You can do the following:
JFrame frame = new JFrame("Title");
frame.getContentPane().repaint();
Upvotes: 0
Reputation: 563
Look at what runGui is doing: it's creating and initializing a GUI every time you call it. Pull that one time initialization code out of runGui and into another place that you run once (like the initialize method). And in runGui access a component that you want to refresh (perhaps the content pane) as:
// This needs to become an instance method (non static) in this example in
// order to access the frame
public void runGui() {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Refresh your component here. Here I'm redrawing the
// content pane
frame.getContentPane().repaint();
}
});
}
Upvotes: 1
Reputation: 7434
frame.repaint();
This article contains some repaint examples:
https://www.programcreek.com/java-api-examples/?class=javax.swing.JFrame&method=repaint
Upvotes: 0