简体   繁体   中英

Is there any method to create a new object of different sub-class when a button is pressed and then put it inside dragHandler?

I don't know if I am asking the right question. I am creating a paint-like application in which the user selects a shape and then draws it on the canvas with mouse drag. I have created a superclass GeometricObject and the sub-classes Line, Rectangle and Eclipse extend it. I declared a variable "go" of type GeometricObject. Based on which button is pressed, a new object of a different sub-class is created and stored in go. For example, if Eclipse button is pressed, a new object of type Eclipse is created and so on. In the dragHandler, if go variable stores a reference to object of type Eclipse, then go is casted to type eclipse and draw method of eclipse is called. But in my case this logic does not work.

GeometricObject go;
public void dragHandler(MouseEvent mouseEvent){

/// transgc is graphicsContext2D

        transgc.clearRect(0,0,screenWidth,screenHeight);
        ex=mouseEvent.getX();
        ey=mouseEvent.getY();

        GeometricObject go=new Rectangle(sx,sy,ex,ey,colorPicker.getValue());

        if(go instanceof Lines)
            ((Lines)go).draw(transgc);
        else if(go instanceof Eclipse)
            ((Eclipse)go).draw(transgc);
        else if(go instanceof Rectangle)
            ((Rectangle)go).draw(transgc);

}

 public void eclipseHandler(ActionEvent e){
        go=new Eclipse(sx,sy,ex,ey,colorPicker.getValue());
    }
    public void rectangleHandler(ActionEvent e){
        go=new Rectangle(sx,sy,ex,ey,colorPicker.getValue());
    }

    public void linesHandler(ActionEvent e){
        go=new Lines(sx,sy,ex,ey,colorPicker.getValue());
    }

Expected output - different shape is drawn when different button is pressed and then mouse is dragged

Actual output - nothing is getting drawn while the mouse is dragged

GeometricObject go=new Rectangle(sx,sy,ex,ey,colorPicker.getValue());

        if(go instanceof Lines)
            ((Lines)go).draw(transgc);
        else if(go instanceof Eclipse)
            ((Eclipse)go).draw(transgc);
        else if(go instanceof Rectangle)
            ((Rectangle)go).draw(transgc);

Here you are always creating a Rectangle object 'go'. It should be omitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM