簡體   English   中英

為什么編譯器在導入 javafx.scene.control.Label 時顯示錯誤?

[英]Why is compiler showing error while importing javafx.scene.control.Label?

我正在學習 javafx,我正在嘗試創建 label。 But while importing javafx.scene.control.Label , I am getting error: The import javafx.scene.control.Label conflicts with a type defined in the same file

整個代碼是:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;

public class Label extends Application {
    public void start(Stage primaryStage) {
        Label label = new Label("This is a label");
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 600, 400);
        root.getChildren().add(label);
        primaryStage.setScene(scene);
        primaryStage.show();
        
        
    }
    public static void main(String args[]) {
        launch(args);
    }
}

class 的 scope 中的類型名稱需要是唯一的。 您定義了一個新的 class,稱為Label ,同時導入另一個 class,也稱為Label 因此,如果您在代碼中編寫Label ,編譯器不知道使用哪個 class。

您可以重命名您的 class(因此不會沖突)或不導入其他 class。 請注意,即使沒有導入,

javafx.scene.control.Label label = new javafx.scene.control.Label();

會工作,但它很丑陋。

編輯:當您的 class 擴展Application時,您可能希望將其重命名為LabelApp或任何應用程序的名稱

這是因為主線程正在尋找預定義的Label class 參數。 但在這里,它使用用戶定義Label class 獲得啟動方法()。 每當主線程看到 class 名稱時,它就會嘗試通過 Z31A1FD140BE4BEF2D588ZA 搜索 class scope。 首先它將在您的程序中看到,然后在您的 package 中看到。如果沒有找到,則 JVM 遵循委托層次結構原則加載該 class。因此您將得到運行時錯誤。

要運行上述程序,我們還可以提供 Label class 的完整路徑,即
javafx.scene.control.Label label = new javafx.scene.control.Label("This is a label"); .

結論 - 請更改您的 class 名稱,您可以使用上述解決方案,但它會變得混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM