簡體   English   中英

按下鍵時使用計時器

[英]Use a timer when a key is pressed

過去一周的搜索沒有提供任何有用的幫助,試圖找出如何做到這一點。 當用戶按下退格鍵時,它會保存游戲。 我設置它在頂部顯示一個小盒子,上面寫着“拯救......”,我想讓它在那里停留大約2秒鍾。 使用此代碼按下按鈕時,我可以顯示它:

if (key.save) {
    font = new Font(null, 0, 16);
    g.setFont(font);
    g.setColor(Color.DARK_GRAY);
    g.fillRect(getWidth() / 2 - 40, -1, 80, 35);
    g.setColor(Color.BLACK);
    g.drawRect(getWidth() / 2 - 40, -1, 80, 35);
    g.setColor(Color.white);
    g.drawString("Saving..", getWidth() / 2 - 30, 22);
}

但是這段代碼不起作用,甚至不會在頂部顯示框:

if (key.save) {
    ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Font font = new Font(null, 0, 16);
            g.setFont(font);
            g.setColor(Color.DARK_GRAY);
            g.fillRect(getWidth() / 2 - 40, -1, 80, 35);
            g.setColor(Color.BLACK);
            g.drawRect(getWidth() / 2 - 40, -1, 80, 35);
            g.setColor(Color.white);
            g.drawString("Saving..", getWidth() / 2 - 30, 22);
        }
    };

    timer = new Timer(0, action);
    timer.start();
}

在此輸入圖像描述

這是使用可以隨時間更新的可渲染工件列表的基本概念的示例。

基本思想是有一個中央繪制循環,負責根據您想要渲染的內容更新UI的當前狀態。 這意味着對UI的任何更改都必須通過此中央循環。

這個例子只使用Swing,但這個概念應該很容易翻譯。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class QuickPaint01 {

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

    public QuickPaint01() {
        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 TestPane extends JPanel implements Environment {

        private List<Drawable> drawables;

        public TestPane() {
            drawables = new ArrayList<>(25);
            Timer update = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Drawable[] draws = drawables.toArray(new Drawable[drawables.size()]);
                    for (Drawable drawable : draws) {
                        if (drawable instanceof Moveable) {
                            ((Moveable)drawable).update(TestPane.this);
                        }
                    }
                    repaint();
                }
            });
            update.setCoalesce(true);
            update.setRepeats(true);
            update.start();
            drawables.add(new Ball());
        }

        @Override
        public void add(Drawable drawable) {
            drawables.add(drawable);
        }

        @Override
        public void remove(Drawable drawable) {
            drawables.remove(drawable);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Drawable drawable : drawables) {
                drawable.draw(this, g2d);
            }
            g2d.dispose();
        }
    }

    public interface Environment {

        public Dimension getSize();
        public void add(Drawable drawable);
        public void remove(Drawable drawable);

    }

    public interface Drawable {

        public void draw(Environment env, Graphics2D g);

    }

    public interface Moveable extends Drawable {

        public void update(Environment env);

    }

    public class Ball implements Moveable {

        private int radius = 20;

        private int x = 0;
        private int y = 0;

        private int xDelta = 4;

        private Shape shape;

        public Ball() {
            shape = new Ellipse2D.Float(0, 0, radius, radius);
        }

        @Override
        public void update(Environment env) {
            x += xDelta;
            if (x + radius > env.getSize().width) {

                x = env.getSize().width - radius;
                xDelta *= -1;

                env.add(new Message(env, "<< Bounce", 1));

            } else if (x < 0) {

                x = 0;
                xDelta *= -1;

                env.add(new Message(env, "Bounce >> ", 1));

            }
            y = (env.getSize().height - radius) / 2;
        }

        @Override
        public void draw(Environment env, Graphics2D g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(x, y);
            g2d.setColor(Color.BLUE);
            g2d.fill(shape);
            g2d.dispose();
        }

    }

    public class Message implements Drawable {

        private Environment environment;
        private String message;
        private int delay;

        public Message(Environment environment, String message, int delay) {
            this.environment = environment;
            this.message = message;
            this.delay = delay;

            Timer timer = new Timer(delay * 1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Message.this.environment.remove(Message.this);
                }
            });
            timer.start();
        }

        @Override
        public void draw(Environment env, Graphics2D g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            FontMetrics fm = g2d.getFontMetrics();
            g2d.drawString(message, env.getSize().width - fm.stringWidth(message), 0 + fm.getAscent());
            g2d.dispose();
        }

    }

}

用偽代碼編寫,您可以使用幾個部分構建解決方案:

  • 引入一個設置為false的字段saveMessageIsVisible
  • 內部的密鑰處理方法
    • 克隆游戲狀態
    • 啟動一個新線程並保存狀態
    • 在此線程的末尾,將saveMessageIsVisible設置為true(並可選擇執行invalidate屏幕)
    • 還會啟動一個持續時間為2秒的計時器,然后再將該字段設置為false。
  • 在繪圖例程內檢查字段並繪制保存框。

要在給定的時間段內執行任務,您可以執行以下操作:

ExecutorService service = Executors.newSingleThreadExecutor();
try {
    Runnable r = new Runnable() {
       @Override
       public void run() {
         // task
       }
    };

    Future<?> f = service.submit(r);

    f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
} catch (Exception e) {
     //Handele Exception
} finally {
     service.shutdown();
}

暫無
暫無

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

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