[英]How to reload a Java Swing GUI?
每次觸發 function 時,我都需要刷新我的 GUI。 這就是我定義 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
}
因此,GUI.runGui() function 在 function 中被調用,例如:
public void myFunction()
{
//CODE
GUI.runGui();
}
問題如下:每次調用這個 function 時,它都會生成一個新的 GUI 實例,所以我最終有多個實例。 這不是我想要的,因為我只需要刷新必須只有一個的 GUI 的內容。 我相信問題出在架構上。 有沒有辦法解決這個問題?
看看 runGui 正在做什么:每次調用它時它都會創建和初始化一個 GUI。 將那一次初始化代碼從 runGui 中拉出並放到您運行一次的另一個地方(如 initialize 方法)。 並在 runGui 中訪問要刷新的組件(可能是內容窗格),如下所示:
// 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();
}
});
}
frame.repaint();
本文包含一些重繪示例:
https://www.programcreek.com/java-api-examples/?class=javax.swing.JFrame&method=repaint
解決方案是從frame
中獲取內容窗格,然后使用.repaint()
。 您可以執行以下操作:
JFrame frame = new JFrame("Title");
frame.getContentPane().repaint();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.