2013-04-30 52 views
0

我正在製作一個記憶遊戲,我想設置它,所以我點擊第一個"card",然後第二個,如果它們不相同,第二個卡片顯示幾秒鐘然後他們回到"non-flipped"的位置。SwingWorker,Thread.sleep()或javax.swing.timer?我需要「插入一個暫停」

我試過使用SwingWorker,Thread.sleepSwingTimer但我無法得到它的工作。使用Thread.sleep第二張牌不會"flip"如果它是重複的,它會等待睡眠時間並消失。如果它不匹配,則「正面朝下」等待,在睡眠定時器之後,第一張卡片會翻轉。無論我放置Thread.sleep的位置如何,都會發生這種情況。

隨着Swing Timer它只看起來「改變定時器」,而我與卡互動,所以我最終翻動8張卡之前,它激活。

我沒有與SwingWorker運氣,我甚至不知道它會爲我正在尋找的工作。

這是我的代碼:

class ButtonListener implements ActionListener 
    { 

     public void actionPerformed(ActionEvent e) 
     { 
      for(int index = 0; index < arraySize; index++) 
      { 

       if(button[index] == e.getSource()) 
       { 
        button[index].setText(String.valueOf(cards.get(index))); 
        button[index].setEnabled(false); 

        number[counter]=cards.get(index); 

        if (counter == 0) 
        { 
         counter++; 
        } 
        else if (counter == 1) 
        { 
         if (number[0] == number[1]) 
         { 
          for(int i = 0; i < arraySize; i++) 
          { 
           if(!button[i].isEnabled()) 
           { 
            button[i].setVisible(false); 
           } 
          } 
         } 
         else 
         { 
          for(int i = 0; i < arraySize; i++) 
          { 
           if(!button[i].isEnabled()) 
           { 
            button[i].setEnabled(true); 
            button[i].setText("Card"); 
           } 
          } 
         } 

         counter = 0; 
        } 
       } 
      } 
     } 
    } 

基本上就是我需要的是當計數器== 1,並且該卡不匹配這個代碼來執行:

button[index].setText(String.valueOf(cards.get(index))); 
        button[index].setEnabled(false); 

然後暫停,所以card is revealed那個時候,最後它恢復到卡面朝下的位置。

這是我試圖用Thread.sleep()

class ButtonListener implements ActionListener 
    { 

     public void actionPerformed(ActionEvent e) 
     { 
      for(int index = 0; index < arraySize; index++) 
      { 

       if(button[index] == e.getSource()) 
       { 
        button[index].setText(String.valueOf(cards.get(index))); 
        button[index].setEnabled(false); 

        number[counter]=cards.get(index); 

        if (counter == 0) 
        { 
         counter++; 
        } 
        else if (counter == 1) 
        { 
         if (number[0] == number[1]) 
         { 
          for(int i = 0; i < arraySize; i++) 
          { 
           if(!button[i].isEnabled()) 
           { 
            button[i].setVisible(false); 
           } 
          } 
         } 
         else 
         { 
          try 
          { 
           Thread.sleep(800); 
          } 
          catch (InterruptedException e1) 
          { 
           e1.printStackTrace(); 
          } 

          for(int i = 0; i < arraySize; i++) 
          { 
           if(!button[i].isEnabled()) 
           { 
            button[i].setEnabled(true); 
            button[i].setText("Card"); 
           } 
          } 
         } 

         counter = 0; 
        } 
       } 
      } 
     } 
    } 

預先感謝任何建議

+3

如果你正在使用'Thread.sleep()方法'確保你不睡覺,在事件指派線程 – 2013-04-30 05:09:05

+2

使用一個Swing'Timer'這一點​​。爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-04-30 05:16:10

+0

我以錯誤的方式使用Swing Timer,我終於設法讓它工作嘿嘿。無論如何,謝謝你。 – user2334483 2013-04-30 06:40:06

回答

3

使用javax.swing.Timer安排未來的事件來觸發。這將允許您安全地更改UI,因爲計時器是在事件分派線程的上下文中觸發的。

能夠同時翻轉多張卡片的問題與您沒有設置阻止用戶翻轉卡片,然後使用計時器的狀態有關。

以下示例基本上一次只允許一個卡片每組翻轉一次。

一旦在兩組中都翻轉了一張卡,計時器就會啓動。當它被觸發時,卡被重置。

enter image description here

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Insets; 
import java.awt.LinearGradientPaint; 
import java.awt.Point; 
import java.awt.Rectangle; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.image.BufferedImage; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import java.io.File; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 
import java.util.Random; 
import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.border.LineBorder; 

public class FlipCards { 

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

