Здраствуйте!
У меня следующая проблема: мне необходимо сделать так, чтобы при одновременном нажатии клавиш - происходили независимые события. Например есть 2 шара, которые передвигаються при нажатии соответствующих клавиш клавиатуры. Но когда, например я хочу чтобы оба шара двигались одновременно, нажиамая при этом сразу 2 клавиши. Но срабатывает только одна. т.е. как бы клавиатура как бы блокируеться. Как сделать так, чтобы я мог нормально передвигать шары?
| Код |
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class mainApp extends JApplet { private static final long serialVersionUID = 1L; private static final Dimension appSize = new Dimension(800, 400); private MainPanel mainPanel = new MainPanel(); private Player player1 = new Player(); private Player player2 = new Player();
public void init() { super.init(); this.setSize(appSize); mainPanel.setBorder(BorderFactory.createLineBorder(Color.white, 4)); this.setContentPane(mainPanel); player1.setKey(new char[] {'w', 's', 'a', 'd'}); player2.setKey(new char[] {'i', 'k', 'j', 'l'}); this.addKeyListener(player1); this.addKeyListener(player2); }
private class MainPanel extends JPanel { private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) { g.setColor(Color.GRAY); g.fillRect(0, 0, appSize.width, appSize.height); g.setColor(Color.white); g.drawLine(appSize.width / 2, 0, appSize.width / 2, appSize.height); g.drawOval(appSize.width / 2 - 100, appSize.height / 2 - 100, 200, 200); g.drawRect(0, appSize.height / 2 - 50, 60, 100); g.drawRect(appSize.width - 60, appSize.height / 2 - 50, 60, 100); player1.paint(g); player2.paint(g); } }
private class Player implements KeyListener { private static final long serialVersionUID = 1L; private MovingBall ball = new MovingBall(0, appSize.width, 0, appSize.height); private char[] keys = null; int x = appSize.width / 2 - 30; int y = appSize.height / 2 - 30; Player() { ball.setColor(Color.green); ball.setRadius(30); ball.setLocation(x,y); } public void setKey(char[] key) { keys = key; }
public void paint(Graphics g) { ball.draw(g); }
public void keyPressed(KeyEvent e) { if (e.getKeyChar() == keys[0]) { y -= 5; ball.setLocation(x, y); mainPanel.repaint(); } else if (e.getKeyChar() == keys[1]) { y += 5; ball.setLocation(x, y); mainPanel.repaint(); } else if (e.getKeyChar() == keys[2]) { x -= 5; ball.setLocation(x, y); mainPanel.repaint(); } else if (e.getKeyChar() == keys[3]) { x += 5; ball.setLocation(x, y); mainPanel.repaint(); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { } } }
|
|