Java-如何从JPanel清除图形
作者:互联网
我正在创建一个简单的程序,我用鼠标点击黑色椭圆.但是,我想要一个新的椭圆形出现,旧的椭圆形消失.我该怎么做呢?我已经搞乱了插入到我的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) {
}
}
解决方法:
立即解决它只是在paint(Graphics g)方法中调用super.paint(g).
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
Paint机制以及为什么我应该覆盖paintComponent()而不是覆盖paint():
Javadoc解释the Paint Mechanism:
By now you know that the paintComponent method is where all of your
painting code should be placed. It is true that this method will be
invoked when it is time to paint, but painting actually begins higher
up the class heirarchy, with the paint method (defined by
java.awt.Component.) This method will be executed by the painting
subsystem whenever you component needs to be rendered. Its signature
is:
- public void paint(Graphics g)
javax.swing.JComponent extends this class and further factors the
paint method into three separate methods, which are invoked in the
following order:
- protected void paintComponent(Graphics g)
- protected void paintBorder(Graphics g)
- protected void paintChildren(Graphics g)
The API does nothing to prevent your code from overriding paintBorder
and paintChildren, but generally speaking, there is no reason for you
to do so. For all practical purposes paintComponent will be the only
method that you will ever need to override.
这就是你的PaintPractice代码应该调用super.paintComponent(g)的原因.
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
此外,您不需要在mousePressed(MouseEvent e)方法中调用removeAll().
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
标签:java-2d,java,swing,jpanel 来源: https://codeday.me/bug/20190722/1504929.html