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
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);
}
}
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...