Fxmlloader load ошибка

I can not figure out for the life of me the problem with this code. I have done research on many similar questions here, addressing whether the directories were correct, possible wrong function calls etc.

I am hoping someone can help me out. Everything is in a file called login in an app called loginapp.

Here is Login.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package login;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class Login extends Application   {

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Login.fxml"));
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("Login.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("Fracken");
        stage.show();
    }
}

Here is Login.fxml

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

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

<AnchorPane id="AnchorPane" prefHeight="317.0" prefWidth="326.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.Login">
   <children>
      <TextField fx:id="txtUsername" layoutX="110.0" layoutY="45.0" promptText="Username" />
      <PasswordField fx:id="txtPassword" layoutX="110.0" layoutY="115.0" promptText="Password" />
      <Button fx:id="btnLogin" layoutX="110.0" layoutY="184.0" mnemonicParsing="false" onAction="btnLoginAction" text="Login" />
      <Button fx:id="btnReset" layoutX="232.0" layoutY="184.0" mnemonicParsing="false" onAction="btnResetAction" text="Reset" />
      <Label fx:id="lblMessage" layoutX="110.0" layoutY="236.0" prefHeight="31.0" prefWidth="187.0" />
   </children>
</AnchorPane>

I am sure the issue is with

Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("Login.fxml"));

I get this error.

Executing C:UsersDavidDesktopJava Projectloginappdistrun122343396loginapp.jar using platform C:Program FilesJavajdk1.8.0_111jre/bin/java
Exception in Application start method
Exception in thread "main" 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 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$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at login.Login.start(Login.java:23)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Java Result: 1

Please help me, I have looked at other’s similar issues on here but no solutions worked.

  1. Reasons Causing the JavaFX FXML Load Exception
  2. Solution to the JavaFX FXML Load Exception

Solution to the JavaFX FXML Load Exception

This tutorial educates about the reasons causing the JavaFX FXML load exception and provides a quick solution.

Reasons Causing the JavaFX FXML Load Exception

The first reason for getting the JavaFX FXML load exception is when the path to an FXML file is not specified correctly to a loader. The path /fxml/view.fxml refers to a file view.fxml in a folder named fxml which resides in the resources folder, i.e., on the classpath.

The getClass().getResource() call invokes an object classloader at runtime, which searches for the classpath for a resource passed to it. In this way, it will find the fxml folder and view.fxml file inside that folder.

The second reason can be having a mismatched component ID which means we may have updated a component ID in our Controller file but forgot to change that ID on the FXML file (or vice-versa). In this case, the Controller would not be able to link that component on the view.fxml file.

See the following chunk to have a clear understanding.

On the Controller File:

On the FXML View File:

Following is the solution to both of these reasons.

Solution to the JavaFX FXML Load Exception

To run this application, we are using Java 18, JavaFX 13, and NetBeans IDE version 13. You may use all of them as per your choice.

Example Code (view.fxml file, the view file):

<!--Step1: XML declaration-->
<?xml version="1.0" encoding="UTF-8"?>

<!--Step 2: import necessary java types in FXML-->

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<!--Step 3: specify the FXML namespace-->

<AnchorPane prefHeight="300.0" prefWidth="400.0"
xmlns="http://javafx.com/javafx/11.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.mycompany.javafx_fxml_loadexception.viewController">

    <!--Step 4: layout pane have children-->
    <children>
        <Button fx:id="btTest" layoutX="170.0"
        layoutY="208.0" mnemonicParsing="false"
        onAction="#onBtTestAction" text="Button" />

        <Label layoutX="167.0" layoutY="126.0" text="Cick here!" />
   </children>

</AnchorPane>

Following is the step-by-step explanation of the above code.

  • We write an XML declaration by describing the version and encoding.
  • Import all the necessary Java types in FXML.
  • We use the AnchorPane tag to declare the fx namespace prefix. This tag permits the child nodes’ edges to be anchored to the offset from an edge of the anchor pane.

    If there is padding or border in the anchor pane, then the offsets would be measured from those insets’ inside edges. The AnchorPane tag has various properties listed below with a brief explanation.

    • The prefHeight and prefWidth properties can be used to override the region’s computed preferred height and width.

    • In FXML, the fx:controller is used to specify the controller on a root element. Remember that we are allowed to have one controller per FXML document and must be specified on the root element.

      What is the root element in this code? The AchnorPane tag is the root element for this code example which is a top-level object in an object graph of the FXML document.

      All the UI elements will be added to this element. Further, we also need to know the rules a controller must satisfy; these rules are listed below:

      • A controller is instantiated by the FXML loader.
      • A controller must have the public no-args constructor. The FXML loader would be unable to instantiate it if it is not there, resulting in an exception at load time.
      • A controller can contain accessible functions that can also be specified as the event handlers in the FXML.
      • The FXML controller automatically looks for a controller’s accessible instance variable(s). If the accessible instance variable’s name matches an element’s fx:id attribute, an object reference from the FXML will automatically be copied into a controller instance variable.

      This feature will make UI elements’ references in the FXML accessible to the controller. Then, the controller would be able to use them.

    • A controller can also access the initialize() function, which must not accept arguments and return the void type. Once the FXML document’s loading process is complete, the FXML loader calls the initialize() function.

  • In FXML, the layout panes contain the children as their child elements. Considering the project requirements, we can add labels, buttons, and other elements.

