我在点击特定按钮时尝试在JPanel上绘制图像。当按下带圆圈的按钮时,我应该可以绘制圆形图像,类似于矩形按钮。我只能绘制一次,这意味着先前绘制的图像被删除。
public class Panel1 extends JPanel {
Image image;
Image image2;
private Point drawPoint;
public Panel1(){
Toolkit toolkit = Toolkit.getDefaultToolkit();
image = toolkit.getImage("JavaIcon\\p3.png");
image2 = toolkit.getImage("JavaIcon\\t.png");
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
drawPoint = new Point(e.getPoint());
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (drawPoint != null) {
if(i==1){
g2d.drawImage(image, drawPoint.x, drawPoint.y, this);
}
if(i==2){
g2d.drawImage(image2, drawPoint.x, drawPoint.y, this);
}
}
g2d.dispose();
}
}
在“if语句”中,我指示是否单击某个按钮,如果为1,则单击一个圆形按钮。
最新编辑
它仍然会删除之前绘制的圆圈:
ArrayList<drawnCircle> list1 = new ArrayList<drawnCircle>();
public void addCircle(Image image, Point point){
Toolkit toolkit = Toolkit.getDefaultToolkit();
image = toolkit.getImage("JavaIcon\\p3.png");
drawnCircle dc = new drawnCircle(image, point);
list1.add(dc);
repaint();
}
public void clear(){
list1.clear();
repaint();
}
class drawnCircle{
private Image image;
private Point point;
public drawnCircle(Image image, Point myPoint){
this.image = image;
this.point = myPoint;
}
public Image getImage(){
return image;
}
public void setImage(Image image){
this.image = image;
}
public Point getPoint(){
return point;
}
}