import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Panel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
final static int WIDTH = 800;
final static int HEIGHT = 600;
private int x = 40, y = 49, r = 20;
Dimension SIZE = new Dimension(WIDTH, HEIGHT);
public Panel() {
setLayout(new BorderLayout());
setPreferredSize(SIZE);
setMaximumSize(SIZE);
setMinimumSize(SIZE);
setBackground(Color.cyan);
setFocusable(true);
requestFocus();
new input(this);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.fillOval(x, y, r, r);
repaint();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class input extends KeyAdapter {
private Panel panel;
public input(Panel panel) {
panel = new Panel();
panel.addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
int x = panel.getX();
int y = panel.getY();
if (keycode == KeyEvent.VK_LEFT) {
panel.setX(x - 1);
}
if (keycode == KeyEvent.VK_RIGHT) {
panel.setX(x + 1);
}
}
}
我是一个Java新手。我试图专门为 KeyListener 制作一个类,但它不起作用。我不知道我做错了什么。
制作一个 inputhandler 类可能毫无意义,它只控制唯一的一个类(jpanel),但我曾经将所有代码放在一个类中。它看起来很糟糕。我正在学习将它们变成更多独立的类或使它们更加面向对象〜我只是混淆了何时创建一个新类,何时不创建一个新类。请帮助我,你能告诉我我上面的代码做错了什么吗?我的想法是错误的还是只是代码?