Java - 如何知道按下了什么键?

时间:2014-01-10 23:12:00

标签: java swing awt keylistener

我正在开发这个应用程序,它是一个弹跳的球。但我想添加应用程序的purpoise。所以我希望用户能够移动垫子,防止球碰到墙壁。所以我有这个代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MainframeTwo extends JPanel implements Runnable{

Color color = Color.red;
int dia = 60;
int diaPad = 120;
long delay = 20;
private int x = 120;
private int y = 340;
private int xx = 120;
private int yy = 670;
private int dx = 6;
private int dy = 7;
private int dxx = 6;
boolean leftKey = false;
boolean rightKey = false;

protected void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(color); 
    g.fillOval(x,y,60,60);

    g.setColor(Color.BLACK);
    g.fillRect(xx,yy,120,15);

}

public void run() {
    while(isVisible()) {
        try {
            Thread.sleep(delay);
        } catch(InterruptedException e) {
            System.out.println("interrupted");
        }
        moveBall();
        repaint();
    }
}

public void moveBall() {
    if(x + dx < 0 || x + dia + dx > getWidth()) {
        dx *= -1;
        color = getColorOne();
    }
    if(y + dy < 0 || y + dia + dy > getHeight()) {
        dy *= -1;
        color = getColorOne();
    }
    x += dx;
    y += dy;
}

public void movePadRight() {
        if(xx + dxx < 0 || xx + diaPad + dxx > getWidth()) {
             dxx *= -1;
        }
        xx += dxx;
}
public void movePadLeft() {
        if(xx + dxx < 0 || xx + diaPad + dxx > getWidth()) {
             dxx *= -1;
        }
        xx += dxx;
}

private Color getColorOne() {
    int rval = (int)Math.floor(Math.random() * 256);
    int gval = (int)Math.floor(Math.random() * 256);
    int bval = (int)Math.floor(Math.random() * 256);
    return new Color(rval, gval, bval);
}


private void start() {
    while(!isVisible()) {
        try {
            Thread.sleep(25);
        } catch(InterruptedException e) {
            System.exit(1);
        }
    }
    Thread thread = new Thread(this);
    thread.setPriority(Thread.NORM_PRIORITY);
    thread.start();
}


public static void main(String[] args) {

    Runnable r = new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            MainframeTwo test = new MainframeTwo();

            frame.getContentPane().add(panel);

            panel.addKeyListener(new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {}

                @Override
                public void keyReleased(KeyEvent e) {
              System.out.println("Released" + e.getKeyChar());
          }

                @Override
                public void keyPressed(KeyEvent e) {
                    System.out.println("Pressed " + e.getKeyChar());

                }
            });

            panel.setFocusable(true);
            panel.requestFocusInWindow();

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(test);
            frame.setSize(640, 960);
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
            frame.setVisible(true);
            test.start();

        }

    };

    SwingUtilities.invokeLater(r);

}
}

可怕的格式化,我知道。 但无论如何,我希望能够有一个if()函数,如果按下键A和S,它将触发。我不知道有可能。如果不可能,请按下按键A和S时告诉我触发movePadLeft和Right的方法。

2 个答案:

答案 0 :(得分:1)

使用布尔值来跟踪是否按下了您关心的每个键。在keyPressed()和keyReleased()方法中设置这些布尔值。检查movePad()函数中的布尔值,并执行正确的操作。

答案 1 :(得分:0)