我真的很新的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();
}
}
一句忠告,最好採取由搖擺提供雙緩衝的優勢。因此,不要直接在JFrame上繪畫,而是通過重寫相應的paintComponent(...)方法來繪製JPanel/JComponent。 –
@ Anony-Mousse:該標籤[已過時](http://stackoverflow.com/tags/homework/info)。 – trashgod