簡體   English   中英

擺動計時器未按計划工作

[英]Swing Timer not working as planned

我認為這是一個計時器問題,我第一次使用它們,我覺得我做錯了。

我有一個方法,為了測試起見,輸入 6 個圖像,並在計時器的幫助下將它們繪制到 JPanel:

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 個骰子圖像,但僅顯示“6.png”。

謝謝你。

我認為您可能不清楚 Timer 的工作原理。 建議:

  • 首先也是最重要的 - 擺脫 for 循環,因為計時器的代碼將替換它。
  • 接下來,如果它是從paintComponent 或其他繪畫方法調用的,請不要。 您永遠不想從繪畫方法中讀取圖像,因為這會減慢方法的速度,從而降低 GUI 的感知性能,這不是一件好事。
  • 接下來,在構造函數中一次性讀取所有圖像並將它們保存到圖像或圖標的數組或 ArrayList 中。 我自己的投票是 ImageIcons 的ArrayList<Icon>
  • 交換圖像的最簡單方法是在 JLabel 中顯示 ImageIcons 並簡單地調用 JLabel 上的setIcon(...) ,傳入最新的圖標。
  • 接下來在您的 Timer 的 ActionListener 中,有一個初始化為 0 的計數器 int 變量。
  • 在 ActionListener 的 actionPerformed 方法中,遞增計數器變量並交換圖像。
  • 使用計數器作為索引從 ArrayList 獲取 ImageIcon。
  • 在 JLabel 上調用setIcon(...) (同樣,這一切都在 Timer 的 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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM