To use the getHostServices() in an application with FXML you must pass Hostservices as a parameter to your controller, as this method can only be called in the main class (application class method).
In your controller you will have to declare a Hostservices type variable in this way:
public class SeuController implements Initializable {
private HostServices host;
// Deve ser público pois será chamado na classe principal
public void setHostService(HostServices host){
this.host = host;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// ...
}
// Método para abrir o browser padrão do usuário com o respectivo site
@FXML
public void irParaSite(ActionEvent event){
host.showDocument("http://www.seusite.com");
}
}
In the main class you should make a slight modification:
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = (Parent) loader.load();
// Passando o HostService para o controller
SeuController controller = loader.getController();
controller.setHostService(getHostServices());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
I use Scenebuilder to mount my FXML and here each menu within the menubar comes with an included menuitem.
<Menu fx:id="menu" mnemonicParsing="false" text="About Us">
<items>
<MenuItem mnemonicParsing="false" onAction="#irParaSite" text="Action 1" />
</items>
</Menu>
Although the menu can receive onAction, only Menuitem performs the action when clicked. If you put onAction on both, clicking Menuitem will activate onAction from the Menu as well.
[EDIT - Workaround to put an action in the Menu instead of Menuitem]
This issue is an adaptation of the following answer (Author credits): https://stackoverflow.com/questions/10315774/javafx-2-0-activating-a-menu-like-a-menuitem
As the behavior you expect is not usual there is an elegant way to configure setOnMouseClick directly from the Menu (See in the documentation that there is no such method) and addEventHandler does not correctly capture mouse events.
Below we have a workaround that solves the problem:
Note: For the solution to work you must remove the current text from the menu, that is, the tag "text=aDaAba" should not exist in FXML. Otherwise the two texts will appear and the click event will not work.
Label menuLabel = new Label("nomeDaAba");
menuLabel.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
host.showDocument("http://www.seusite.com");
}
});
menu.setGraphic(menuLabel);
As you can see the event was placed on the Menu Label, and worked in the tests performed.
Sorry! Now it’s done ;)
– Eduardo Toffolo