Example Code (viewController.java class, the controller class):

//Step 1: replace this package name with your package name
package com.mycompany.javafx_fxml_loadexception;

//Step 2: import necessary libraries
import javafx.fxml.FXML;
import javafx.scene.control.Button;

// Step 3: viewController class
public class viewController {

    //define button
    @FXML
    private Button btTest;

    //define the action when the button is clicked
    @FXML
    public void onBtTestAction() {
        System.out.println("CLICK");
    }//end onBtTestAction method

}//end viewController class

The viewController.java class is a controller class that uses the @FXML annotation on some members. Remember that this annotation can be used on constructors and classes.

Using this annotation, we specify that the FXML loader can easily access this member even if that is private. We do not need to use the @FXML annotation if the FXML loader uses a public member.

However, using @FXML for a public member does not raise any error. So, it is good to annotate every member.

The following FXML sets the onBtTestAction() function of a controller class as an event handler for the Button:

<Button fx:id="btTest" layoutX="170.0" layoutY="208.0" mnemonicParsing="false"         onAction="#onBtTestAction" text="Button" />

Example Code (App.java class, the main class):

//Step 1: replace the package name with your package name
package com.mycompany.javafx_fxml_loadexception;

//Step 2: import necessary libraries
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

//Step 3: primary launch class extending the Application class
public class App extends Application {

    /**
     *
     * @param stage
     */
    @Override
    public void start(Stage stage) {
        //load the view.fxml file, add it to the scene and show it
        try {
            Parent parent = FXMLLoader.load(getClass().getResource("/fxml/view.fxml"));
            //create a scene
            Scene scene = new Scene(parent);
            //set scene to a stage
            stage.setScene(scene);
            //show the stage
            stage.show();
        }//end try
        catch (IOException e) {
            e.printStackTrace();
        }//end catch
    }//end start method

    public static void main(String[] args) {
        launch(args);
    }//end main method

}//end App class

The main file extends the Application class and overrides its abstract method start(). In the start() method, we load the view.fxml file, create a scene, set this scene to a stage, and display that stage.

OUTPUT (prints the word CLICK on IDE’s console whenever we click on the Button):

Solution to JavaFX fxml Load Exception - Output

Check the following screenshot to place each file at the correct location:

Solution to JavaFX fxml Load Exception - Files Directory

_Quantium_

0 / 0 / 1

Регистрация: 27.05.2017

Сообщений: 7

1

27.05.2017, 17:26. Показов 11167. Ответов 9

Метки exception, fxml, javafx (Все метки)


Студворк — интернет-сервис помощи студентам

