2012-03-09 3 views
1

Приветствую всех, я здесь немного. Когда я запускаю программу и нажимаю кнопку отправки, она должна менять 4 снимка каждые 2 секунды. Однако это не перерисовывает изображения. Если кто-то может дать мне руку, было бы здорово. Я использую eclipse, и программа компилируется и работает. Вот код.не перерисовывает изображение s

/** Here is the GUI of the program 
* class name SlideShowGui.java 
* @author Kiril Anastasov 
* @date 07/03/2012 
*/ 

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

public class SlideShowGui extends JPanel implements ActionListener, Runnable 
{ 
    JLabel name, comments, images; 
    JTextField namejtf, commentsjtf, captionjtf; 
    JButton submit; 
    ImageIcon pictures1, pictures2, pictures3, pictures4; 
    //ImageIcon []pictures2 = {galileo1.jpg}; 


    SlideShowGui() 
    { 


     name = new JLabel("Name:"); 
     this.add(name); 

     namejtf = new JTextField(15); 
     this.add(namejtf); 

     comments = new JLabel("Comments:"); 
     this.add(comments); 

     commentsjtf = new JTextField(15); 
     this.add(commentsjtf); 

     submit = new JButton("Submit"); 
     this.add(submit); 
     submit.addActionListener(this); 


     pictures1 = new ImageIcon("galileo1.jpg"); 
     images = new JLabel(pictures1); 
     this.add(images); 


     pictures2 = new ImageIcon("galileo2.jpg"); 
     this.add(images); 
     pictures3 = new ImageIcon("galileo3.jpg"); 
     this.add(images); 
     pictures4 = new ImageIcon("galileo4.jpg"); 
     this.add(images); 



     captionjtf = new JTextField(24); 
     this.add(captionjtf); 
     //pictures = new ImageIcon("galileo1.jpg"); 
     // images.setIcon(pictures); 
    } 

    public void actionPerformed(ActionEvent ae) 
    { 
     Thread t = new Thread(this); 
     t.start(); 

     if(ae.getSource() == submit) 
     { 

      int i = 0; 
      boolean go = true; 
      while(go) 
      { 

       i++; 
       System.out.println(i); 

       try 
       { 
        Thread.sleep(2000); 

         if(i == 1) 
         { 
          pictures1 = new ImageIcon("galileo1.jpg"); 
          images.setIcon(pictures1);                          
          System.out.println("picture 1 should be displayed here"); 
         } 
         if(i == 2) 
         { 
          pictures2 = new ImageIcon("galileo2.jpg"); 
          images.setIcon(pictures2); 
          System.out.println("picture 2 should be displayed here"); 

         } 
         if(i == 3) 
         { 
          pictures3 = new ImageIcon("galileo3.jpg"); 
          images.setIcon(pictures3); 
          System.out.println("picture 3 should be displayed here"); 
         } 
         if(i == 4) 
         { 
          pictures4 = new ImageIcon("galileo4.jpg"); 
          images.setIcon(pictures4); 
          System.out.println("picture 4 should be displayed here"); 
         } 


         if(i == 4) 
         { 
           i = 0; 
         } 


       } 
       catch (InterruptedException ie) 
       { 
        System.out.println("thread exception"); 
       } 

     } 
    } 

} 

    public void run() 
    { 

    } 
} 

/**The driver class of the program. Here is the JFrame 
* class name TestSlideShow.java 
* @author Kiril Anastasov 
* @date 07/03/2012 
*/ 

import java.awt.*; 
import javax.swing.*; 
public class TestSlideShow 
{ 
    public static void main(String[] args) 
    { 
     JFrame application = new JFrame(); 
     SlideShowGui panel = new SlideShowGui(); 
     application.add(panel); 
     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     application.setSize(300,600); 
     application.setLocation(400,100); 
     application.setVisible(true); 


    } 

} 
+1

Нет, ты опять забыл, вчера тот же вопрос, ответили @mKorbel, вы забыли применить хотя бы одну вещь, которую он сказал. Никогда не используйте 'Thread.sleep (...)' в Swing, что заморозит ваше приложение. Скорее используйте 'javax.swing.Timer' для достижения такого поведения. Где ваш EDT? –

+1

@Gagandeep Bali stunt man :-) – mKorbel

ответ

5

Всегда используйте javax.swing.Timer Никогда не используйте Thread.sleep(...) в Swing atleast. Вот попробуйте этот код, но заменить path к изображениям:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class SlideShow extends JPanel 
{ 
    private int i = 0; 
    private Timer timer; 
    private JLabel images = new JLabel(); 
    private Icon bg = UIManager.getIcon("OptionPane.warningIcon"); 
    private Icon red = UIManager.getIcon("OptionPane.errorIcon"); 
    private Icon blue = UIManager.getIcon("OptionPane.informationIcon"); 
    private ImageIcon pictures1, pictures2, pictures3, pictures4; 
    private ActionListener action = new ActionListener() 
    { 
     public void actionPerformed(ActionEvent ae) 
     {   

      boolean go = true; 

      i++; 
      System.out.println(i); 

      if(i == 1) 
      { 
       images.setIcon(bg);                          
       System.out.println("picture 1 should be displayed here"); 
      } 
      if(i == 2) 
      { 
       images.setIcon(red); 
       System.out.println("picture 2 should be displayed here"); 
      } 
      if(i == 3) 
      { 
       images.setIcon(blue); 
       System.out.println("picture 3 should be displayed here"); 
      } 
      if(i == 4) 
      { 
       images.setIcon(bg); 
       System.out.println("picture 4 should be displayed here"); 
      } 
      if(i == 5) 
      { 
       go = false; 
       timer.stop(); 
       System.exit(0); 
      } 
      revalidate(); 
      repaint(); 
     } 
    }; 

    public SlideShow() 
    { 
     JFrame frame = new JFrame("SLIDE SHOW"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationByPlatform(true); 

     frame.getContentPane().add(this); 

     add(images); 

     frame.setSize(300, 300); 
     frame.setVisible(true); 
     timer = new Timer(2000, action);  
     timer.start(); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new SlideShow(); 
      } 
     }); 
    } 
} 
+0

Привет, друг, это было действительно полезно !!! – Kiril

+0

@Kiril: Хе-хе, Просто запомните - Держите Smiling :-) –

+0

sooo nice answer +1 – mKorbel

4

Весь if (i == ... часть может быть упрощена. Объявите статический член класса в SlideShowGUI:

private final static ImageIcon[] icons = {new ImageIcon("galileo1.jpg"), 
              new ImageIcon("galileo2.jpg"), 
              new ImageIcon("galileo3.jpg"), 
              new ImageIcon("galileo4.jpg")}; 

и использовать его в замене if заявления:

images.setIcon(icons[i-1]); 
System.printf("Picture %s should be displayed%n", i-1); 
if (i == 4) { 
    i = 0; 
} 
+0

(мой ответ был общим намеком, и он не должен решить реальную проблему с перерисовыванием изображений ...) –

+0

это [одна из причин, почему очередь существует] (http: // stackoverflow .com/a/7944388/714968) +1 для базовых вещей – mKorbel

4

Вы можете упростить код, как упоминалось Andreas_D.

Ваш текущий проект заблокирует основной поток, как вы его вызываете, Thread.sleep(), это заморозит ваше приложение.

Если вы хотите обновить Image, вы должны реализовать код обновления внутри метода run().

Так что если вы обнаружите, что пользователь нажимает на отправку JButton, создайте и запустите новый Thread для обновления пользовательского интерфейса.

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