首页 > 解决方案 > JavaFX ListView setItems() 无法解析符号

问题描述

创建 JavaFX GUI 应用程序并且无法让 ListView 在我的 Controller 类上工作。这是代码:

MP3.Java

package mp3player;

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

public class MP3 extends Application {

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

    }


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

MP3Controller.java

package mp3player;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;

public class MP3Controller {
    ObservableList<String> songs = FXCollections.observableArrayList("Song 1", "Song 2");
    ListView<String> songsView = new ListView<String>();

    songsView.setItems(songs);
}

mp3player.fxml

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

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<GridPane alignment="center" hgap="10" scaleY="1.0" vgap="10" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mp3player.MP3Controller">
   <columnConstraints>
      <ColumnConstraints />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints maxHeight="200.0" minHeight="171.0" prefHeight="200.0" />
      <RowConstraints maxHeight="29.0" minHeight="0.0" prefHeight="0.0" />
   </rowConstraints>
   <children>
      <VBox prefHeight="200.0" prefWidth="100.0">
         <children>
            <HBox prefHeight="50.0" prefWidth="100.0" />
            <HBox prefHeight="100.0" prefWidth="200.0">
               <children>
                  <ListView fx:id="songsView" prefHeight="67.0" prefWidth="146.0" />
               </children></HBox>
            <HBox prefHeight="47.0" prefWidth="100.0" />
         </children>
      </VBox>
   </children>
</GridPane>

任何帮助将不胜感激。我不确定这里发生了什么,因为我非常密切地关注文档,我怀疑这可能与导入 javafx 有关?如果是这样,您可以尝试在您的机器上运行脚本并查看它是否有效。感谢大家!

标签: javalistviewuser-interfacejavafxfxml

解决方案


尝试在您的代码中尝试在方法或构造函数之外设置值,以说明为什么它不允许您设置值

您可以通过创建构造函数或方法来完成

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;

public class MP3Controller {
    ObservableList<String> songs = FXCollections.observableArrayList("Song 1", "Song 2");
    ListView<String> songsView = new ListView<String>();
    MP3Controller() {
        songsView.setItems(songs);
    }
}

推荐阅读