Clicking on a JPanel to draw shapes

百般思念 提交于 2019-12-02 01:43:01
trashgod

Absent a complete example, it's hard to say. I'd expect your DrawingCanvas to override paintComponent() in order to render the accumulated Shape instances in shapeList. You might compare your approach to that shown in GaphPanel, cited here.

The code you provided is not complete, but anyway the problem is in your mouseClicked method, if you change your second if to something like the following for example:

    if (e.getSource().equals(canvas) && createShape == true){
        int x = e.getX();
        int y = e.getY();
        s = new Rectangle(x,y,x+50,y+50);
        canvas.addShape(s);
    }

then a rectangle of width & height 50 will be painted whenever you click on the canvas, depending on your x, y location (you could change the fixed width/height by using a variable based on user input). Also, I'm not sure what you're trying to do in your first if section where you're adding a MouseListener to a newly created shape that is not added to the canvas, I guess there's something else you want to do...

I had to overwrite the canvas class' paint method; call super.paint in the canvas class and repaint each shape individually

public void paint(Graphics g){
            super.paint(g);
            for(int i=0;i<shapeList.size();i++){
                ((Shape)shapeList.get(i)).paint(g);
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!