Java 使用来自不同类的keyEvent

Java 使用来自不同类的keyEvent,java,Java,如果我的小鸡到了角落,我试图限制它的移动。这是我的移动方法代码 public void move1(){ if(((x<=350) && (y>=350)) || ((x>=450) && (y>=350))){ if(dy<0){ dy=0; } } if(((x>=350) && (y<=350)) || ((x<

如果我的小鸡到了角落,我试图限制它的移动。这是我的移动方法代码

public void move1(){


    if(((x<=350) && (y>=350)) || ((x>=450) && (y>=350))){
        if(dy<0){
            dy=0;
        }
    }
    if(((x>=350) && (y<=350)) || ((x<=450) && (y<=350))){
        if(dx<0 || dx>0){
            dx=0;
        }
    }

    if(((y<=250) && (x<=350)) || ((y<=250) && (x>=450))){
        if(dy>0){
        dy=0;
        }
    }
    if (x >= 750){ 
    x = 750; 
    } 
    if (y >= 575){
    y = 575; 
    }
    x += dx;y += dy; 

}

动画非常好,但我的小鸡不会回应keyevent,我强烈建议你看一看,它们更习惯于这种情况,它们更关注焦点相关的问题。这篇关于“可能”的帖子肯定会让你感兴趣,主题是“关注:——)

编辑: 下面是帮助中的一个小程序:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyBindingExample
{
    private DrawingBoard contentPane;
    /*
     * There variables will simply
     * decide how much the square
     * will move with click key press,
     * in this case I have set this to
     * 1 (inside the constructor).
     * brakes will simply tell whether
     * the square will move or not in
     * a given direction.
     */
    private int speed;
    private int brakes;

    public KeyBindingExample() {
        speed = 5;
        brakes = 0;
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Swing Worker Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new DrawingBoard(10, 10, Color.BLUE.darker());

        addBindingsToBoard();

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void addBindingsToBoard() {
        /*
         * Since, when UP Arrow is pressed, that means, the square
         * can move vertically upwards, hence, the square will move
         * along Y-Axis that too in the negative direction of the 
         * same, though along X-Axis the square will move nowhere,
         * hence, we passing 0 and -1, since we want to add the 
         * current location (say square is at present at 50, 50),
         * now after UP Arrow key event, square will be at (50, 49);
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("UP"),
                                "UP Arrow Key", brakes, -speed);
        /*
         * When RIGHT Arrow is pressed, the square is suppose to
         * move horizontally, along the X-Axis, in the positive
         * direction towards the RIGHT. Hence +1 change along X-Axis
         * and no change along Y-Axis, i.e. from (50, 49), the square
         * will now move to (51, 49), that's why we passing (+1, 0)
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("RIGHT"),
                                "RIGHT Arrow Key", speed, brakes);
        /*
         * When DOWN Arrow is pressed, the square is suppose to
         * move vertically, along the Y-Axis, in the positive
         * direction towards the BOTTOM. Hence no change along X-Axis
         * and +1 change along Y-Axis, i.e. from (51, 49), the square
         * will now move to (51, 50), that's why we passing (0, +1)
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("DOWN"),
                                "DOWN Arrow Key", brakes, +speed);
        /*
         * When LEFT Arrow is pressed, the square is suppose to
         * move horizontally, along the X-Axis, in the negative
         * direction towards the LEFT side. Hence -1 change along X-Axis
         * and no change along Y-Axis, i.e. from (51, 50), the square
         * will now move to (50, 50), that's why we passing (-1, 0).
         * The square will atlast come to it's initial position.
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("LEFT"),
                                "LEFT Arrow Key", -speed, brakes);
    }

    private void putBindingsFor(JComponent comp,
        KeyStroke keyStroke, String value, final int moveX, final int moveY) {
        comp.getInputMap().put(keyStroke, value);
        comp.getActionMap().put(value, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                contentPane.setValues(moveX, moveY);
            }
        });
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new KeyBindingExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class DrawingBoard extends JPanel {

    private int x;
    private int y;
    private int width;
    private int height;
    private Color rectColor;

    public DrawingBoard(int x, int y, Color rColor) {
        setOpaque(true);
        this.x = x;
        this.y = y;
        rectColor = rColor;
        width = height = 10;
    }

    public void setValues(int deltaX, int deltaY) {

        System.out.format("Firstly X : %d\tY : %d%n", x, y);
        repaint(x, y, width, height);
        /*
         * Whatever values are passed from above, i.e.
         * say on Left ARROW, we passing (-1, 0),
         * therefore deltaX will be -1 and deltaY will
         * be 0. Now whatever the current value of X is
         * we are simply adding deltaX to that value
         * and the same goes for deltaY as well.
         * Now since the value for x and y is updated
         * after these two statements below, we checking
         * that whether these two updated values lies
         * within the bounds of our board or not.
         * If they are, then we simply calling repaint,
         * to draw the square at this new location, else
         * we simply bring back the previous values of 
         * x and y to their previous state.
         */
        x += deltaX;
        y += deltaY;

        if ((x + width) <= getWidth() && (y + height) <= getHeight()
                        && x >= 0 && y >= 0) {
            System.out.format("Later X : %d\tY : %d%n", x, y);
            repaint(x, y, width, height);
        }
        else {
            x -= deltaX;
            y -= deltaY;
            System.out.format("Later X : %d\tY : %d%n", x, y);
            repaint(x, y, width, height);
        }
    }

    /*
     * Make this a customary habbit of overridding
     * this method whenever you have to override
     * any JComponent, instead of calling
     * setPreferredSize(...).
     */
    @Override
    public Dimension getPreferredSize() {
        return (new Dimension(100, 100));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(rectColor);
        g.fillRect(x, y, width, height);
    }
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
公共类KeyBindingExample
{
私人绘图板内容窗格;
/*
*这些变量将简单地
*决定这个正方形有多少
*将随着单击键的按下而移动,
*在这种情况下,我已将其设置为
*1(在构造函数内部)。
*刹车只会告诉你
*广场是否会移动
*给定的方向。
*/
私人整数速度;
私家车;
公钥绑定示例(){
速度=5;
制动器=0;
}
私有void displayGUI()
{
JFrame=新JFrame(“Swing Worker示例”);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane=新的绘图板(10,10,Color.BLUE.darker());
addBindingsToBoard();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(真);
frame.setVisible(true);
}
私有void addBindingsToBoard(){
/*
*因为,当按下向上箭头时,表示正方形
*可以垂直向上移动,因此,正方形将移动
*沿着Y轴,也就是在
*同样,尽管沿着X轴,正方形不会移动,
*因此,我们传递0和-1,因为我们要添加
*当前位置(假设广场目前为50,50),
*现在在向上箭头键事件之后,正方形将位于(50,49);
*/
putBindingsFor(contentPane,KeyStroke.getKeyStroke(“UP”),
“向上箭头键”,刹车,-速度);
/*
*按下向右箭头时,假定正方形为
*沿X轴以正方向水平移动
*向右的方向。因此+1沿X轴变化
*并且沿Y轴没有变化,即从(50,49)开始,正方形
*现在转到(51,49),这就是我们通过(+1,0)的原因
*/
putBindingsFor(contentPane,KeyStroke.getKeyStroke(“右”),
“右箭头键”、速度、制动器);
/*
*按下向下箭头时,假定正方形为
*沿Y轴以正方向垂直移动
*朝向底部的方向。因此沿X轴没有变化
*和+1沿Y轴变化,即从(51,49)开始,平方
*现在将移动到(51,50),这就是我们通过(0,1)的原因
*/
putBindingsFor(contentPane,KeyStroke.getKeyStroke(“向下”),
“向下箭头键”、制动器、+速度);
/*
*按下左箭头时,假定正方形为
*沿X轴以负方向水平移动
*朝向左侧的方向。因此-1沿X轴变化
*并且沿Y轴没有变化,即从(51,50)开始,正方形
*现在将移动到(50,50),这就是我们通过(-1,0)的原因。
*广场至少会回到它的初始位置。
*/
putBindingsFor(contentPane,KeyStroke.getKeyStroke(“左”),
“左箭头键”—速度、制动器);
}
用于(JComponent comp,
击键击键、字符串值、最终int-moveX、最终int-moveY){
comp.getInputMap().put(击键,值);
comp.getActionMap().put(值,新的AbstractAction()){
@凌驾
已执行的公共无效行动(行动事件ae){
contentPane.setValues(moveX,moveY);
}
});
}
公共静态void main(字符串[]args)
{
Runnable Runnable=新的Runnable()
{
@凌驾
公开募捐
{
新的KeyBindingExample().displayGUI();
}
};
invokeLater(可运行);
}
}
类DrawingBoard扩展JPanel{
私人INTX;
私营企业;
私有整数宽度;
私人内部高度;
私人色彩;
公共绘图板(内x、内y、彩色){
set不透明(true);
这个.x=x;
这个。y=y;
rectColor=rColor;
宽度=高度=10;
}
公共无效设置值(int deltaX、int deltaY){
System.out.format(“第一个X:%d\tY:%d%n”,X,y);
重新喷漆(x、y、宽度、高度);
/*
*从上面传递的任何值,即。
*如左箭头所示,我们经过(-1,0),
*因此,deltaX将为-1,deltaY将为-1
*现在不管X的当前值是多少
*我们只是在这个价值上加上代尔税
*德尔泰也是如此。
*现在,由于x和y的值已更新
*在下面这两个陈述之后,我们将进行检查
*这两个更新的值是否存在
*是否在我们董事会的范围内。
*如果是的话,我们就称之为重绘,
*要在此新位置绘制正方形,请执行以下操作:
*我们只是简单地恢复了
*x和y恢复到其以前的状态。
*/
x+=代尔税;
y+=三角洲;
如果((x+宽度)=0){
System.out.format(“以后的X:%d\tY:%d%n”,X,y);
重新喷漆(x、y、宽度、高度);
}
否则{
x-=deltaX;
y-=三角洲;
System.out.format(“以后的X:%d\tY:%d%n”,X,y);
重新喷漆(x
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyBindingExample
{
    private DrawingBoard contentPane;
    /*
     * There variables will simply
     * decide how much the square
     * will move with click key press,
     * in this case I have set this to
     * 1 (inside the constructor).
     * brakes will simply tell whether
     * the square will move or not in
     * a given direction.
     */
    private int speed;
    private int brakes;

    public KeyBindingExample() {
        speed = 5;
        brakes = 0;
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Swing Worker Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new DrawingBoard(10, 10, Color.BLUE.darker());

        addBindingsToBoard();

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void addBindingsToBoard() {
        /*
         * Since, when UP Arrow is pressed, that means, the square
         * can move vertically upwards, hence, the square will move
         * along Y-Axis that too in the negative direction of the 
         * same, though along X-Axis the square will move nowhere,
         * hence, we passing 0 and -1, since we want to add the 
         * current location (say square is at present at 50, 50),
         * now after UP Arrow key event, square will be at (50, 49);
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("UP"),
                                "UP Arrow Key", brakes, -speed);
        /*
         * When RIGHT Arrow is pressed, the square is suppose to
         * move horizontally, along the X-Axis, in the positive
         * direction towards the RIGHT. Hence +1 change along X-Axis
         * and no change along Y-Axis, i.e. from (50, 49), the square
         * will now move to (51, 49), that's why we passing (+1, 0)
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("RIGHT"),
                                "RIGHT Arrow Key", speed, brakes);
        /*
         * When DOWN Arrow is pressed, the square is suppose to
         * move vertically, along the Y-Axis, in the positive
         * direction towards the BOTTOM. Hence no change along X-Axis
         * and +1 change along Y-Axis, i.e. from (51, 49), the square
         * will now move to (51, 50), that's why we passing (0, +1)
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("DOWN"),
                                "DOWN Arrow Key", brakes, +speed);
        /*
         * When LEFT Arrow is pressed, the square is suppose to
         * move horizontally, along the X-Axis, in the negative
         * direction towards the LEFT side. Hence -1 change along X-Axis
         * and no change along Y-Axis, i.e. from (51, 50), the square
         * will now move to (50, 50), that's why we passing (-1, 0).
         * The square will atlast come to it's initial position.
         */
        putBindingsFor(contentPane, KeyStroke.getKeyStroke("LEFT"),
                                "LEFT Arrow Key", -speed, brakes);
    }

    private void putBindingsFor(JComponent comp,
        KeyStroke keyStroke, String value, final int moveX, final int moveY) {
        comp.getInputMap().put(keyStroke, value);
        comp.getActionMap().put(value, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                contentPane.setValues(moveX, moveY);
            }
        });
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new KeyBindingExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class DrawingBoard extends JPanel {

    private int x;
    private int y;
    private int width;
    private int height;
    private Color rectColor;

    public DrawingBoard(int x, int y, Color rColor) {
        setOpaque(true);
        this.x = x;
        this.y = y;
        rectColor = rColor;
        width = height = 10;
    }

    public void setValues(int deltaX, int deltaY) {

        System.out.format("Firstly X : %d\tY : %d%n", x, y);
        repaint(x, y, width, height);
        /*
         * Whatever values are passed from above, i.e.
         * say on Left ARROW, we passing (-1, 0),
         * therefore deltaX will be -1 and deltaY will
         * be 0. Now whatever the current value of X is
         * we are simply adding deltaX to that value
         * and the same goes for deltaY as well.
         * Now since the value for x and y is updated
         * after these two statements below, we checking
         * that whether these two updated values lies
         * within the bounds of our board or not.
         * If they are, then we simply calling repaint,
         * to draw the square at this new location, else
         * we simply bring back the previous values of 
         * x and y to their previous state.
         */
        x += deltaX;
        y += deltaY;

        if ((x + width) <= getWidth() && (y + height) <= getHeight()
                        && x >= 0 && y >= 0) {
            System.out.format("Later X : %d\tY : %d%n", x, y);
            repaint(x, y, width, height);
        }
        else {
            x -= deltaX;
            y -= deltaY;
            System.out.format("Later X : %d\tY : %d%n", x, y);
            repaint(x, y, width, height);
        }
    }

    /*
     * Make this a customary habbit of overridding
     * this method whenever you have to override
     * any JComponent, instead of calling
     * setPreferredSize(...).
     */
    @Override
    public Dimension getPreferredSize() {
        return (new Dimension(100, 100));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(rectColor);
        g.fillRect(x, y, width, height);
    }
}