我真的是 Java 的新手,我需要一个圆圈在单击 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();
}
}
最佳答案
看看这是否有帮助,这里我在画圆之前用背景色填充了整个矩形。虽然效率不高,但达到目的
替换paint方法如下
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);
}
关于java - 单击鼠标移动一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12551143/