JavaFX ListView setItems()无法解析符号

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

正在创建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有关?如果是这样,您可以尝试在计算机中运行脚本并查看其是否有效。谢谢大家!

java listview user-interface javafx fxml
1个回答
0
投票

尝试以下在您的代码中,您尝试在方法或构造函数之外设置值,这就是为什么它不允许您设置值的原因

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

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.