При нажатии на кнопку должна произойти загрузка FXML и открыться новая форма, но у меня выдаёт ошибку, не понимаю из-за чего.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package sample;
 
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
 
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class ConnectForm {
 
    @FXML
    public TextField loginInput;
 
 
    public void joinAction(ActionEvent actionEvent) {
        String allegedLogin = loginInput.getText();
        String login;
        if (allegedLogin.equalsIgnoreCase("") || allegedLogin.equalsIgnoreCase(" ") || allegedLogin.contains("  ") || allegedLogin.contains("   ")) {
            try {
                login = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                login = "UNKNOWN_USER";
            }
        } else {
            login = allegedLogin;
        }
 
        loginInput.setText(login);
 
        try {
            Stage stage = new Stage();
            Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); //Сюда ссылается Exception
 
            stage.setTitle("ChatFX Client");
            stage.setScene(new Scene(root, 400, 500));
            stage.getScene().getStylesheets().add(0, "sample/MainForm.css");
            stage.show();
            Main.st.hide();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

IDE выдаёт:

Код

javafx.fxml.LoadException: 
/C:/Users/ANTON/IdeaProjects/ChatFXClient/out/production/ChatFXClient/sample/sample.fxml:10

	at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
	at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
	at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
	at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
	at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
	at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
	at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
	at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
	at sample.ConnectForm.joinAction(ConnectForm.java:50)
	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.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
	at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
	at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
	at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
	at javafx.event.Event.fireEvent(Event.java:198)
	at javafx.scene.Node.fireEvent(Node.java:8413)
	at javafx.scene.control.Button.fire(Button.java:185)
	at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
	at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
	at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
	at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
	at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
	at javafx.event.Event.fireEvent(Event.java:198)
	at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
	at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
	at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
	at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
	at java.security.AccessController.doPrivileged(Native Method)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
	at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
	at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
	at com.sun.glass.ui.View.notifyMouse(View.java:937)
	at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
	at java.lang.Thread.run(Thread.java:748)
java.lang.InstantiationException: sample.Controller
Caused by: java.lang.InstantiationException: sample.Controller
	at java.lang.Class.newInstance(Class.java:427)
	at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
	at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
	... 71 more
Caused by: java.lang.NoSuchMethodException: sample.Controller.<init>()
	at java.lang.Class.getConstructor0(Class.java:3082)
	at java.lang.Class.newInstance(Class.java:412)
	... 73 more



0



77 / 77 / 77

Регистрация: 29.01.2017

Сообщений: 167

27.05.2017, 17:39

2

говорит в 10й строке в sample.fxml ошибка.
выложи fxml файл



0



_Quantium_

0 / 0 / 1

Регистрация: 27.05.2017

Сообщений: 7

27.05.2017, 17:43

 [ТС]

3

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.Cursor?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.text.Font?>
 
<Pane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" >
   <children>
      <TextField blendMode="MULTIPLY" cache="true" layoutY="475.0" prefHeight="25.0" prefWidth="300.0" promptText="Ваше сообщение" styleClass="input">
         <font>
            <Font name="Segoe UI Symbol" size="12.0" />
         </font>
         <cursor>
            <Cursor fx:constant="DEFAULT" />
         </cursor>
      </TextField>
      <Button id="button" layoutX="300.0" layoutY="475.0" mnemonicParsing="false" onAction="#sendMessage" prefHeight="25.0" prefWidth="100.0" text="Отправить" />
      <TextArea id="incoming" prefHeight="476.0" prefWidth="400.0" styleClass="textarea" wrapText="true" />
   </children>
</Pane>



0



Kadota

77 / 77 / 77

Регистрация: 29.01.2017

Сообщений: 167

27.05.2017, 19:08

4

можешь скинуть Controller класс
java.lang.InstantiationException: sample.Controller

XML
1
<Pane fx:controller="sample.Controller" ...



0



_Quantium_

0 / 0 / 1

Регистрация: 27.05.2017

Сообщений: 7

27.05.2017, 19:12

 [ТС]

5

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package sample;
 
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
public class Controller {
 
    @FXML
    TextField msginput;
 
    @FXML
    TextField fx_input_login;
 
    @FXML
    public TextArea incoming;
 
    private Main main;
 
    Controller(Main main){
        this.main = main;
    }
 
    public void sendMessage(ActionEvent actionEvent) {
        String msg = msginput.getText();
        if(msg.equalsIgnoreCase("")) {
            incoming.appendText("Вы не ввели сообщение!n");
            return;
        }
 
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String time = dateFormat.format(cal.getTime());
 
        msg = "[" + fx_input_login.getText() + " ; " + time + " ] : ";
 
        main.getWriter().write(msg);
        main.getWriter().flush();
 
    }
}



0



77 / 77 / 77

Регистрация: 29.01.2017

Сообщений: 167

27.05.2017, 21:12

6

Лучший ответ Сообщение было отмечено _Quantium_ как решение

Решение

это из-за конструктора в Controller. С конструктором даже пустой проект не компилится. Не нашел почему.
Попробуй вместо конструктора использовать сеттер, например



1



0 / 0 / 1

Регистрация: 27.05.2017

Сообщений: 7

27.05.2017, 21:15

 [ТС]

7

Спасибо, работает



0



635 / 527 / 165

Регистрация: 01.04.2010

Сообщений: 1,843

29.05.2017, 23:24

8

Цитата
Сообщение от Kadota
Посмотреть сообщение

Не нашел почему

Потому что контроллер создаётся при помощи конструктора без аргументов, если такого конструктора нет, то и создание контроллера невозможно. Соответственно, имеет место быть исключительная ситуация.



0



77 / 77 / 77

Регистрация: 29.01.2017

Сообщений: 167

30.05.2017, 09:17

9

aleksandy, но я пробовал добавить пустой конструктор, все равно была ошибка



0



_Quantium_

0 / 0 / 1

Регистрация: 27.05.2017

Сообщений: 7

30.05.2017, 09:21

 [ТС]

10

У меня работало с конструктором, если я его в fxml не вписывал, а при создании формы в FXMLLoader добавлял контроллер с его конструктором,

Java
1
2
3
4
5
6
7
8
9
 Stage stage = new Stage();
            FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
            loader.setController(new Controller(new Main, this, "another_string"));
            Parent root = loader.load();
 
            stage.setTitle("sample");
            stage.setScene(new Scene(root, 400, 500));
            stage.getScene().getStylesheets().add(0, "sample/MainForm.css");
            stage.show();



0



Я только учусь и сразу же возникли проблемы с JavaFX. Библиотеки я подключил! Всё установил, а всё ровно ошибка!
Main:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        //Parent root = FXMLLoader.load(getClass().getResource("/fxml/main.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }

Conroller:

package sample;

public class Controller {
}

sample.fxml:

<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>

Сама ошибка!!!

"C:Program FilesJavajdk-12binjava.exe" "--module-path=C:Program FilesJavajavafx-sdk-11.0.2lib--add-modules=javafx.controls" --add-modules javafx.base,javafx.graphics --add-reads javafx.base=ALL-UNNAMED --add-reads javafx.graphics=ALL-UNNAMED "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.1libidea_rt.jar=63514:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.1bin" -Dfile.encoding=UTF-8 -classpath "C:UsersdpozhDesktopJAVAJAVA-KODlesson16outproductionlesson16;C:Program FilesJavajavafx-sdk-11.0.2libsrc.zip;C:Program FilesJavajavafx-sdk-11.0.2libjavafx-swt.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.web.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.base.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.fxml.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.media.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.swing.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.controls.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.graphics.jar" -p "C:Program FilesJavajavafx-sdk-11.0.2libjavafx.base.jar;C:Program FilesJavajavafx-sdk-11.0.2libjavafx.graphics.jar" sample.Main
Exception in Application start method
java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
	at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x7f1029bf) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x7f1029bf
	at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
	at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
	at sample.Main.start(Main.java:13)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
	at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
	... 1 more
Exception running application sample.Main

Process finished with exit code 1

5c9faf10850ca768187851.png5c9faf18b0bf7695742910.png


  • Вопрос задан

    более трёх лет назад

  • 11018 просмотров

Всё заработало, установил jdk 8u201

Пригласить эксперта

У вас ошибка class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x7f1029bf) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x7f1029bf сообщает о том, что он не может что-то найти/подключить.

Так как в VM options у вас был указан —add-modules javafx.controls, но нет, например, javafx.fxml и javafx.graphics, предлагаю именно их и добавить (через запятую после —add-modules javafx.controls).

Я сам потратил некоторое время, но разобрался. Для себя в поле VM options прописал следующее:

--module-path "C:Program FilesJavajavafx-sdk-11.0.2lib" --add-modules javafx.controls,javafx.fxml,javafx.base,javafx.graphics,javafx.web --add-exports javafx.graphics/com.sun.javafx.sg.prism=ALL-UNNAMED

У меня заработало))


  • Показать ещё
    Загружается…

04 июн. 2023, в 01:35

1500 руб./за проект

04 июн. 2023, в 01:25

40000 руб./за проект

03 июн. 2023, в 23:42

1500 руб./за проект

Минуточку внимания

I am using Intellij (JavaFX with Maven module), after adding the javafx plugins I get the following error:
Exception in Application start method

java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
	at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x36cbb069) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x36cbb069
	at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
	at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
	at app.Main.start(Main.java:24)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
	at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
	... 1 more
Exception running application app.Main

it is happening on:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml")); // The sample.fxml is in the resources folder
Here is my maven pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>Pere</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.3</version>
                <configuration>
                    <mainClass>org.openjfx.App</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>12.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>12.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics</artifactId>
            <version>12.0.2</version>
        </dependency>
    </dependencies>



</project>

Понравилась статья? Поделить с друзьями:
  • Fuzzy s821 ошибка дверцы
  • Fuso canter ошибка p0093
  • Fusion chef by julabo ошибка e01
  • Fused location ошибка
  • Fuse dad ошибка