2013-02-12 3 views
0

В принципе, существуют два разных типа BufferedImage img_w и img_b1 ... Как только я установил свой Jframe/label в один из них, он никогда не меняет или никогда не отсылает() к новому Imagebuffered значение ...Невозможно перекрасить внутри Jframe/label

заранее спасибо ..

BufferedImage img_w = new BufferedImage(old_width_i, old_height_i, BufferedImage.TYPE_INT_RGB); 
BufferedImage img_b1 = new BufferedImage(old_width_i, old_height_i, BufferedImage.TYPE_INT_RGB); 

// add data into the img_w and img_b1 

JFrame frame=new JFrame(); 
JLabel label = new JLabel(new ImageIcon(img_w)); 
frame.getContentPane().add(label, BorderLayout.WEST); 
frame.pack(); 
frame.setVisible(true); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

try { 
    Thread.sleep(1000); 
} catch (InterruptedException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

//I am trying to sleep only cause I want to make out if the image is changing or not or basically , to have a rotating illusion... 

System.out.println("Hello"); 
frame.getContentPane().add(new JLabel(new ImageIcon(img_w)), BorderLayout.WEST); 
frame.repaint(); 


label = new JLabel(new ImageIcon(img_b1)); 
frame.getContentPane().add(label,BorderLayout.WEST); //display the image (works) 
label.repaint(); //update the display?? 
frame.repaint(); 
frame.getContentPane().repaint(); 
+0

Чтобы лучше помочь, опубликуйте [SSCCE] (http://sscce.org/). –

+1

* «Как только я установил свой Jframe/label одному из них, он никогда не меняет или никогда не пересказывает() в новое значение Imagebuffered ...» * См. ['ImageViewer'] (http://stackoverflow.com/a/ 13512826/418556) для рабочего примера. –

ответ

3

Это ...

try { 
    Thread.sleep(1000); 
} catch (InterruptedException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

помешает интерфейс от рассмотрения запросов краски, пока она не закончится. Вы никогда не должны блокировать EDT.

Пример ниже (прост) и демонстрирует простой способ перемещения между изображениями вручную.

public class FlipPictures { 

    public static void main(String[] args) { 
     new FlipPictures(); 
    } 

    public FlipPictures() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception ex) { 
       } 

       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new PicturePane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

      } 
     }); 
    } 

    public class PicturePane extends JPanel { 

     private JLabel picture; 
     private File[] pictures; 
     private int currentPicture = -1; 

     public PicturePane() { 

      pictures = new File("/point/me/to/a/directory/of/images").listFiles(new FileFilter() { 
       @Override 
       public boolean accept(File pathname) { 
        String name = pathname.getName().toLowerCase(); 
        return name.endsWith(".png") 
          || name.endsWith(".gif") 
          || name.endsWith(".jpg") 
          || name.endsWith(".jpeg") 
          || name.endsWith(".bmp"); 
       } 
      }); 

      setLayout(new BorderLayout()); 
      picture = new JLabel(); 
      picture.setHorizontalAlignment(JLabel.CENTER); 
      picture.setVerticalAlignment(JLabel.CENTER); 
      add(picture); 

      JButton change = new JButton("Change"); 
      add(change, BorderLayout.SOUTH); 

      change.addActionListener(new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        changePicture(); 
       } 
      }); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(400, 400); 
     } 

     protected void changePicture() { 

      if (pictures != null && pictures.length > 0) { 

       currentPicture++; 
       if (currentPicture >= pictures.length) { 
        currentPicture = 0; 
       } 

       try { 
        // This is a potentionally blocking process and really should be threaded... 
        picture.setIcon(new ImageIcon(ImageIO.read(pictures[currentPicture]))); 
        picture.setText(null); 
       } catch (IOException ex) { 
        ex.printStackTrace(); 
        picture.setText(ex.getMessage()); 
       } 

      } else { 

       picture.setText("No Pictures :("); 

      } 

     } 

    } 

} 

Обновлено

Или, если вы предпочитаете, чтобы автоматически переключаться между изображениями

public class FlipPictures { 

    public static void main(String[] args) { 
     new FlipPictures(); 
    } 

    public FlipPictures() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception ex) { 
       } 

       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new PicturePane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

      } 
     }); 
    } 

    public class PicturePane extends JPanel { 

     private JLabel picture; 

     public PicturePane() { 
      setLayout(new BorderLayout()); 
      picture = new JLabel(); 
      picture.setHorizontalAlignment(JLabel.CENTER); 
      picture.setVerticalAlignment(JLabel.CENTER); 
      add(picture); 

      BackgroundSwitcher switcher = new BackgroundSwitcher(this); 
      switcher.execute(); 

     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(400, 400); 
     } 

     public void setPicture(BufferedImage image) { 

      picture.setIcon(new ImageIcon(image)); 

     } 

    } 

    public class BackgroundSwitcher extends SwingWorker<Void, BufferedImage> { 

     private File[] pictures; 
     private int currentPicture = -1; 
     private PicturePane picturePane; 

     public BackgroundSwitcher(PicturePane picturePane) { 
      pictures = new File("/point/me/to/a/directory/of/images").listFiles(new FileFilter() { 
       @Override 
       public boolean accept(File pathname) { 
        String name = pathname.getName().toLowerCase(); 
        return name.endsWith(".png") 
          || name.endsWith(".gif") 
          || name.endsWith(".jpg") 
          || name.endsWith(".jpeg") 
          || name.endsWith(".bmp"); 
       } 
      }); 
      this.picturePane = picturePane; 
     } 

     @Override 
     protected void process(List<BufferedImage> chunks) { 
      picturePane.setPicture(chunks.get(chunks.size() - 1)); 
     } 

     @Override 
     protected Void doInBackground() throws Exception { 
      if (pictures != null && pictures.length > 0) { 
       while (true) { 

        currentPicture++; 
        if (currentPicture >= pictures.length) { 
         currentPicture = 0; 
        } 

        try { 
         publish(ImageIO.read(pictures[currentPicture])); 
        } catch (IOException ex) { 
         ex.printStackTrace(); 
        } 
        Thread.sleep(1000); 
       } 
      } 
      return null; 
     } 
    } 
} 

Вы хотели бы взглянуть на Concurrency in Swing

2

Ваш код не является полным, так все, что мы можем сделать, это догадываться. В следующий раз отправьте сообщение SSCCE.

Я бы предположил, что проблема в том, что вы добавляете компонент в видимый кадр. Вы не вызывали revalidate() на панели, чтобы размер метки оставался (0, 0).

Однако нет необходимости создавать новую JLabel. Просто измените образ, вызвав метод setIcon() существующей метки, и ярлык будет перерисовываться. Нет необходимости ссылаться на repaint() на фрейм или любой другой компонент.

+0

+1 для aetIcon ... – MadProgrammer

Смежные вопросы