简体   繁体   English

如何使用Java中的键盘移动图像?

[英]How to make an image move using the keyboard in java?

I have a maze that I need to get a ball to move through, but I don't know what code I need to use to move the image of the ball around the maze. 我有一个迷宫,需要让球穿过它,但是我不知道我需要使用什么代码在迷宫中移动球的图像。 I have been given a hint that I need to swap images round. 提示我需要四处交换图像。

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class CBallMaze extends JFrame implements ActionListener 
{
//Below is where I have declared all the different objects I have used throughout my program

private JButton buttonRight, buttonLeft, buttonUp, buttonDown, buttonTL, buttonTR, buttonBL, buttonBR, buttonCenter, optionOne, optionTwo, optionThree, optionExit, scenarioAct, scenarioRun, scenarioReset, compassPH;
private JButton [] game = new JButton [208];
private JPanel panelCentre, panelRight, panelBottom, buttonPanel, compassPanel, optionsPanel, selectionPanel, panelAct, panelRun, panelReset, panelSlider;
private JTextField optionTF, squareTF, directionTF;
private JLabel option, square, direction, compassDirection;
private JSlider speedSlider;
private String firstOption = "1", secondOption = "2", thirdOption = "3", upDirection = "North", rightDirection = "East", downDirection = "South", leftDirection = "West";
private int i;
private int[] map = new int[]
        {
        1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
        3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
        3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
        1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
        3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
        1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
        3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
        1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
        3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
        4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        };

final ImageIcon iconCompassNorth = new ImageIcon("north.jpg"); 
final ImageIcon iconCompassWest = new ImageIcon("west.jpg");
final ImageIcon iconCompassSouth = new ImageIcon("south.jpg");
final ImageIcon iconCompassEast = new ImageIcon("east.jpg");
ImageIcon iconReset = new ImageIcon("Reset.jpg");
ImageIcon iconRun = new ImageIcon("Run.jpg");
ImageIcon iconAct = new ImageIcon("Act.jpg");
ImageIcon iconSand, iconWhite, iconBall, iconEnd;

public CBallMaze(String title) {
    super(title);
}
public static void main(String[] args)
{
    CBallMaze cBallMaze = new CBallMaze("CBallMaze Ball Maze Application");
    cBallMaze.setSize(775, 650);
    cBallMaze.createGUI();
    cBallMaze.setVisible(true);
}
private void createGUI()
{   
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new BorderLayout() );

    //Panels

    panelCentre = new JPanel();
    panelCentre.setPreferredSize(new Dimension(625, 450));
    panelCentre.setBackground(Color.BLACK);
    window.add(panelCentre);
    panelCentre.setLayout(new GridLayout(13, 16));

    panelRight = new JPanel();
    panelRight.setPreferredSize(new Dimension(180, 450));
    panelRight.setBackground(Color.WHITE);
    window.add(panelRight, BorderLayout.EAST);

    optionsPanel = new JPanel();
    optionsPanel.setPreferredSize(new Dimension(150, 100));
    optionsPanel.setBackground(Color.WHITE);
    panelRight.add(optionsPanel, BorderLayout.EAST);

    buttonPanel = new JPanel();
    buttonPanel.setPreferredSize(new Dimension(175, 100));
    buttonPanel.setBackground(Color.WHITE);
    panelRight.add(buttonPanel, BorderLayout.EAST);

    selectionPanel = new JPanel();
    selectionPanel.setPreferredSize(new Dimension(175, 150));
    selectionPanel.setBackground(Color.WHITE);
    panelRight.add(selectionPanel, BorderLayout.EAST);

    ImageIcon cw = new ImageIcon("west.jpg");

    compassPanel = new JPanel();
    compassPanel.setPreferredSize(new Dimension(175, 300));
    compassPanel.setBackground(Color.WHITE);
    panelRight.add(compassPanel, BorderLayout.EAST);

    panelBottom = new JPanel();
    panelBottom.setPreferredSize(new Dimension(875, 50));
    panelBottom.setBackground(Color.WHITE);
    window.add(panelBottom, BorderLayout.SOUTH);

    panelAct = new JPanel();
    panelAct.setPreferredSize(new Dimension(125, 40));
    panelAct.setBackground(Color.WHITE);
    panelBottom.add(panelAct, BorderLayout.SOUTH);

    panelRun = new JPanel();
    panelRun.setPreferredSize(new Dimension(125, 40));
    panelRun.setBackground(Color.WHITE);
    panelBottom.add(panelRun, BorderLayout.SOUTH);

    panelReset = new JPanel();
    panelReset.setPreferredSize(new Dimension(125, 40));
    panelReset.setBackground(Color.WHITE);
    panelBottom.add(panelReset, BorderLayout.SOUTH);

    panelSlider = new JPanel();
    panelSlider.setPreferredSize(new Dimension(200, 40));
    panelSlider.setBackground(Color.WHITE);
    panelBottom.add(panelSlider, BorderLayout.SOUTH);

    //Displays

    option = new JLabel("Option: ");
    optionsPanel.add(option, BorderLayout.LINE_START);
    option.setEnabled(true);
    option.setForeground(Color.BLACK);
    option.setHorizontalAlignment(JLabel.LEFT);

    optionTF = new JTextField("1");
    optionsPanel.add(optionTF, BorderLayout.LINE_END);
    optionTF.setEnabled(true);
    optionTF.setPreferredSize(new Dimension(50, 25));
    optionTF.setHorizontalAlignment(JTextField.CENTER);

    square = new JLabel("Square:   ");
    optionsPanel.add(square, BorderLayout.LINE_START);
    square.setEnabled(true);
    square.setForeground(Color.BLACK);
    square.setHorizontalAlignment(JLabel.LEFT);

    squareTF = new JTextField("");
    optionsPanel.add(squareTF, BorderLayout.LINE_END);
    squareTF.setEnabled(true);
    squareTF.setPreferredSize(new Dimension(50, 25));
    squareTF.setHorizontalAlignment(JTextField.CENTER);

    direction = new JLabel("Direction:  ");
    optionsPanel.add(direction, BorderLayout.LINE_START);
    direction.setEnabled(true);
    direction.setForeground(Color.BLACK);
    direction.setHorizontalAlignment(JLabel.LEFT);

    directionTF = new JTextField("Still");
    optionsPanel.add(directionTF, BorderLayout.LINE_END);
    directionTF.setEnabled(true);
    directionTF.setPreferredSize(new Dimension(50, 25));
    directionTF.setHorizontalAlignment(JTextField.CENTER);

    //buttons

    buttonTL = new JButton("");
    buttonPanel.add(buttonTL);
    buttonTL.setPreferredSize(new Dimension(45, 25));
    buttonTL.setEnabled(false);

    buttonUp = new JButton("^");
    buttonPanel.add(buttonUp);
    buttonUp.setPreferredSize(new Dimension(45, 25));
    buttonUp.addActionListener(this);
    buttonUp.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            directionTF.setText(upDirection);
            compassDirection.setIcon(iconCompassNorth);
        }
    });

    buttonTR = new JButton("");
    buttonPanel.add(buttonTR); 
    buttonTR.setPreferredSize(new Dimension(45, 25));
    buttonTR.setEnabled(false);

    buttonLeft = new JButton("<");
    buttonPanel.add(buttonLeft);
    buttonLeft.setPreferredSize(new Dimension(45, 25));
    buttonLeft.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            directionTF.setText(leftDirection);
            compassDirection.setIcon(iconCompassWest);
        }
    });

    buttonCenter = new JButton("");
    buttonPanel.add(buttonCenter);
    buttonCenter.setPreferredSize(new Dimension(45, 25));
    buttonCenter.setEnabled(false);

    buttonRight = new JButton(">");
    buttonPanel.add(buttonRight);
    buttonRight.setPreferredSize(new Dimension(45, 25));
    buttonRight.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            directionTF.setText(rightDirection);
            compassDirection.setIcon(iconCompassEast);
        }
    });

    buttonBL = new JButton("");
    buttonPanel.add(buttonBL);
    buttonBL.setPreferredSize(new Dimension(45, 25));
    buttonBL.setEnabled(false);

    buttonDown = new JButton("v");
    buttonPanel.add(buttonDown);
    buttonDown.setPreferredSize(new Dimension(45, 25));
    buttonDown.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            directionTF.setText(downDirection);
            compassDirection.setIcon(iconCompassSouth);
        }
    });

    buttonBR = new JButton("");
    buttonPanel.add(buttonBR);
    buttonBR.setPreferredSize(new Dimension(45, 25));
    buttonBR.setEnabled(false);

    optionOne = new JButton("Option One");
    selectionPanel.add(optionOne);
    optionOne.setPreferredSize(new Dimension(125, 25));
    optionOne.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            optionTF.setText(firstOption);
        }
    });

    optionTwo = new JButton("Option Two");
    selectionPanel.add(optionTwo);
    optionTwo.setPreferredSize(new Dimension(125, 25));
    optionTwo.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            optionTF.setText(secondOption);
        }
    });

    optionThree = new JButton("Option Three");
    selectionPanel.add(optionThree);
    optionThree.setPreferredSize(new Dimension(125, 25));
    optionThree.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            optionTF.setText(thirdOption);
        }
    });

    optionExit = new JButton("Exit");
    selectionPanel.add(optionExit);
    optionExit.setPreferredSize(new Dimension(125, 25));

    scenarioAct = new JButton("Act");
    scenarioAct.setIcon(iconAct);
    panelAct.add(scenarioAct);
    scenarioAct.addActionListener(this);

    scenarioRun = new JButton("Run");
    scenarioRun.setIcon(iconRun);
    panelRun.add(scenarioRun);
    scenarioRun.addActionListener(this);

    scenarioReset = new JButton("Reset");
    scenarioReset.setIcon(iconReset);
    panelReset.add(scenarioReset);
    scenarioReset.addActionListener(this);

    JSlider speedSlider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
    speedSlider.setMajorTickSpacing(10);
    speedSlider.setMinorTickSpacing(5);
    speedSlider.setPaintTicks(true);
    speedSlider.setBackground(Color.WHITE);
    speedSlider.setLabelTable(speedSlider.createStandardLabels(10));
    panelSlider.add(speedSlider);

    compassDirection = new JLabel();
    compassPanel.add(compassDirection);

    try
    {
        iconSand = new ImageIcon("sand.jpg");
    }
    catch (Exception e)
    {
        System.err.println("Sand Icon "+e);
    }

    try
    {
        iconBall = new ImageIcon("sand60x60.png");
    }
    catch (Exception e)
    {
        System.err.println("Ball Icon "+e);
    }

    try
    {
        iconWhite = new ImageIcon("white32x32.jpg");
    }
    catch (Exception e)
    {
        System.err.println("White Icon "+e);
    }

    try
    {
        iconEnd = new ImageIcon("sandstone.jpg");
    }
    catch (Exception e)
    {
        System.err.println("End Icon"+e);
    }

    for (i=0;i<208;i++)
    {
        game[i] = new JButton ();

        if(map[i]==1)
        {
            game[i].setIcon(iconSand);
        }
        if(map[i]==2)
        {
            game[i].setIcon(iconBall);
        }
        if(map[i]==3)
        {
            game[i].setIcon(iconWhite);
        }
        if(map[i]==4)
        {
            game[i].setIcon(iconEnd);
        }

        game[i].setBorder(null);
        game[i].setPreferredSize(new Dimension(32, 32));
        game[i].addActionListener(this);
        panelCentre.add(game[i]);

    }
}
public void actionPerformed(ActionEvent arg0) 
{

}
}

