簡體   English   中英

在Java中輸入鍵盤后如何更改圖像?

[英]How to change an image after a keyboard input in java?

我有以下代碼向您展示:

public class Test extends JPanel implements ActionListener, KeyListener
{
     Timer tm = new Timer(5, this);
     int x = 0, y = 0, velX = 0, velY = 0; 



public Test()
{
    tm.start(); //starts the timer
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false); 
}




public void paint(Graphics g)
{
    super.paint(g);
    ImageIcon s = new ImageIcon("C:\\Users\\Owner\\Pictures\\Stick.jpg");
    s.paintIcon(this,g,x,y);

}




public void actionPerformed(ActionEvent e)
{
    if (x < 0)
    {
        velX = 0;
        x = 0;
    }

    if (x > 630)
    {
        velX = 0;
        x = 630;
    }

    if(y < 0)
    {
        velY = 0;
        y = 0;
    }

    if(y > 430)
    {
        velY = 0;
        y = 430;
    }
    x = x + velX;
    y = y + velY;
    repaint();
}




public void keyPressed(KeyEvent e)
{
    int c = e.getKeyCode();

    if (c == KeyEvent.VK_LEFT)
    {
        velX = -1;
        velY = 0;

    }
    if(c == KeyEvent.VK_UP)
    {
        velX = 0;
        velY = -1;

    }
    if(c == KeyEvent.VK_RIGHT)
    {
        velX = 1;
        velY = 0;
    }
    if(c == KeyEvent.VK_DOWN)
    {
        velX = 0;
        velY = 1;
    }
}

public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
    velX = 0;
    velY = 0;
}





public static void main(String[] args)
{
    Test t = new Test();
    JFrame jf = new JFrame();
    jf.setTitle("Tutorial");
    jf.setSize(700, 600);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.add(t);
    jf.setVisible(true);
}

我的問題是,只要用戶按住鍵盤上的向右箭頭,它就會更改圖像,而當用戶放開它時,它將返回默認圖像。 請告訴我該怎么做。 我認為這是Graphics類中的一系列if語句,然后將它們調用為鍵輸入,但是我不太確定。 我也在使用Eclipse。 謝謝。

  1. 覆蓋paintComponent而不是paint 有關更多詳細信息,請參見在AWT和Swing中 執行自定義繪畫繪畫。
  2. 使用鍵綁定API代替KeyListener ,這將減少問題。 有關更多詳細信息,請參見如何使用鍵綁定

本質上,您可以只將Image作為類實例字段,該字段由paintComponent方法繪制。 當按下鍵時,您將圖像更改為“移動圖像”,並在釋放該圖像時,將其更改回“默認圖像”

更新了示例

步行小馬

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

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

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

    public interface Mover {

        public enum Direction {

            LEFT, RIGHT, NONE;
        }

        public void setDirection(Direction direction);

        public Direction getDirection();

    }

    public class TestPane extends JPanel implements Mover {

        private BufferedImage left;
        private BufferedImage right;
        private BufferedImage stand;

        private BufferedImage current;
        private Direction direction = Direction.NONE;
        private int xPos;
        private int yPos;

        public TestPane() {
            try {
                left = ImageIO.read(getClass().getResource("/Left.png"));
                right = ImageIO.read(getClass().getResource("/Right.png"));
                stand = ImageIO.read(getClass().getResource("/Stand.png"));
                current = stand;
                xPos = 100 - (current.getWidth() / 2);
                yPos = 100 - (current.getHeight() / 2);
            } catch (IOException exp) {
                exp.printStackTrace();
            }

            bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,   0, false), new MoveAction(this, Direction.LEFT));
            bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,   0, true), new MoveAction(this, Direction.NONE));

            bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), new MoveAction(this, Direction.RIGHT));
            bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), new MoveAction(this, Direction.NONE));

            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    updatePosition();
                    repaint();
                }
            });
            timer.start();
        }

        protected void bindKeyStrokeTo(int condition, String name, KeyStroke keyStroke, Action action) {
            InputMap im = getInputMap(condition);
            ActionMap am = getActionMap();

            im.put(keyStroke, name);
            am.put(name, action);
        }

        @Override
        public Direction getDirection() {
            return direction;
        }

        @Override
        public void setDirection(Direction direction) {
            this.direction = direction;
        }

        protected void updatePosition() {

            switch (getDirection()) {
                case LEFT:
                    current = left;
                    xPos -= 1;
                    break;
                case RIGHT:
                    current = right;
                    xPos += 1;
                    break;
                case NONE:
                    current = stand;
                    break;
            }

            if (xPos < 0) {
                xPos = 0;
                current = stand;
            } else if (xPos + current.getWidth() > getWidth()) {
                current = stand;
                xPos = getWidth() - current.getWidth();
            }

        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(current, xPos, yPos, this);
            g2d.dispose();
        }

    }

    public class MoveAction extends AbstractAction {

        private Mover mover;
        private Mover.Direction direction;

        public MoveAction(Mover mover, Mover.Direction direction) {
            this.mover = mover;
            this.direction = direction;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            mover.setDirection(direction);
        }

    }

}

暫無
暫無

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

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