2017-11-28 61 views
2

ListView를 업데이트하려고하는데 list.setItems (newObList)가 실행될 때 java.lang.NullPointerException이 발생하고 ObservableList 참조를 새 업데이트 목록으로 변경하려고 시도했지만 아무 것도 수행하지 않았습니다. . 목록을 먼저 지운 다음 항목을 다시 설정하면 NullPointerException이 발생합니다. 또한 항목을 null로 설정 한 다음 NullPointerException을 다시 설정해 보았습니다. 나는 혼란 스러울뿐입니다. 어떻게 해결해야할지 모르겠습니다. 나를 안내 해줘.ListView를 업데이트하면 NullPointerException이 발생합니다.

refreshData() 메서드의 경우 list.setItems(obList); 문에서 예외가 발생합니다. 보조 스테이지의 닫기 버튼 ("새 단어 삽입"단계)을 누르면 해당 버튼이 refreshData() 메서드를 호출하는 closeInsertWord() 메서드를 호출합니다. MainController.java이라는 컨트롤러 클래스 하나만 사용합니다.

public class MainController implements Initializable{ 

@FXML 
private ListView<String> list; 


@FXML 
TextField iWord, iMeanings, iSyn, iAnt; 


public AVLTree dictTree; 
public ArrayList<String> aList; 
ObservableList<String> obList; 

@Override 
public void initialize(URL location, ResourceBundle resources) 
{ 
    dictTree = readData(); 
} 

public void fillList() 
{ 

    aList = new ArrayList<>(); 

    aList.add("Word: meaning1, meaning2, ... , meaningN/a synonym * an antonym"); 
    dictTree.inOrder(aList); 

    obList = FXCollections.observableArrayList(aList); 
    list.setItems(obList); 
} 

// 여기에 몇 가지 중요하지 않은 코드

public void openInsertWord() throws Exception 
{ 
    Stage primaryStage2 = new Stage(); 

    Parent root = FXMLLoader.load(getClass().getResource("InsertUI.fxml")); 
    primaryStage2.setTitle("Insert a word"); 
    primaryStage2.getIcons().add(new Image("file:icon.png")); 
    primaryStage2.setScene(new Scene(root)); 
    primaryStage2.setResizable(false); 
    primaryStage2.initStyle(StageStyle.UNDECORATED); 
    primaryStage2.show(); 
} 

public void insertWord() 
{ 
    String word = iWord.getText(); 

    String synonym = iSyn.getText(); 
    String antonym = iAnt.getText(); 

    String[] meanings = iMeanings.getText().split("[, ]+"); 

    dictTree.insert(word, meanings, synonym, antonym); 
} 

public void refreshData() 
{ 
    aList = new ArrayList<>(); 

    aList.add("Word: meaning1, meaning2, ... , meaningN/a synonym * an antonym"); 
    dictTree.inOrder(aList); 

    obList = FXCollections.observableArrayList(aList); 

    list.setItems(obList); // The exception happens here 
} 

public void closeInsertWord() 
{ 
    (iWord).getScene().getWindow().hide(); 
    refreshData(); 
} 

메인 클래스 :

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

public class Main extends Application 
{ 

    @Override 
    public void start(Stage primaryStage) throws Exception 
    { 
     Parent root = FXMLLoader.load(getClass().getResource("MainUI.fxml")); 
     primaryStage.setTitle("dict"); 
     primaryStage.getIcons().add(new Image("file:icon.png")); 
     primaryStage.setScene(new Scene(root)); 
     primaryStage.setResizable(false); 
     primaryStage.show(); 
    } 

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

스택 추적 :

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774) 
    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.EventDispatchChainImp`enter code here`l.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) 
Caused by: 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.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:1771) 
    ... 48 more 
Caused by: java.lang.NullPointerException 
    at MainController.refreshData(MainController.java:155) 
    at MainController.closeInsertWord(MainController.java:161) 
    ... 58 more 

메인 무대 FXML 파일의 내용 (MainUI.fxml) :

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

