【发布时间】:2014-12-24 14:45:29
【问题描述】:
我试图将 RedSquare 类的对象添加到 CatchMeV2 类的 JFrame 中。有什么问题?
public class CatchMeV2 implements ActionListener{
int width = 400;
int height = 450;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(400, 400);
frame.setTitle("CatchMe.V2");
RedSquare r = new RedSquare();
frame.add(r);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
public class RedSquare extends JPanel implements ActionListener {
int x = 20; int y = 20;
int velX = 4; int velY = 4;
public RedSquare(){
addActionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(x, y, 50, 50);
repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
x += velX;
y += velY;
if (x < 0) {
velX = 0;
x = 0;
}
if (x > 400 - 50) {
velX = 0;
x = 400 - 50;
}
if (y < 0) {
velY = 0;
y = 0;
}
if (y > 400 - 40) {
velY = 0;
y = 400 - 40;
}
repaint();
}
}
actionPerformed 方法不做任何事情。任何人都可以帮忙吗?或者有没有简单的方法来做到这一点? 背景:我试图通过使用一个类来制作游戏。我做到了,但问题是我一次只能输入 1 个键输入并且它是滞后的。我的老师说,如果我把它分成不同的班级,它就不会落后。是真的吗?
【问题讨论】:
-
阅读 Oracle 教程 Graphics2d 和自定义绘画以获取工作代码示例
-
redsquare 不是从 swing 组件 [jpanel] 扩展而来的组件
-
@FastSnail 我该如何改进它?