    public FlipCards() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class Card extends JPanel { 

     private BufferedImage image; 
     private boolean flipped = false; 

     private Dimension prefSize; 

     public Card(BufferedImage image, Dimension prefSize) { 
      setBorder(new LineBorder(Color.DARK_GRAY)); 
      this.image = image; 
      this.prefSize = prefSize; 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return prefSize; 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      LinearGradientPaint lgp = new LinearGradientPaint(
        new Point(0, 0), 
        new Point(0, getHeight()), 
        new float[]{0f, 1f}, 
        new Color[]{Color.WHITE, Color.GRAY}); 
      g2d.setPaint(lgp); 
      g2d.fill(new Rectangle(0, 0, getWidth(), getHeight())); 
      if (flipped && image != null) { 
       int x = (getWidth() - image.getWidth())/2; 
       int y = (getHeight() - image.getHeight())/2; 
       g2d.drawImage(image, x, y, this); 
      } 
      g2d.dispose(); 
     } 

     public void setFlipped(boolean flipped) { 

      this.flipped = flipped; 
      repaint(); 

     } 
    } 

    public class CardsPane extends JPanel { 

     private Card flippedCard = null; 

     public CardsPane(List<BufferedImage> images, Dimension prefSize) { 
      setLayout(new GridBagLayout()); 
      MouseAdapter mouseHandler = new MouseAdapter() { 
       @Override 
       public void mouseClicked(MouseEvent e) { 
        if (flippedCard == null) { 
         Card card = (Card) e.getComponent(); 
         card.setFlipped(true); 
         flippedCard = card; 
         firePropertyChange("flippedCard", null, card); 
        } 
       } 
      }; 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.insets = new Insets(4, 4, 4, 4); 
      gbc.fill = GridBagConstraints.BOTH; 
      gbc.weightx = 0.25f; 
      for (BufferedImage img : images) { 
       Card card = new Card(img, prefSize); 
       card.addMouseListener(mouseHandler); 
       add(card, gbc); 
      } 
     } 

     public Card getFlippedCard() { 
      return flippedCard; 
     } 

     public void reset() { 
      if (flippedCard != null) { 
       flippedCard.setFlipped(false); 
       flippedCard = null; 
      } 
     } 
    } 

    public class TestPane extends JPanel { 

     private CardsPane topCards; 
     private CardsPane bottomCards; 

     private Timer resetTimer; 

     public TestPane() { 

      resetTimer = new Timer(1000, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        topCards.reset(); 
        bottomCards.reset(); 
       } 
      }); 
      resetTimer.setRepeats(false); 
      resetTimer.setCoalesce(true); 

      PropertyChangeListener propertyChangeHandler = new PropertyChangeListener() { 
       @Override 
       public void propertyChange(PropertyChangeEvent evt) { 
        Card top = topCards.getFlippedCard(); 
        Card bottom = bottomCards.getFlippedCard(); 
        if (top != null && bottom != null) { 
         resetTimer.start(); 
        } 
       } 
      }; 
      BufferedImage[] images = new BufferedImage[4]; 
      try { 
       images[0] = ImageIO.read(new File("./Card01.png")); 
       images[1] = ImageIO.read(new File("./Card02.jpg")); 
       images[2] = ImageIO.read(new File("./Card03.jpg")); 
       images[3] = ImageIO.read(new File("./Card04.png")); 

       Dimension prefSize = getMaxBounds(images); 

       List<BufferedImage> topImages = new ArrayList<>(Arrays.asList(images)); 
       Random rnd = new Random(System.currentTimeMillis()); 
       int rotate = (int) Math.round((rnd.nextFloat() * 200) - 50); 
       Collections.rotate(topImages, rotate); 
       topCards = new CardsPane(topImages, prefSize); 
       topCards.addPropertyChangeListener("flippedCard", propertyChangeHandler); 

       List<BufferedImage> botImages = new ArrayList<>(Arrays.asList(images)); 

       int botRotate = (int) Math.round((rnd.nextFloat() * 200) - 50); 
       Collections.rotate(botImages, botRotate); 
       bottomCards = new CardsPane(botImages, prefSize); 
       bottomCards.addPropertyChangeListener("flippedCard", propertyChangeHandler); 

       setLayout(new GridBagLayout()); 
       GridBagConstraints gbc = new GridBagConstraints(); 
       gbc.insets = new Insets(4, 4, 4, 4); 
       gbc.gridwidth = GridBagConstraints.REMAINDER; 
       add(topCards, gbc); 
       add(bottomCards, gbc); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

     protected Dimension getMaxBounds(BufferedImage[] images) { 
      int width = 0; 
      int height = 0; 

      for (BufferedImage img : images) { 
       width = Math.max(width, img.getWidth()); 
       height = Math.max(height, img.getHeight()); 
      } 

      return new Dimension(width, height); 
     } 
    } 
} 
相關問題