<?import javafx.scene.control.Label?> 
<?import javafx.scene.control.ListView?> 
<?import javafx.scene.control.Menu?> 
<?import javafx.scene.control.MenuBar?> 
<?import javafx.scene.control.MenuItem?> 
<?import javafx.scene.effect.InnerShadow?> 
<?import javafx.scene.layout.AnchorPane?> 
<?import javafx.scene.text.Font?> 

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="698.0" prefWidth="582.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController"> 
    <children> 
     <Label layoutX="257.0" layoutY="42.0" text="Dictionary" textFill="#720000"> 
     <font> 
      <Font name="System Bold" size="14.0" /> 
     </font> 
     </Label> 
     <ListView fx:id="list" layoutX="22.0" layoutY="72.0" prefHeight="148.0" prefWidth="541.0"> 
     <effect> 
      <InnerShadow blurType="TWO_PASS_BOX" /> 
     </effect></ListView> 
     <MenuBar prefHeight="20.0" prefWidth="582.0"> 
     <menus> 
      <Menu mnemonicParsing="false" text="File"> 
      <items> 
       <MenuItem fx:id="load" mnemonicParsing="false" onAction="#fillList" text="Load Data" /> 
        <MenuItem fx:id="export" mnemonicParsing="false" onAction="#export" text="Export to a file" /> 
        <MenuItem fx:id="close" mnemonicParsing="false" onAction="#close" text="Close" /> 
      </items> 
      </Menu> 
      <Menu mnemonicParsing="false" text="Available Operations"> 
      <items> 
       <MenuItem fx:id="InsertNew" mnemonicParsing="false" onAction="#openInsertWord" text="Insert new word" /> 
        <MenuItem fx:id="showPost" mnemonicParsing="false" text="Show Postfix Expressions" /> 
        <MenuItem fx:id="evPost" mnemonicParsing="false" text="Evaluate Postfix Expressions" /> 
      </items> 
      </Menu> 
     </menus> 
     </MenuBar> 
    </children> 
</AnchorPane> 

보조 단계의 FXML 파일 (InsertUI.fxml) :

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

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


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="297.0" prefWidth="503.0" style="-fx-border-color: #720000; -fx-border-width: 3;" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController"> 
    <children> 
     <Label layoutX="176.0" layoutY="23.0" text="Insert a new word" textFill="#720000"> 
     <font> 
      <Font name="System Bold" size="18.0" /> 
     </font> 
     </Label> 
     <Label layoutX="32.0" layoutY="74.0" text="Word"> 
     <font> 
      <Font name="System Bold" size="13.0" /> 
     </font> 
     </Label> 
     <Label layoutX="32.0" layoutY="116.0" text="Meaning(s)"> 
     <font> 
      <Font name="System Bold" size="13.0" /> 
     </font> 
     </Label> 
     <Label layoutX="32.0" layoutY="159.0" text="Synonym"> 
     <font> 
      <Font name="System Bold" size="13.0" /> 
     </font> 
     </Label> 
     <Label layoutX="32.0" layoutY="204.0" text="Antonym"> 
     <font> 
      <Font name="System Bold" size="13.0" /> 
     </font> 
     </Label> 
     <TextField fx:id="iWord" layoutX="134.0" layoutY="71.0" /> 
     <TextField fx:id="iMeanings" layoutX="134.0" layoutY="113.0" prefHeight="25.0" prefWidth="355.0" /> 
     <TextField fx:id="iSyn" layoutX="134.0" layoutY="156.0" /> 
     <TextField fx:id="iAnt" layoutX="134.0" layoutY="201.0" /> 
     <Button layoutX="355.0" layoutY="245.0" mnemonicParsing="false" onAction="#insertWord" text="Insert" textFill="#720000"> 
     <font> 
      <Font name="System Bold" size="16.0" /> 
     </font> 
     </Button> 
     <Button layoutX="444.0" layoutY="263.0" mnemonicParsing="false" onAction="#closeInsertWord" text="close" /> 
    </children> 
</AnchorPane> 

The GUI screenshot here

+0

전체 스택 추적 및 FXML을 게시하십시오. 예외는 어디에서 발생합니까? 'fillList()'를 호출하는 동안? 아니면'refreshData()'중에? 그렇다면 그 방법은 어디서부터 호출됩니까? –

+0

@James_D 전체 업데이트. 모든 것을 추가했습니다. – BaraSec

+1

