2013-04-09 41 views
0

我想在窗格中添加兩個不同的標籤和圖像。我使用的代碼是這樣的:JavaFX。添加多個標籤和圖像到窗格

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 


public class Controller extends Application { 


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

    public void start(Stage primaryStage) throws Exception { 

     primaryStage.setTitle("Starting FX"); 
     primaryStage.setScene(new Scene(new Panel(), 590, 390)); 
     primaryStage.setResizable(false); 
     primaryStage.centerOnScreen(); 
     primaryStage.show(); 

    } 

} 



import javafx.scene.control.Label; 
import javafx.scene.image.Image; 
import javafx.scene.image.ImageView; 
import javafx.scene.layout.Pane; 


public class Panel extends Pane { 

    private ImageView image = new ImageView(new Image(getClass().getResourceAsStream("red.jpg"))); 

    private Label label1 = new Label(); 
    private Label label2 = new Label(); 

    public Panel() { 

     label1.relocate(524, 280); 
     label1.setGraphic(image); 
     this.getChildren().add(label1); 

     label2.relocate(250, 200); 
     label2.setGraphic(image); 
     this.getChildren().add(label2); 


    } 



} 

我的問題是,它不會在屏幕上添加兩個標籤。

如果我有:

this.getChildren().add(label1); 
this.getChildren().add(label2); 

它顯示在屏幕上只有標籤2,即使如果我打印(this.getchildren()),它有兩個標籤。

如果我有其中之一,它通常會添加它。

即使我沒有既不和執行

this.getChildren().addAll(label1, label2); 

它仍然只添加標籤2。

這是爲什麼?

謝謝

回答

0

這是因爲ImageView的是一個節點,它不能在場景圖的兩倍。添加第二個ImageView並將其添加到第二個標籤。

private ImageView image1 = new ImageView(new Image(getClass().getResourceAsStream("red.jpg")));

3

兩個標籤實際上是有,但不能同時使用相同的ImageView的場景圖。如果您將文字添加到標籤,您應該看到它們。您必須創建兩個獨立的ImageView實例,每個標籤一個。嘗試這個。

public class Panel extends Pane 
{ 
    Image labelImage = new Image(getClass().getResourceAsStream("red.jpg")); 
    private Label label1 = new Label(); 
    private Label label2 = new Label(); 

    public Panel() 
    { 
     label1.relocate(524, 280); 
     label1.setGraphic(new ImageView(labelImage)); 
     this.getChildren().add(label1); 

     label2.relocate(250, 200); 
     label2.setGraphic(new ImageView(labelImage)); 
     this.getChildren().add(label2); 
    } 
} 

結帳這個職位更多信息 Reusing same ImageView multiple times in the same scene on JavaFX

+0

謝謝兩位非常多。它按預期工作。 – 2013-04-09 13:44:10

+0

如果它是正確的,你能接受答案嗎? – Flavio 2013-09-07 14:02:59