【发布时间】:2015-05-16 19:17:35
【问题描述】:
如果在此之前确实有人问过这个问题,请提前道歉。我真的试图找到对我有帮助的东西。可惜我没有运气。
这是我的情况:
我有一个带有按钮和滑块的 Frame 类。我有一个线程类。使用框架类中的按钮,我创建线程类的实例。线程类的一个实例代表一张图片。所有的子线程(图片)都会显示在同一帧中,并以一定的间隔移动。
这是我的问题:
滑块控制运动画面的间隔。所以他们移动得更快或更慢。所有图片应该同时变快或变慢。不幸的是,只有第一个创建的线程会受到滑块的影响。我的 ComponentAdapter 也有同样的问题,它有他的 componentResized 函数。所有线程(或图片)应相对于帧大小同时变大或变小。
在这里,我将尝试大致向您展示我是如何做到的:
框架类:
//The actionPerformed for the button that keeps creating threads
//Every thread is a picture (ant in this case) that
// moves through the same field of buttons
public void actionPerformed(ActionEvent e){
a = new AmeiseThread(this);
a.start();
}
// The slider in the frame.When it changes, also the picture movement speed changes
sliderKind.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
a.sleeptime = 1000 / speed;
}
}
});
// Whenever the Frame gets resized, it will change the Pictures
// on its buttons relatively to its new size
class MyComponentAdapter extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
xScale = jbArray.get(1).getSize().width;
yScale = jbArray.get(1).getSize().height;
a.ameisen.clear();
a.ameisen.add(new ImageIcon(new ImageIcon("ameise.gif").getImage()
.getScaledInstance(xScale, yScale, Image.SCALE_SMOOTH)));
a.ameisen.add(new ImageIcon(new ImageIcon("ameise90.gif").getImage()
.getScaledInstance(xScale, yScale, Image.SCALE_SMOOTH)));
a.ameisen.add(new ImageIcon(new ImageIcon("ameise180.gif").getImage()
.getScaledInstance(xScale, yScale, Image.SCALE_SMOOTH)));
a.ameisen.add(new ImageIcon(new ImageIcon("ameise270.gif").getImage()
.getScaledInstance(xScale, yScale, Image.SCALE_SMOOTH)));
}
}
我想不出我的线程类中写的任何内容,这可能是有趣的。我认为问题出在我已经在某处发布的代码中。但是,如果您确实需要更多信息,请发表评论,我会立即发布更多信息。
再次抱歉,如果该问题已经存在。我觉得确实如此,因为它听起来很简单。虽然我真的试图找到一个类似的问题,但我没有运气。
【问题讨论】:
-
您应该使用静态字段或保存您创建的所有线程并在滑块更改时对其进行迭代。
标签: java multithreading resize synchronized