这是我正在努力做的事情 - 长话短说: 构建一个窗口(将称为MainWindow),顶部有按钮,中间有一个图片。我想让用户选择在每隔几秒更改中心图片时选择要做的事情(按钮)。给用户的部分选项是“暂停”和“恢复” - 控制序列。 基本上尝试通过线程更新GUI(MainWindow)。这个线程将运行,而布尔'playSequence'将为真。
有人可以解释为什么我不能让它工作..
以下是代码:
package SpecializedControls;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import DataEntities.SgiImage;
public class SgiImagePanel extends JPanel implements Runnable {
private List<SgiImage> seqImageList;
private JLabel lastImage;
private boolean playSequence;
public SgiImagePanel (){}
public SgiImagePanel (List<SgiImage> sequenceList)
{
seqImageList = sequenceList ;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(playSequence)
{
for (SgiImage image : seqImageList)
{
display(image);
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void display(SgiImage image)
{
reset();
JLabel picLabel = new JLabel(new ImageIcon(image.getImage()));
add(picLabel);
lastImage = picLabel;
}
public void display(List<SgiImage> sequenceList)
{
if(sequenceList==null)
return;
playSequence = true;
SgiImagePanel seq = new SgiImagePanel(sequenceList);
Thread thread = new Thread(seq);
thread.start();
}
public void reset(){
if (lastImage != null)
{
remove(lastImage);
lastImage = null;
}
}
public void pause() {
playSequence = false;
}
public void resume(){
playSequence = true;
}
}
答案 0 :(得分:2)
setIcon(...)
方法交换图标。 stop()
方法即可轻松暂停Swing Timer,并可以通过调用start()
轻松重启。答案 1 :(得分:0)
尝试使用以下代码加载图片:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}