【发布时间】:2021-07-07 04:21:44
【问题描述】:
以下是我的代码的简化版本。菜单面板只有一个开始按钮,而游戏面板只是一个黑屏,带有一个正方形,当按下箭头键时它应该会移动。因此,当我单击菜单面板中的按钮开始游戏时,图形加载正常,但按键监听器根本不起作用。这似乎只有在涉及多个面板或在它们之间切换时才会出现问题。我是一个完整的初学者,所以任何建议都会非常有帮助。
主类
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
MyFrame frame= new MyFrame();
frame.setSize(1000,1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
MyFrame 类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener{
CardLayout card;
JButton b1;
Container c;
MyPanel game;
JPanel menu;
public MyFrame(){
c=getContentPane();
card=new CardLayout();
c.setLayout(card);
game = new MyPanel();
menu = new JPanel();
b1=new JButton("Start");
b1.addActionListener(this);
c.add("p", menu);
menu.add("a",b1);
c.add("d", game);
}
public void actionPerformed(ActionEvent e) {
card.show(c, "d");
}
}
MyPanel 类
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.*;
public class MyPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, KeyListener{
Timer myTimer;
int x = 0;
int y = 0;
int xVel, yVel;
public MyPanel() {
myTimer = new Timer(50, this);
myTimer.start();
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void startTimer() {
myTimer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.CYAN);
g.drawRect(x, y, 100, 100);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myTimer) {
repaint();
x += xVel;
y += yVel;
}
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key== KeyEvent.VK_UP) {
up();
}
if(key== KeyEvent.VK_DOWN) {
down();
}
if(key== KeyEvent.VK_RIGHT) {
right();
}
if(key== KeyEvent.VK_LEFT) {
left();
}
}
public void keyReleased(KeyEvent e) {
xVel = 0;
yVel = 0;
}
public void up() {
xVel = 0;
yVel = -5;
}
public void down() {
xVel = 0;
yVel = 5;
}
public void right() {
xVel = 5;
yVel = 0;
}
public void left() {
xVel = -5;
yVel = 0;
}
}
【问题讨论】:
-
KeyListeners 绑定到一个组件并依赖于该组件具有焦点等,相反,我建议查看 KeyBindings。见这里:stackoverflow.com/questions/23486827/… 和
标签: java swing user-interface keylistener