Search code examples
javaclassjavafxconstructorextend

Java: Extending a class and adding a no-arg constructor (for wrapper)


I need to extend a class ChartViewer, which does not have a no-arg constructor, with a class ChartViewerWrapper to add a no-arg constructor.

How would I go about doing this?


Extra information (not that relevant)

The reason I need to do this is as a workaround as per below, the quote is taken from a forum regarding JavaFX 8 and JFreeChart. I want to use ChartViewer in FXML:

Currently the ChartViewer node cannot be used in FXML. I think the only reason is because it does not have a constructor without arguments (when I extended the ChartViewer class and added a simple constructor without arguments, I could add my wrapper class into FXML and it works).

(I could just add a no-arg constructor directly in ChartViewer, but it is an External Library and for various good reasons I decided I don't want to do this.)


Solution

  • Although Scary Wombat answered the general question I had, this is a solution for my particular case:

    public class ChartViewerWrapper extends ChartViewer {
    
        public ChartViewerWrapper() {
            super(new JFreeChart(new XYPlot())); // just an empty placeholder...
        }
    
    }
    

    Then you can use ChartViewerWrapper in FXML, for example like so:

    <Pane>
        <ChartViewerWrapper />
    </Pane>
    

    And change the associated properties in the controller when you need to.