Clicking on a JPanel to draw shapes

后端 未结 3 1107
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 09:54

I have a JFrame containing 3 JPanels; Options, menu, canvas. In options there are a number of JButtons representing shapes. The aim is to click on the JButton of a shape e.g. re

3条回答
  •  失恋的感觉
    2021-01-22 10:21

    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...

提交回复
热议问题