我有一个加载条,每次设置它的值时都不会重新绘制。我试过多次最大化和最小化屏幕,但仍然显示0%的进度。代码尚未完成。任何的想法? 代码:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LoadingTest {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
F f = new F("Loading Bar Test");
}
}
class F extends JFrame implements Runnable, ActionListener {
private static final long serialVersionUID = 4684842549708528589L;
private JProgressBar variableBar = new JProgressBar(0,100);
private JProgressBar randomGenBar = new JProgressBar(0,100);
private JProgressBar addBar = new JProgressBar(0,100);
private JProgressBar totalbar = new JProgressBar(0,100);
private JButton button;
public F(String str) {
setTitle(str);
setDefaultCloseOperation(3);
getContentPane().setLayout(new GridLayout(9,1));
variableBar.setStringPainted(true);
variableBar.setValue(0);
button = new JButton("Run Tasks");
button.addActionListener(this);
add(button);
add(new JLabel("Creating variables..."));
add(variableBar);
add(new JLabel("Generating Random Values..."));
add(randomGenBar);
add(new JLabel("Adding Values..."));
add(addBar);
add(new JLabel("Total Progress:"));
add(totalbar);
pack();
setVisible(true);
}
public void run() {
int p = 5;
int i1;
variableBar.setValue(p);
int i2;
p += 5;
variableBar.setValue(p);
int i3;
p += 5;
variableBar.setValue(p);
int i4;
p += 5;
variableBar.setValue(p);
int i5;
p += 5;
variableBar.setValue(p);
int i6;
p += 5;
variableBar.setValue(p);
int i7;
p += 5;
variableBar.setValue(p);
int i8;
p += 5;
variableBar.setValue(p);
int i9;
p += 5;
variableBar.setValue(p);
int i10;
p += 5;
variableBar.setValue(p);
int i11;
p += 5;
variableBar.setValue(p);
int i12;
p += 5;
variableBar.setValue(p);
int i13;
p += 5;
variableBar.setValue(p);
int i14;
p += 5;
variableBar.setValue(p);
int i15;
p += 5;
variableBar.setValue(p);
int i16;
p += 5;
variableBar.setValue(p);
int i17;
p += 5;
variableBar.setValue(p);
int i18;
p += 5;
variableBar.setValue(p);
int i19;
p += 5;
variableBar.setValue(p);
int i20;
p += 5;
variableBar.setValue(p);
}
private F() {
}
public void actionPerformed(ActionEvent e) {
new Thread(new F()).start();
}
}
答案 0 :(得分:3)
您正在actionPerformed方法中创建一个新的F对象。未示出的F对象中的JProgressBar正在进行中,但不在您正在显示的那个中。
尝试更改此内容:
new Thread(new F()).start();
到此:
new Thread(this).start();
看看会发生什么。
顺便说一下,你是从后台线程进行Swing调用,这是你绝对不应该做的事情。而是使用SwingWorker,设置其progress属性,然后使用PropertyChangeListener在Swing事件线程上侦听该属性。
除了编号2:您编写的后台主题将立即完成,因此您不会看到任何渐进的进展,而是立即完成进度。
答案 1 :(得分:1)
当ActionEvent
进入时,您将在新的run()
上启动Thread
方法,而不是事件调度线程,其中必须进行所有UI更新。< / p>