[英]How to display changing text in JLabel using for loop
public class UserInterface {
OpenFile of = new OpenFile();
JFrame jf = new JFrame("File Manager");
JButton jb1 = new JButton("Open File");
JLabel jl1 = new JLabel("Recommendations appear here");
JLabel jl2 = new JLabel();
JList<String> list;
public void build() {
DefaultListModel<String> str = new DefaultListModel<String>();
for (int i = 0; i < of.f.length; i++) {
str.addElement(of.f[i].getAbsolutePath());
}
list = new JList<String>(str);
Border b = BorderFactory.createLineBorder(Color.black, 2);
Font f = new Font("Arial", Font.BOLD, 20);
jb1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
of.OpenFileMethod(list.getSelectedValue());
}
});
jl1.setFont(f);
jl1.setBorder(b);
list.setFont(f);
jf.add(jl1).setBounds(30, 100, 300, 200);
jf.add(list).setBounds(400, 100, 300, 300);
jf.add(jb1).setBounds(250, 300, 100, 50);
jf.setLayout(null);
jf.setSize(800, 800);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 100; i++) {
jl1.setText("Loading.");
jl1.setText("Loading...");
}
}
}
for循環中的問題,僅將最后的“正在加載...”文本設置為JLabel,我希望它進入循環並打印100次。 可能是循環在啟動swing應用程序之前結束了。 有什么解決辦法嗎?
有什么解決辦法嗎?
他們沒有錯,這里的代碼可以完美地工作,但是這里的問題是當循環執行時,眨眼就可以完成!
在這種情況下,您最好的朋友是javax.swing.Timer
類
該示例將向您展示如何使用它,並希望解決您的問題,計時器具有自己的共享Thread
因此您不必擔心它會在掛起用戶界面或阻止代碼的情況下運行。
//this int determines the time delay for each time it executes it's actions
private int delay = 20;
private int times = 0;
private String text = "Loading ";
private Timer textTimer;
private class TimerAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
times++;
String theSetText = text;
for (int i = 0; i < times; i++) {
theSetText += ".";
}
if (times == 3) {
times = 0;
}
}
}
您始終可以通過timer.addActioListener
方法添加更多的動作偵聽器, timer.addActioListener
方法也將在那里循環。
對於您的問題,只需將上面的代碼添加到您的類中,然后在代碼中添加替換循環即可
textTimer = new Timer (delay,new TimerAction ());
textTimer.start();
當時間合適時(根據需要)當您希望停止時,只需致電
textTimer.stop();
停止計時器運行。 這是獲得有關主題如何使用擺動計時器的更多信息的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.