java - 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 有关?如果是这样,您可以尝试在您的机器上运行脚本并查看它是否有效。感谢大家!
解决方案
尝试在您的代码中尝试在方法或构造函数之外设置值,以说明为什么它不允许您设置值
您可以通过创建构造函数或方法来完成
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);
}
}
推荐阅读
- r - 使用行和向数据框(R)添加新列
- typescript - NestJS Mongo Alias Field Mongo Like Spring Data
- terraform - 使用我的 Vault 服务器验证我的 TF 代码
- excel - 为数据透视表中的数字范围创建自定义组
- xml - 用于识别 XML 文件列表中的重复项的 Powershell 脚本
- firebase - 如何在使用 Firebase 身份验证的应用中加入生物特征身份验证
- javascript - 对象作为 React 子级无效。如果您打算渲染一组孩子,请改用数组 - FlatList
- c# - 使用 HttpClient 测量服务器响应时间
- vue.js - 您好,我正在尝试使用 v-if,但想知道要输入什么才能单击按钮作为真实声明
- javascript - forkJoin 但下一个 observable 取决于之前的那个