두 번째 FXML 파일의 컨트롤러에서'closeInsertWord()'가 호출됩니다. 해당 FXML 파일에는'fx : id = "list"'라는 요소가 없으므로 컨트롤러에서'list'는 null입니다. 따라서'list.setItems()'를 호출 할 때 null 포인터 예외가 발생합니다.서로 다른 컨트롤러에 대해 서로 다른 클래스를 생성하는 것으로 시작하십시오. 서로 다른 FXML 파일의 컨트롤러에 대해 동일한 클래스를 사용할 때 너무 혼란 스럽습니다 (사용자가 발견 한 것처럼). 당신은 https://stackoverflow.com/questions/14187963/ –

답변

0

closeInsertWord()입니다 두 번째 FXML 파일의 컨트롤러에서 부 트토 (butto) 핸들러 n 파일에 정의되어 있습니다. 해당 FXML 파일에 fx:id="list"이라는 요소가 없으므로 해당 컨트롤러에서 list가 null입니다. 따라서 list.setItems()에 전화 할 때 널 포인터 예외가 발생합니다.

두 개의 서로 다른 FXML 파일과 연결된 컨트롤러에 대해 동일한 클래스를 사용하는 것은 일반적으로 좋지 않습니다. 각 컨트롤러 인스턴스마다 어떤 필드가 초기화되고 null인지 추적하는 것은 매우 어렵습니다.

각 FXML 파일마다 다른 컨트롤러 클래스를 만듭니다. 해당 파일을로드 할 때 필요한 두 번째 컨트롤러로 데이터를 전달하십시오.

같은 뭔가 :

public class MainController implements Initializable{ 

    @FXML 
    private ListView<String> list; 

    private AVLTree dictTree; 

    @Override 
    public void initialize(URL location, ResourceBundle resources) 
    { 
     dictTree = readData(); 
    } 

    public void fillList() 
    { 

     List<String> aList = new ArrayList<>(); 
     String data = "Word: meaning1, meaning2, ... , meaningN/a synonym * an antonym"; 
     aList.add(data); 
     dictTree.inOrder(aList); 

     list.getItems.add(data); 
    } 

    public void openInsertWord() throws Exception 
    { 
     Stage primaryStage2 = new Stage(); 

     FXMLLoader loader = new FXMLLoader(getClass().getResource("InsertUI.fxml")); 
     Parent root = FXMLLoader.load(); 

     InsertWordController controller = loader.getController(); 
     // seems like these two things really contain the same information... 
     // I don't think you need both of them? 
     controller.setDictTree(dictTree); 
     controller.setItemsList(list.getItems()); 

     primaryStage2.setTitle("Insert a word"); 
     primaryStage2.getIcons().add(new Image("file:icon.png")); 
     primaryStage2.setScene(new Scene(root)); 
     primaryStage2.setResizable(false); 
     primaryStage2.initStyle(StageStyle.UNDECORATED); 
     primaryStage2.show(); 
    } 
} 

그리고 두 번째 FXML 파일에 대한 다음 컨트롤러는 :

public class InsertWordController { 

    @FXML 
    private TextField iWord; 
    @FXML 
    private TextField iMeanings ; 
    @FXML 
    private TextField iSyn ; 
    @FXML 
    private TextField iAnt ; 

    private AVLTree dictTree ; 
    private List<String> itemsList ; 

    public void setDictTree(AVLTree dictTree) { 
     this.dictTree = dictTree ; 
    } 

    public void setItemsList(List<String> itemsList) { 
     this.itemsList = itemsList ; 
    } 

    public void closeInsertWord() 
    { 
     iWord.getScene().getWindow().hide(); 
     String data = "Word: meaning1, meaning2, ... , meaningN/a synonym * an antonym" ; 
     List<String> aList = new ArrayList<>(); 
     aList.add(data); 
     dictTree.inOrder(aList); 
     itemsList.add(data); 
    } 
} 

그리고 물론

두 번째 FXML 파일의 fx:controller 속성을 변경합니다.

+0

내가 가지고있는 것에 적응하기위한 약간의 수정을 통해, 그것은 완벽하게 작동했습니다! 시간을 많이 주셔서 감사합니다 :) – BaraSec