首页 > 解决方案 > 除非我单击窗口标题,否则 JLabel 无法正常工作

问题描述

我有一个程序,我试图显示一个图像,5 秒后它从 JLabel 中删除图像,然后显示第二个图像,但第二个图像不会自行显示,除非我单击顶部的标题或栏程序创建的窗口。我想在不与窗口交互的情况下自动显示图像。有什么帮助吗?

public void pictures(){
  try{
     BufferedImage myPicture = ImageIO.read(new File("round-1.jpg"));
     JLabel picLabel = new JLabel(new ImageIcon(myPicture));
     picLabel.setSize(800,600);
     add(picLabel);
     picLabel.setVisible(true);
     Timer timer = new Timer();
     timer.schedule(new TimerTask() {
          @Override
          public void run(){
             picLabel.setVisible(false);
             pictures2();
          }
       }, 5000);
     }
  catch(IOException e){
     e.printStackTrace();
  }
}

public void pictures2(){
  try{
     BufferedImage myPicture2 = ImageIO.read(new File("go.png"));
     JLabel picLabel2 = new JLabel(new ImageIcon(myPicture2));
     picLabel2.setSize(800,600);
     add(picLabel2);
     picLabel2.setVisible(true);
  }
  catch(IOException e){
     e.printStackTrace();
  }
}

标签: javaswingjlabel

解决方案


也许是因为您的计时器任务的工作(运行方法)在单独的线程中运行,而不是在 Swing 事件处理线程中?

我怀疑您应该调用SwingUtilities.invokeLater计时器的 run 方法,以便在 Swing 事件处理线程中完成对标签的更改。


推荐阅读