[英]Move a circle on mouse click
我对Java真的很陌生,当单击JFrame时,我需要一个圆来使其围绕JFrame移动,但是该圆必须获得随机坐标。 到目前为止,此代码每次单击都会生成一个新的圆圈,但所有其他圆圈也都停留在该圆圈中。 我只需要绕一个圈移动框架即可。 所以也许有人可以帮我一下:)
这是我的代码:
public class test2 extends JFrame implements MouseListener {
int height, width;
public test2() {
this.setTitle("Click");
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
addMouseListener(this);
width = getSize().width;
height = getSize().height;
}
public void paint (Graphics g) {
setBackground (Color.red);
g.setColor(Color.yellow);
int a, b;
a = -50 + (int)(Math.random()*(width+40));
b = (int)(Math.random()*(height+20));
g.fillOval(a, b, 130, 110);
}
public void mouseClicked(MouseEvent e) {
int a, b;
a = -50 + (int)(Math.random()*(width+40));
b = (int)(Math.random()*(height+20));
repaint();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public static void main(String arg[]){
new test2();
}
}
看看是否有帮助,这里我在画圆之前用背景色填充了整个矩形。 虽然效率不高但达到了目的
替换油漆方法如下
public void paint (Graphics g) {
setBackground (Color.red);
g.setColor(Color.red);
g.fillRect(0, 0, width, height);
g.setColor(Color.yellow);
int a, b;
a = -50 + (int)(Math.random()*(width+40));
b = (int)(Math.random()*(height+20));
g.fillOval(a, b, 130, 110);
}
我认为您在这里遇到的主要问题之一是您没有使全局a和b变量。 每次调用paint()
和mouseClicked()
方法时,都会创建2个新变量。 还有其他两个问题/警告。
JFrame
则您的`paint()
方法实际上应该称为paintComponents(Graphics g)
super.paint(g);
在paintComponents()定义下。 实际上,令我惊讶的是什么都没画。 另外,Anony-Mousse在谈到惯例时是正确的。 类名应始终以大写开头。
您的代码应如下所示:
public class Test2 extends JFrame implements MouseListener {
int height, width;
int a,b;
public test2() {
this.setTitle("Click");
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
addMouseListener(this);
width = getSize().width;
height = getSize().height;
}
public void paintComponents(Graphics g) {
super.paint(g);
setBackground(Color.red);
g.setColor(Color.yellow);
a = -50 + (int)(Math.random()*(width+40));
b = (int)(Math.random()*(height+20));
g.fillOval(a, b, 130, 110);
}
public void mouseClicked(MouseEvent e) {
int a, b;
a = -50 + (int)(Math.random()*(width+40));
b = (int)(Math.random()*(height+20));
repaint();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public static void main(String arg[]){
new test2();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.