如何显示文件中的文本?

问题描述 投票:1回答:1

以下方法应该从名为“ helpText”的文本文件中读取文本。此方法适用于旧项目,但不适用于我的新项目。

Label text;

@FXML
public void initialize() {
    try {
        text.setText(
            new String(
              ScreenController.getResAsStream("text/helpText").readAllBytes(),
                StandardCharsets.UTF_8).strip());
        System.out.println(text.isResizable());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是包括上述方法的RulesForPlayGame.java

package com.example.rps.controllers;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class RulesForPlayGameWindow extends Window {

@FXML
Label text;

@FXML
public void initialize() {
    try {
        text.setText(
            new String(
                ScreenController.getResAsStream("/text/helpText").readAllBytes(),
                StandardCharsets.UTF_8).strip());
        System.out.println(text.isResizable());
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
    }
}

}

这是ScreenController.java,其中包括getResAsStream中使用的方法RulesForPlayGameWindow.java

package com.example.rps.controllers;


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

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;


public class ScreenController {

private Connection conn;
private Stage stage;


public static final String LOGIN = "src/main/resources/fxml/login.fxml";
public static final String CREATE_ACCOUNT = "src/main/resources/fxml/createAccount.fxml";
public static final String ACTIVE_GAMES = "src/main/resources/fxml/activeGame.fxml";
public static final String NEW_GAME = "src/main/resources/fxml/newGame.fxml";
public static final String GAME = "src/main/resources/fxml/game.fxml";
public static final String WINNER = "src/main/resources/fxml/winner.fxml";
public static final String ADD_FRIEND = "src/main/resources/fxml/addFriend.fxml";
public static final String RULES = "src/main/resources/fxml/rulesforplaygame.fxml";



public ScreenController(Connection conn, Stage stage) {
    this.stage = stage;
    this.conn = conn;
}



public void setWindow (String selectedWindow, String token) {


    try {
        URL url = new File(selectedWindow).toURI().toURL();
        FXMLLoader loader = new FXMLLoader(url);
        Parent root = loader.load();
        Scene scene = new Scene(root);

        Window window = loader.getController();
        window.init(conn, this, token);

        if (!(window instanceof LoginWindow) && !(window instanceof CreateAccountWindow) && !(window instanceof RulesForPlayGameWindow)) {

            boolean validToken = window.validateToken(token);

            if(!validToken) {
                setWindow(LOGIN, "");
            } else {
                window.setUpWindow();

                stage.setScene(scene);
                stage.show();
            }
        } else {

            window.setUpWindow();

            stage.setScene(scene);
            stage.show();
        }



    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static InputStream getResAsStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }
}

这是RulesForPlayGame.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.TextField?>

<BorderPane id="rulesForPlayGame"
            styleClass="rulesForPlayGame"
            stylesheets="@/css/rulesForPlayGame.css"
            xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"                        

fx:controller="com.example.rps.controllers.RulesForPlayGameWindow"
prefHeight="400.0" prefWidth="600.0">

<top>
    <HBox id="headerPosition">
        <Label id="header" text="Rules"/>
    </HBox>
</top>

<Label fx:id="text" id="text" wrapText="true"/>

</BorderPane>

这是我的名为helpText的文本文件,位于resources/text内,其中资源设置为Intellij中的资源文件夹。

This is the rules to be able to play this game. Have fun playing

Current problem当我运行RulesForPlayGameWindow时,它会加载,但不会从文件中加载任何文本。我的异常消息抛出Null。

Project structure

java file-read
1个回答
0
投票

我正在回答,因为这已失控。

您的问题缺少什么:

  1. 您没有主类或应用程序类。你如何开始你的应用。

  2. 您丢失了整个堆栈跟踪。不要打印'e.getMessage()'不在您的代码中。

接下来,修复您的网址。资源已添加到您的类路径中,因此所有路径都应更改为。

public static final String LOGIN = "/fxml/login.fxml";

原因是因为您将在开发过程中使用src文件夹only运行您的应用程序。这就是为什么您拥有资源,然后您的想法就会知道将资源与应用程序捆绑在一起。

这与您尝试读取的文本文件相同。路径应为/text/helpText,根据您组织资源的方式,第一个斜杠很重要。

这里是一个完整的例子:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.text.Text?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pkg.DisplayTextController">
    <center>
        <Button fx:id="button" onAction="#buttonPressed">XYZ</Button>
    </center>
    <bottom>
        <Text fx:id="text"/>
    </bottom>
</BorderPane>

控制器:

public class DisplayTextController implements Initializable  {
    @FXML private Button button;
    @FXML private Text text;

    @FXML
    private void buttonPressed(ActionEvent evt){
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        String loaded;
        try {
            InputStream stream = getClass().getResourceAsStream("/text/help.txt");
            System.out.println(stream);
            loaded = new String( stream.readAllBytes(), StandardCharsets.UTF_8 );
        } catch(Exception e){
            loaded = "could not load " + "/text/help.txt";
            e.printStackTrace();
        }
        text.setText(loaded);
    }

}

还有我的主要班级。

public class DTMain extends Application{

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("text field");
        FXMLLoader spinnerSceneLoader = new FXMLLoader(getClass().getResource("/fxml/DisplayText.fxml"));
        Parent root = (Parent) spinnerSceneLoader.load();

        DisplayTextController ctrlrPointer = (DisplayTextController) spinnerSceneLoader.getController();

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();




    }

}

这项工作,并注意到一个主要的区别,我只是使用“ getClass”而不是您的Thread.getContextLoader()...

© www.soinside.com 2019 - 2024. All rights reserved.