問題,我試圖讓一個SwingWorker的工作。 我有下面的代碼的那一刻:用的SwingWorker
public class ImageWorker extends SwingWorker<Void, Void> implements KeyListener
{
private JLabel imageLabel;
private ImageIcon basicImage;
private ImageIcon whiteImage;
public static void main(String[] args)
{
new ImageWorker();
}
public ImageWorker()
{
final JFrame frame = new JFrame();
imageLabel = new JLabel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.getContentPane().add(imageLabel);
frame.setVisible(true);
try
{
basicImage = new ImageIcon(ImageIO.read(new File("src\\img\\basis1.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
whiteImage = new ImageIcon(ImageIO.read(new File("src\\img\\wit.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
}
catch(IOException ex)
{
ex.getMessage();
}
this.execute();
}
@Override
protected Void doInBackground()
{
try
{
while (true)
{
displayImage(basicImage);
Thread.sleep(1000L);
if(isCancelled())
return null;
}
}
catch(InterruptedException e)
{
e.getMessage();
}
return null;
}
private void displayImage(final Icon image)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(image);
}
});
}
我期待的圖像出現在的JLabel,但我只看到JFrame中彈出。文件正確加載我已經在另一個設置中測試過。 任何指針?
你究竟在做什麼,需要一個'SwingWorker'?它意味着用於在後臺執行某些密集操作但希望結果顯示在UI中的情況,因此需要在「Event Dispatch Thread」中執行某些操作,例如通過網絡加載映像。在這裏,它看起來像你只是不斷地顯示圖像。也許如果你解釋你想達到什麼,你會得到一個很好的答案。 – 2011-03-03 15:13:25
我沒有做任何事情,我只是試圖在JLabel上替換一些圖像,直到用戶按下一個鍵。但由於我不是程序員,我不知道從哪裏開始。我被告知SwingWorker將是一個容易開始的地方,因爲效率和代碼都不重要。這是我一次性使用某個課程的演示文稿(顯然不是CS相關的)。我在尋找快速ñ髒嘿嘿http://stackoverflow.com/questions/5179569/alternating-images-with-a-timer-using-java – Oxymoron 2011-03-03 15:17:57
好了,沒有什麼幫助。讓我再說一遍。 – 2011-03-03 15:25:37