2012-11-20 54 views
2

Im在scrollPane中製作播放列表,但我想在加載新播放列表時更改scrollPane中的內容。 setContent()只是添加內容。如何刪除滾動窗格中的舊內容並插入我的新文本,即。有沒有辦法做一個「scrollpane.removeContent()」?JAVAFX 2.0如何動態更改scrollPane中的內容?

+2

其名稱所暗示的setContent()設置內容不會添加到它。再次檢查你的代碼,你以某種方式再次重新設置舊內容。要刪除內容,只需調用setContent(null)或setContent(new Pane())v.s .. –

+0

非常感謝!我很確定這是setcontent()弄亂了代碼,我忘了重置舊的內容變量。 –

回答

7

烏魯克是對的。

scrollPane.setContent(node)已經完全按照您的要求進行了操作(替換現有內容),並且不需要removeContent方法,因爲setContent(null)將刪除滾動窗格中的所有內容。


這裏是一個示例應用來證明這一點:

import javafx.application.Application; 
import javafx.beans.property.*; 
import javafx.event.*; 
import javafx.scene.Scene; 
import javafx.scene.control.*; 
import javafx.scene.image.*; 
import javafx.scene.layout.*; 
import javafx.stage.Stage; 

public class ScrollPaneReplace extends Application { 
    public static void main(String[] args) { launch(args); } 

    String[] imageLocs = { 
    "http://uhallnyu.files.wordpress.com/2011/11/green-apple.jpg", 
    "http://i.i.com.com/cnwk.1d/i/tim/2011/03/10/orange_iStock_000001331357X_540x405.jpg", 
    "http://smoothiejuicerecipes.com/pear.jpg" 
    }; 
    ImageView[] images = new ImageView[imageLocs.length]; 

    @Override public void init() { 
    for (int i = 0; i < imageLocs.length; i++) { 
     images[i] = new ImageView(new Image(imageLocs[i], 200, 0, true, true)); 
    } 
    } 

    @Override public void start(Stage stage) { 
    stage.setTitle("Healthy Choices"); 
    stage.getIcons().add(new Image("http://files.softicons.com/download/application-icons/pixelophilia-icons-by-omercetin/png/32/apple-green.png")); 

    final ScrollPane scroll = new ScrollPane(); 
    scroll.setPrefSize(100, 100); 

    final IntegerProperty curImageIdx = new SimpleIntegerProperty(0); 
    scroll.setContent(images[curImageIdx.get()]); 

    Button next = new Button("Next Image"); 
    next.setOnAction(new EventHandler<ActionEvent>() { 
     @Override public void handle(ActionEvent t) { 
     curImageIdx.set((curImageIdx.get() + 1) % 3); 
     scroll.setContent(images[curImageIdx.get()]); 
     } 
    }); 

    Button remove = new Button("Remove Image"); 
    remove.setOnAction(new EventHandler<ActionEvent>() { 
     @Override public void handle(ActionEvent t) { 
     scroll.setContent(null); 
     } 
    }); 

    VBox controls = new VBox(10); 
    controls.getChildren().setAll(next, remove); 

    HBox layout = new HBox(10); 
    layout.getChildren().setAll(controls, scroll); 
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;"); 
    HBox.setHgrow(scroll, Priority.ALWAYS); 

    stage.setScene(new Scene(layout)); 
    stage.show(); 

    scroll.setHvalue(0.25); scroll.setVvalue(0.25); 
    } 
} 

樣本圖像用於不同的ScrollPane內容設置:

applechoice orangechoice nochoice

+0

謝謝!這非常有幫助。 –