[英]Jslider can not tick when its value changed from JButton periodically
我正在做一个swing
项目。 有一张地图,我有给定数据在不同时间的栅格图像。 通常,我通过JSlider
更改时间,并且它请求服务器提供光栅图像。 然后,我将响应图像添加到地图。 有一个Play JButton
,当按下它时,会将那些图像一一添加到地图的栅格图层。 它将被视为动画。 在该JButton's
actionPerfomed
方法中,我在for循环中更改了JSlider's
值。
我的问题是当我按Play JButton
,我看不到数据在播放,但是我知道代码块有效,因为我记录了每个图像(来自服务器)。 我发现这是因为JButton
在其actionPerformed
方法结束之前不会释放Focus
。 因为JButton
看起来一直被按下直到结束。 所以我只看到地图上的最后一张图像。
首先,我尝试了JButton.setFocusable(false)
等,但是效果不佳。
其次,我尝试使用SwingWorker
。 我这样添加它:
class PlayMvgmLayerWorker extends SwingWorker<Void, Void> {
public PlayMvgmLayerWorker(String title) {
super(title);
}
@Override
protected void done(Void aVoid) {
}
@Override
protected Void doInBackground() {
try{
BufferedImage[] image = new BufferedImage[24];
for(int i=0; i<24; i++) {
final int value = i - 48 + 24;
timeSlider.setValue( value );
Thread.sleep(10000l);
}
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
}
private JButton animation = new JButton("");
animation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new PlayMvgmLayerWorker("title").execute();
}
});
private JSlider timeSlider = new JSlider();
timeSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
// time consuming processes ( server call, add image to map, etc)
}
});
我试图简化它。
它比以前好很多,但是我仍然看不到数据正确播放。 有时,在JSlider
滴答之后播放数据。 可能是因为我的耗时过程在second components(JSlider)
stateChanged
事件中吗? 我是否也应该在JSlider's
事件中使用第二个SwingWorker
? 关于我该怎么办的任何建议?
此外,在播放数据之前禁用所有组件并在播放数据之后启用它们的最佳方法是什么?
提前非常感谢你
如果必须同时运行两个活动Activity A和Activity B,则需要为第二个活动创建一个线程-第一个活动将已经在其自己的线程(主程序)中运行。
该方案如下:
Program A:
create new Thread: Activity B
run allother tasks for Activity A
更具体地说,以下程序将运行您的仿真并更新滑块的刻度:
public P() {
animation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doInBackgroundImp();
}
});
setSize(500, 500);
setLayout(new FlowLayout());
add(animation);
add(timeSlider);
setVisible(true);
}
protected void doInBackgroundImp() {
Thread th=new Thread() {
public void run() {
try{
for(int i=0; i<24; i++) {
final int value = i - 48 + 24;
timeSlider.setValue( i );
System.out.println(timeSlider.getValue()+" "+value);
Thread.sleep(1000);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
};
th.start();
}
private JButton animation = new JButton("");
private JSlider timeSlider = new JSlider();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.