2016-04-16 3 views
1

私はこれがタイマーの問題だと思っています。初めて使用していて、間違っているような気がします。スイングタイマーが計画どおりに動作していない

私はJPanelのにそれらを描画testings酒、入力6枚の画像とタイマーの助けとするための方法があります

private void drawDice(Graphics2D g2d) throws IOException, InterruptedException { 
    image = ImageIO.read(getClass().getResourceAsStream("/1.png")); 
    m_dice.add(image); 
    image = ImageIO.read(getClass().getResourceAsStream("/2.png")); 
    m_dice.add(image); 
    image = ImageIO.read(getClass().getResourceAsStream("/3.png")); 
    m_dice.add(image); 
    image = ImageIO.read(getClass().getResourceAsStream("/4.png")); 
    m_dice.add(image); 
    image = ImageIO.read(getClass().getResourceAsStream("/5.png")); 
    m_dice.add(image); 
    image = ImageIO.read(getClass().getResourceAsStream("/6.png")); 
    m_dice.add(image); 

    time.start(); 
    for(int i = 0; i < m_dice.size(); i++){ 
     g2d.drawImage(m_dice.get(i), 700, 400, null, null); 
     repaint(); 
    } 

    time.stop(); 
} 

Timer time = new Timer(1000,this); < at the top of the class 

所望の出力は、すべての6枚のダイスの画像を1秒に示されていることであるが「6.png」だけが表示されます。

ありがとうございました。

+0

あなたの質問に答えるのは難しいです - それはスイングタイマーについてですが、TimerのActionListenerコードを表示していません!また、forループはActionListenerのコードがそれを置き換えるために属しません。 –

+0

@HovercraftFullOfEels私はこれで完全に間違った方向に行くと思う、私はイメージが描画されますが、遅れているが、今これがGraphics2Dであることを認識し、スイングではありません。私の悪い。 –

答えて

1

タイマーの仕組みがはっきりしないと思いますが、提案:

  • まず、タイマーのコードがこれを置き換えるため、forループを取り除いてください。
  • 次に、これがpaintComponentまたは他の描画メソッドから呼び出されている場合、そうしないでください。メソッドを遅くし、GUIのパフォーマンスを遅くするので、良い方法ではないので、ペインティングメソッドからイメージを読み込むことは決してありません。
  • 次に、すべての画像をコンストラクタで一度読み込んで、画像またはアイコンの配列またはArrayListに保存します。自分の投票はImageIconsのArrayList<Icon>です。
  • イメージを交換する最も簡単な方法は、ImageIconをJLabelに表示し、JLabelでsetIcon(...)を呼び出して、最新のアイコンを渡すことです。
  • 次に、TimerのActionListenerで、カウンタの変数を0に初期化します。
  • ActionListenerのactionPerformedメソッドで、カウンタ変数をインクリメントしてイメージをスワップします。
  • カウンタをインデックスとして使用して、ArrayListからImageIconを取得します。
  • JLabelでsetIcon(...)を呼び出します(もう一度、これはすべてタイマーのactionPerformedメソッド内で実行されます)。
  • カウンタがArrayList内のアイコンの数より大きい場合は、カウンタを0にします。あなたのタイマーにstop()を呼び出してください。

ような何か:たとえば

int timerDelay = 1000; 
new Timer(timerDelay, new ActionListener(){ 
    int count = 0; 

    @Override 
    public void actionPerformed(ActionEvent e) { 
    if (count < IMAGE_COUNT) { 
     someLabel.setIcon(icons[count]); 
     count++; 
    } else { 
     // stop the timer 
     ((Timer)e.getSource()).stop(); 
    } 

    } 
}).start(); 

、このプログラムの "ロール" をランダム回のJLabelのMAXCOUNT番号でImageIconsを交換することにより、ダイ:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

import javax.imageio.ImageIO; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class RollDice extends JPanel { 
    // nice public domain dice face images. All 6 images in one "sprite sheet" image. 
    private static final String IMG_PATH = "https://upload.wikimedia.org/" 
      + "wikipedia/commons/4/4c/Dice.png"; 
    private static final int TIMER_DELAY = 200; 
    private List<Icon> diceIcons = new ArrayList<>(); // list to hold dice face image icons 
    private JLabel diceLabel = new JLabel(); // jlabel to display images 
    private Timer diceTimer; // swing timer 

    public RollDice(BufferedImage img) { 
     // subdivide the sprite sheet into individual images 
     // use them to create ImageIcons 
     // and add them to my diceIcons ArrayList<Icon>. 
     double imgW = img.getWidth()/3.0; 
     double imgH = img.getHeight()/2.0; 
     for (int row = 0; row < 2; row++) { 
      int y = (int) (row * imgH); 
      for (int col = 0; col < 3; col++) { 
       int x = (int) (col * imgW); 
       BufferedImage subImg = img.getSubimage(x, y, (int)imgW, (int)imgH); 
       diceIcons.add(new ImageIcon(subImg)); 
      } 
     } 

     // panel to hold roll dice button 
     JPanel btnPanel = new JPanel(); 
     btnPanel.setOpaque(false); 
     btnPanel.add(new JButton(new RollDiceAction("Roll Dice"))); 

     // set the JLabel's icon to the first one in the collection 
     diceLabel.setIcon(diceIcons.get(0)); 

     setLayout(new BorderLayout()); 
     setBackground(Color.WHITE); 
     add(diceLabel); 
     add(btnPanel, BorderLayout.PAGE_END); 

    } 

    public void rollDice() { 
     // if the timer's already running, exit this method 
     if (diceTimer != null && diceTimer.isRunning()) { 
      return; 
     } 

     // else create a new Timer and start it 
     diceTimer = new Timer(TIMER_DELAY, new TimerListener()); 
     diceTimer.start(); 
    } 

    // ActionListener for the Swing Timer 
    private class TimerListener implements ActionListener { 
     private int count = 0; // count how many times dice changes face 
     private final int maxCount = 20; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // once there are max count changes, stop the timer 
      if (count >= maxCount) { 
       ((Timer) e.getSource()).stop(); 
      } 

      // get a random index from 0 to 5 
      int randomIndex = (int) (Math.random() * diceIcons.size()); 
      // show that random number's dice face 
      diceLabel.setIcon(diceIcons.get(randomIndex)); 
      count++; // increment the count 
     } 
    } 

    // ActionListener for our button 
    private class RollDiceAction extends AbstractAction { 
     public RollDiceAction(String name) { 
      super(name); // text to show in the button 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      rollDice(); // simply call the roll dice method 
     } 
    } 

    private static void createAndShowGui(BufferedImage img) { 
     RollDice mainPanel = new RollDice(img); 

     JFrame frame = new JFrame("RollDice"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     try { 
      URL imgUrl = new URL(IMG_PATH); 
      final BufferedImage img = ImageIO.read(imgUrl); 
      SwingUtilities.invokeLater(() -> { 
       createAndShowGui(img); 
      }); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      System.exit(-1); 
     } 
    } 
} 
+0

華麗なありがとう。 @PigeonMilkStories:あなたのメインプログラムとは別の小さなプログラムでデバッグしてください。 –

+0

@PigeonMilkStories:メインプログラムとは別の小さなプログラムでデバッグしてください。解決したら、メインプログラムにコードを移植します。 –

+0

@PigeonMilkStories:runnableプログラムの例を参照してください。 –

関連する問題