【发布时间】:2015-07-12 08:59:56
【问题描述】:
我正在创建一个简单的程序,在该程序中我用鼠标单击的地方画了一个黑色椭圆。但是,我希望出现一个新的椭圆形而旧的椭圆形消失。我该怎么做呢?我已经搞砸了插入到我的 mousePressed 方法中的 removeAll() 方法,但是它对我不起作用。 removeAll() 方法甚至适合这个吗?还是我应该使用其他东西?抱歉,如果答案很明显,但我对此仍然很陌生并正在努力学习。任何建议将不胜感激。谢谢。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintPractice extends JPanel implements MouseListener {
Random rand = new Random();
int x = rand.nextInt(450);
int y = rand.nextInt(450);
public PaintPractice(){
super();
addMouseListener(this);
}
public static void main(String[] args){
JFrame frame = new JFrame();
PaintPractice panel = new PaintPractice();
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
removeAll();
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
【问题讨论】:
-
记得阅读文档中对你不知道的方法的描述。这就是你错误使用 removeAll() 方法的原因。