简体   繁体   中英

How do I make a java class that inherits from another one which is loading an fxml file

I have a custom interface that I created in scene builder and I want to reuse it in a variation created with a child class. The problem seems to be that it won't inherit methods marked with @FXML. Is there any way to extend a class that loads fxml instead of copying the entire class?

Example Parent Class:

public class Browser extends StackPane implements Initializable {

public Browser() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Browser.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}

@Override
public void initialize(URL url, ResourceBundle rb) {
}

// Adds a new tab.
@FXML
private void addTab(ActionEvent event) {
    BrowserTab tab = new BrowserTab();
    tab.getEngine().load(initialTab.getAddress());
    if (tabs.getTabs().size() >= TABMAX + 1) {
        BaseApp.showNotify("You may open a maximum of " + TABMAX + " tabs.");
    } else {
        tabs.getTabs().add(tabs.getTabs().size() - 1, tab.tab);
    }
}
}

Example Child Class:

public class AdBrowser extends Browser {

public AdBrowser() {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/AdBrowser.fxml"));
    fxmlLoader.setRoot(this);
    fxmlLoader.setController(this);
    try {
        fxmlLoader.load();
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}

}

When I try to run the program instantiating the child class I get and error saying Controller method "addTab" not found.

Turning my comment into an answer.

I have no experience at all with fxml, but you could try broadening the access permissions to that method, eg from private to protected .

Code outside the class defining a private method is usually not allowed to call that method. Some frameworks circumvent these restrictions, and perhaps javafx is among them. But even these frameworks might and often will distinguish based on what access privileges a given method has.

One reason behind this is that a private method name should never cause a clash: you can have two private methods of the same name in base class and derived class, and neither knows of the other. They will not override one another. As far as the derived class is concerned, the method in the parent class simply does not exist. Since this is a reasonable working principle, it makes sense for frameworks to follow this as well, even if circumvented access restrictions would allow them to act otherwise.

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