簡體   English   中英

在Java Swing中更新主GUI元素

[英]Updating main GUI Elements in Java Swing

我正在嘗試更新java swing應用程序中的主要gui,因此有一個可運行的線程可以保持主gui可見,但問題是它在main中調用,而main是一個靜態函數。 我想說Element.SetTtext。 但是我要更新的所有調用都不是靜態的。 如何更新主GUI中的標簽,...等?

public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() 
            {
                new AGC().setVisible(true);
          // code to update labels here
            }
        });
    }

需要更多清晰度,何時需要更新標簽? 它是基於一個事件?

您始終可以保留要更新的組件的全局變量,並從事件處理程序訪問它。

您能否使用代碼更新您的問題,以便更清晰?

我從你的問題中理解的是,你認為靜態意味着不可改變。 Java不是這樣。 在Java中,永不改變的對象和組件被定性為final

保持你的主要簡單和小,並在doThings();進行循環和更改doThings();

這是一個Timer,以便更新JLabel的文本:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Foo extends JFrame {

    public Foo() {
        jLabel1 = new JLabel("label 1");
        jPanel1 = new JPanel();
        jPanel1.add(jLabel1);
        add(jPanel1);
        pack();
        // code to update whatever you like here
        doThings();
    }

    private void doThings() {
        // code to update whatever you like here
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                jLabel1.setText("foo " + (j++));
            }
        };
        Timer timer = new Timer(500, actionListener);
        timer.start();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Foo().setVisible(true);
            }
        });
    }
    private JLabel jLabel1;
    private JPanel jPanel1;
    private int j = 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM