环顾四周并且有一些类似的问题,但似乎没有一个问题显示如何在单个JFrame
中运行多个进度条,同时从其他3个线程更新它。
最好我计划有一个自己的进度条类,很多我看到人们在一个我不喜欢的主线程中进行所有进度条工作的例子。如果这就是你的意思,我很抱歉我以前从未使用过进度条。
我想监视机器人线程的进度。我将直接从Robot类发送更新到我的进度条,如果可能的话,在我的主程序中有一个progressbar对象。
我的主线程有点像这样
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
Motor m = new Motor();
Robot xRob = new Robot(cyclicBarrier, m);
Robot yRob = new Robot(cyclicBarrier, m);
Robot zRob = new Robot(cyclicBarrier, m);
Thread xRobThread = new Thread(xRob);
Thread yRobThread = new Thread(new Robot(cyclicBarrier, m));
Thread zRobThread = new Thread(zRob);
boolean clockwise = true, counterClockwise = false;
m.setMotor(clockwise, 14400000, xRob);
m.setMotor(clockwise, 0, yRob);
m.setMotor(counterClockwise, 36000000, zRob);
xRobThread.start();
yRobThread.start();
zRobThread.start();
这是我机器人课程的重要部分。
public class Robot implements Runnable{
public void run(){
System.out.println("Running: ");
m.Engage(this);
try {
System.out.println("Sleeping: ");
Thread.sleep(3000);
cyclicBarrier.await();
} catch (Exception e){
e.printStackTrace();
}
System.out.println("Engaging: ");
}
public void Rotate(){
if ((opcode & clockwise) > 0){
rotation++;
if(rotation == 360){
rotation = 0;
moveCount++;
}
}
if ((opcode & counter) > 0){
rotation--;
if(rotation == -360){
rotation = 0;
moveCount --;
}
}
}
}
这是我到目前为止的进度条
public class ProgressBar {
final int MAX = 100;
final JFrame frame = new JFrame("JProgress ");
final JProgressBar pbOne = new JProgressBar();
final JProgressBar pbTwo = new JProgressBar();
final JProgressBar pbThree = new JProgressBar();
ProgressBar(){
pbOne.setMinimum(0);
pbOne.setMaximum(MAX);
pbOne.setStringPainted(true);
pbTwo.setMinimum(0);
pbTwo.setMaximum(MAX);
pbTwo.setStringPainted(true);
pbThree.setMinimum(0);
pbThree.setMaximum(MAX);
pbThree.setStringPainted(true);
frame.setLayout(new FlowLayout());
frame.getContentPane().add(pbOne);
frame.getContentPane().add(pbTwo);
frame.getContentPane().add(pbThree);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
public void setProgress(int progress){
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
pb.setValue(progress); //HERE IS where I get lost. How do I differentiate between PBs and Threads
// As in which thread the code is coming from and which progress bar it's updating.
}
});
java.lang.Thread.sleep(100);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(frame, e.getMessage());
}
}
}
每次在我的机器人类中进行旋转时,我都会更新进度,但是我还没有实现,因为我想首先让设计失效。