1

mi problema es el siguiente:

Estoy intentando hacer una aplicacion con FXML pero a la hora de cargar el archivo FXML en JavaFX me esta dando un problema de localizacion de el archivo de FXML, mi estructura de proyecto es la siguiente:

Estructura de proyecto

Y por aqui os dejo mi clase MainClass.java

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
 *
 * @author verodaht
 */
public class MainClass extends Application {

    private Stage primaryStage;
    private AnchorPane rootLayout;


    @Override
    public void start(Stage primaryStage) throws IOException {

        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("AddressApp");

        initRootLayout();

    }

    private void initRootLayout() throws IOException {

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainClass.class.getResource("/vista/Main.fxml"));

        rootLayout = (AnchorPane) loader.load();

        Scene scene = new Scene (rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }



}

En la siguiente linea:
loader.setLocation(MainClass.class.getResource("/vista/Main.fxml"));

El Main.fxml

    <?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <AnchorPane prefHeight="907.0" prefWidth="1328.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
      <SplitPane dividerPositions="0.8114630467571644" prefHeight="907.0" prefWidth="1328.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <items>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
               <children>
                  <TableView prefHeight="905.0" prefWidth="1072.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                    <columns>
                      <TableColumn prefWidth="181.0" text="NOMBRE" />
                      <TableColumn prefWidth="165.0" text="APELLIDO" />                        <TableColumn prefWidth="232.0" text="POSICION" />
                        <TableColumn prefWidth="206.0" text="DORSAL" />
                    </columns>
                  </TableView>
               </children>
            </AnchorPane>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
               <children>
                  <VBox fillWidth="false" prefHeight="905.0" prefWidth="246.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                     <children>
                        <Button mnemonicParsing="false" prefHeight="68.0" prefWidth="246.0" text="AÑADIR" AnchorPane.topAnchor="500.0" />
                        <Button mnemonicParsing="false" prefHeight="71.0" prefWidth="250.0" text="EDITAR" />
                        <Button mnemonicParsing="false" prefHeight="65.0" prefWidth="254.0" text="BORRAR" />
                     </children>
                  </VBox>
               </children>
            </AnchorPane>
        </items>
      </SplitPane>
   </children>
</AnchorPane>

He probado a ponerlo de varias formas ya estilo:

(vista/Main.fxml) (../vista/Main.fxml) (/Main.fxml)

Y no se si me dejo alguna.

Y con todas me esta dando el siguiente error:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Location is not set.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at MainClass.initRootLayout(MainClass.java:33)
    at MainClass.start(MainClass.java:24)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    ... 1 more

Y no se por que.

Gracias de antemano

8
  • Podrias compartir el codigo de tu archivo Main.fxml. ¿Qué controlador tiene asignado?
    – Ziggy Pop
    el 29 ene. 2019 a las 10:57
  • hola Ziggy, por aqui te lo dejo el 29 ene. 2019 a las 11:04
  • No veo que tengas asignado un controlador para tu archivo te estaria faltando la declaracion fx:controller="CarpetaControlador.TuControlador" en tu AnchorPane.¿Me explico?, veo tu modelo y vista pero creo que no tenes una clase controlador, es asi? deberias crear un controlador para el Main.fxml
    – Ziggy Pop
    el 29 ene. 2019 a las 11:25
  • Prueba de este modo: FXMLLoader loader = new FXMLLoader(getClass().getResource("/vista/Main.fxml")); y nada más.
    – A. Cedano
    el 29 ene. 2019 a las 12:51
  • Yo probe el codigo que paso y cambiando en el metodo InitiParent. rootLayout = (AnchorPane) loader.load(); por rootLayout = loader.load(); y dejando solo vista/Main.fxml sin la barra (Windows) funciona, pero creo que los errores que le marca es por el controlador.
    – Ziggy Pop
    el 29 ene. 2019 a las 15:58

2 respuestas 2

0

Puedes aplicar estos algoritmos para cargar el FXML

public Parent cargarFXML(String rutaFXML) {

    Parent root = null;
    try {
       root = FXMLLoader.load(getClass().getResource(rutaFXML));
    } catch (IOException ex) {
        Logger.getLogger(VentanaImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return root;

Luego puedes cargar cualquier ventana

public void nuevaVentana(String rutaFXML) {
   Stage stage = new Stage();
   //stage.initStyle(StageStyle.TRANSPARENT);


   Scene scene = new Scene(this.cargarFXML(rutaFXML));
  // scene.setFill(null);

   stage.setTitle("Sistema de Gestión de Documentos");
   stage.getIcons().add(new Image(getClass().getResource("/proyectogestiondocumental/recursos/logo.png").toExternalForm()));


   stage.setScene(scene);
   //stage.setResizable(false);
   stage.sizeToScene();
   stage.show();
}
}
0

Creo que es porque no tienes controlador. Si pulsas en el archivo .fxml botón derecho, deberías de tener la opción de make controller como te pongo en la imagen make controller

Sino dentro del xml, le tienes que agregar al anchorpane principal la siguiente etiqueta y crear tu el archivo del controlador a mano

introducir la descripción de la imagen aquí

La estructura es fx:controller="NombrePaquete.NombreDelControlador+Controller"

El resultado en el árbol sería el siguiente

introducir la descripción de la imagen aquí

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.