沙60x60砂白32x32

Try this (works for me): 试试这个(对我有用):

After this line panelCentre.add(game[i]); 在此行之后panelCentre.add(game[i]); enter this: 输入此:

    game[i].addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println(e.getKeyCode());
            switch (e.getKeyCode()) {
                case KeyEvent.VK_RIGHT:
                    System.out.println("right..."); 
                    break;
                case KeyEvent.VK_LEFT:
                    System.out.println("left..."); 
                    break;
                case KeyEvent.VK_DOWN:
                    System.out.println("down..."); 
                    break;
                case KeyEvent.VK_UP:
                    System.out.println("up..."); 
            }
        }
    });

This should print out the direction you typed with the arrow keys. 这应该打印出您使用箭头键键入的方向。

Here is the answer to the question 这是问题的答案

How to move the ball in the maze https://gist.github.com/ad78d37918de6320733b 如何在迷宫中移动球 https://gist.github.com/ad78d37918de6320733b

Note that you should use an own KeyEventDispatcher because otherwise you would have to attach the KeyListener to ALL components in your WHOLE GUI (see this post ) 请注意 ,您应该使用自己的KeyEventDispatcher,因为否则,您将必须将KeyListener附加到WHOLE GUI中的所有组件(请参阅此文章

Anyway, as @chris pointed out, a ball object and another data structure than array would make your assignment easier :) 无论如何,正如@chris指出的那样,一个球对象和另一个数据结构(而不​​是数组)会使您的分配工作更容易:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM