Java 回转计时器未按计划工作
我认为这是一个计时器的问题,我第一次使用它们,我觉得我做错了 为了测试起见,我有一种方法,输入6个图像,并在计时器的帮助下将它们绘制到JPanel:Java 回转计时器未按计划工作,java,swing,timer,Java,Swing,Timer,我认为这是一个计时器的问题,我第一次使用它们,我觉得我做错了 为了测试起见,我有一种方法,输入6个图像,并在计时器的帮助下将它们绘制到JPanel: private void drawDice(Graphics2D g2d) throws IOException, InterruptedException { image = ImageIO.read(getClass().getResourceAsStream("/1.png")); m_dice.add(image);
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
private void drawDice(Graphics2D g2d)抛出IOException、InterruptedException{
image=ImageIO.read(getClass().getResourceAsStream(“/1.png”);
m_dice.add(图像);
image=ImageIO.read(getClass().getResourceAsStream(“/2.png”);
m_dice.add(图像);
image=ImageIO.read(getClass().getResourceAsStream(“/3.png”);
m_dice.add(图像);
image=ImageIO.read(getClass().getResourceAsStream(“/4.png”);
m_dice.add(图像);
image=ImageIO.read(getClass().getResourceAsStream(“/5.png”);
m_dice.add(图像);
image=ImageIO.read(getClass().getResourceAsStream(“/6.png”);
m_dice.add(图像);
time.start();
对于(int i=0;i
所需的输出是,所有6个骰子图像以1秒的间隔显示,但仅显示“6.png”
谢谢。我想你可能不清楚计时器是如何工作的。建议:
- 首先也是最重要的——去掉for循环,因为计时器的代码将替换它
- 接下来,如果这是从paintComponent或其他绘制方法调用的,则不要。您永远不希望从绘画方法中读取图像,因为这样会减慢该方法的速度,从而降低GUI的感知性能,这不是一件好事
- 接下来,在构造函数中一次性读取所有图像,并将它们保存到图像或图标的数组或ArrayList中。我自己的投票是图像图标的
ArrayList
- 交换图像的最简单方法是在JLabel中显示图像图标,只需在JLabel上调用
,并传入最新的图标setIcon(…)
- 接下来,在计时器的ActionListener中,有一个初始化为0的计数器int变量李>
- 在ActionListener的actionPerformed方法中,增加计数器变量,并交换图像李>
- 使用计数器作为索引从ArrayList获取ImageIcon
- 在JLabel上调用
(同样,这都是在计时器的actionPerformed方法中完成的)setIcon(…)
- 如果计数器大于等于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();
int timerDelay=1000;
新计时器(timerDelay,新ActionListener(){
整数计数=0;
@凌驾
已执行的公共无效操作(操作事件e){
如果(计数<图像计数){
setIcon(icons[count]);
计数++;
}否则{
//停止计时
((计时器)e.getSource()).stop();
}
}
}).start();
例如,此程序通过在JLabel maxCount中随机交换ImageIcon来“滚动”模具次数:
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);
}
}
}
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.image.buffereImage;
导入java.io.IOException;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.List;
导入javax.imageio.imageio;
导入javax.swing.*;
@抑制警告(“串行”)
公共类RollDice扩展了JPanel{
//不错的公共域骰子脸图片。所有6张图片都在一张“精灵表”图片中。
私有静态最终字符串IMG_PATH=”https://upload.wikimedia.org/"
+“wikipedia/commons/4/4c/Dice.png”;
专用静态最终int定时器_延迟=200;
private List diceIcons=new ArrayList();//用于保存骰子面图像图标的列表
private JLabel dicellabel=new JLabel();//用于显示图像的JLabel
专用计时器diceTimer;//摆动计时器
公共滚动骰子(BuffereImage img){
//将精灵工作表细分为单个图像
//使用它们来创建图像图标
//并将它们添加到我的骰子列表中。
double imgW=img.getWidth()/3.0;
double imgH=img.getHeight()/2.0;
对于(int行=0;行<2;行++){
int y=(int)(行*imgH);
for(int col=0;col<3;col++){
int x=(int)(col*imgW);
buffereImage subImg=img.getSubimage(x,y,(int)imgW,(int)imgH);
添加(新图像图标(subImg));
}
}
//用于固定掷骰子按钮的面板
JPanel btnPanel=新的JPanel();
btnPanel.set不透明(假);
添加(新JButton(新掷骰子动作(“掷骰子”));
//将JLabel图标设置为集合中的第一个图标
diceLabel.setIcon(diceIcons.get(0));
setLayout(新的BorderLayout());
挫折地面(颜色:白色);
添加(标签);
添加(btnPanel,BorderLayout.PAGE_END);
}
公共无效滚动骰子(){
//如果计时器已在运行,请退出此方法
if(diceTimer!=null&&diceTimer.isRunning()){
返回;
}
//否则,创建一个新计时器并启动它
diceTimer=新定时器(定时器延迟,新定时器延迟();
diceTimer.start();
}
//Swing计时器的ActionListener
私有类TimerListener实现ActionListener{
private int count=0;//计算骰子改变脸的次数
私有最终整数最大计数=20;
@凌驾
已执行的公共无效操作(操作事件e){
//一旦最大计数发生变化,停止计时器
如果(计数>=最大计数){
((计时器)e.getSource()).stop();
}
//获取从0到5的随机索引
int randomIndex=(int)(Math.random()*diceIcons.size());
//显示随机数的骰子面
diceLabel.setIcon(diceIcons.get(randomIndex));
计数+++;//增量