簡體   English   中英

定期更改JButton文本

[英]Changing JButton Text Periodically

我想創建一個JButton,它在第一次單擊后會定期更改其文本。 我對Swing庫不是很熟悉。 什么是一個很好的起點? 我可以不執行任何操作來更新其文本嗎?

謝謝。

對於Swing中的所有定期事件,我只建議使用javax.swing.Timer

例如,使用Timer輸出的應該是

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;

public class CrazyButtonTimer {

    private JFrame frame = new JFrame(" Crazy Button Timer");
    private JButton b = new JButton("Crazy Colored Button");
    private Random random;

    public CrazyButtonTimer() {
        b.setPreferredSize(new Dimension(250, 35));
        frame.getContentPane().add(b);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        javax.swing.Timer timer = new Timer(500, new TimerListener());
        timer.setInitialDelay(250);
        timer.start();
    }

    private class TimerListener implements ActionListener {

        private TimerListener() {
        }

        @Override
        public void actionPerformed(final ActionEvent e) {
            Color c = b.getForeground();
            if (c == Color.red) {
                b.setForeground(Color.blue);
            } else {
                b.setForeground(Color.red);
            }
        }
    }

    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                CrazyButtonTimer crazyButtonTimer = new CrazyButtonTimer();
            }
        });
    }
}

所有其他答案都未提及如何定期更新。 如果您需要它不定期更新,則可以在GUI類中創建一個方法,例如:updateButton();。 並在每次您希望它更改文本時調用它。

public void updateButton(String newText)
{
     Button.setText(newText);
}

只是以為我會添加這個,以防有人想不定期設置它。

如果您每隔固定的時間更改一次,則可以使用Swing Timer或Thread來執行此操作。 但是為此,您必須至少聽一個動作,以便您可以初始化並啟動它。

您還可以像下面這樣使用java.util中的TimerTask類:

java.util.TimerTask timerTask = new java.util.TimerTask() {
    @Override
    public void run() {
        //change button text here using button.setText("newText"); method
    }
};

java.util.Timer myTimer = new java.util.Timer();
myTimer.schedule(timerTask, 3 * 1000, 3* 1000); // This will start timer task after 3 seconds and repeat it on every 3 seconds.

我建議您創建一個計時器( 在這里您可以找到一些文檔)

Timer timer = new Timer(100,this);

您的類必須擴展動作監聽器,它實現了以下方法,該方法使您可以更改JButton的文本(我稱其為``按鈕'')。

public void actionPerformed(ActionEvent e) {
  if(e.getSource.equals(timer)){
    button.setText("newText");
  }
}

路卡

如果要定期更改它(例如每5秒更改一次),則可以創建一個新線程,該線程將按鈕的文本設置為所需的值並重新繪制(如有必要)。

暫無
暫無

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

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