gpt4 book ai didi

JavaFX ListView setItems() 无法解析符号

转载 作者:行者123 更新时间:2023-12-01 18:22:41 25 4
gpt4 key购买 nike

创建 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);
}
}

关于JavaFX ListView setItems() 无法解析符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60277728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com