Clicking on a JPanel to draw shapes

后端 未结 3 1106
没有蜡笔的小新
没有蜡笔的小新 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:14

    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);
                }
            }
    
    0 讨论(0)
  • 2021-01-22 10:19

    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.

    image

    0 讨论(0)
  • 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...

    0 讨论(0)
提交回复
热议问题