如何在Jpanel上点击鼠标绘制一个实心椭圆
我想编写一段代码,在面板内单击鼠标时绘制一个填充的椭圆形。我曾经开发过一些代码,但不幸的是,当我尝试进行下一次单击时,整个面板一片空白,新的点出现了。我想保留前面的要点,并通过下一个用户单击面板来添加一些新的要点。如何实现MyPanel
的绘图组件?这是我的代码;它无法正常工作,因为它产生一些小点而不是矩形。
class MyPanel extends JPanel {
Point pointClicked;
public MyPanel() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
pointClicked = e.getPoint();
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(pointClicked.x, pointClicked.y, 1, 1);
}
}
I want to write a code to draw a filled oval where ever the mouse is clicked inside a panel. I used to develop some codes but unfortunately when I tried to do the next click the whole panel blanked and new point appeared. I want to keep the previous points and add some new ones by the next user’s click on the panel. How do I implement the paint component of MyPanel
? Here is my code; it does not work properly, because it produces some small points instead of rectangle.
class MyPanel extends JPanel {
Point pointClicked;
public MyPanel() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
pointClicked = e.getPoint();
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(pointClicked.x, pointClicked.y, 1, 1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要跟踪每个绘制的椭圆形,并在每次调用 PaintComponent() 方法时重新绘制所有椭圆形。
查看自定义绘画方法了解两种不同的方法
You need to keep track of each oval painted and repaint all ovals each time the paintComponent() method is called.
Check out Custom Painting Approaches for two different ways to do this