JAVA/javafx

[JAVAFX] Scrollpane 에 anchorpane 추가, 삭제 / add anchorpane to scrollpane and remove from scrollpane

자바칩 프라푸치노 2020. 12. 10. 21:20

 

 

 

stackoverflow에서 본건데

버튼을 누르면 scrollpane에 anchorpane이 백그라운드 색상 랜덤으로 계속 생기고

삭제하면 해당 anchorpane이 삭제되는 코드

 

이 코드를 fxml 따로 controller따로 분리해서 추가 되는거 까진 했는데 

해당 anchorpane삭제되는 것은 성공 못했음 ㅠㅠ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
 
import java.util.Random;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class ScrollingVBox extends Application {
 
 
    @Override
    public void start(Stage primaryStage) {
 
        final Random rng = new Random();
        VBox content = new VBox(5);
        ScrollPane scroller = new ScrollPane(content);
        scroller.setFitToWidth(true);
 
        Button addButton = new Button("Add");
        addButton.setOnAction(e -> {
            AnchorPane anchorPane = new AnchorPane();
            String style = String.format("-fx-background: rgb(%d, %d, %d);"+
                    "-fx-background-color: -fx-background;",
                    rng.nextInt(256),
                    rng.nextInt(256),
                    rng.nextInt(256));
            anchorPane.setStyle(style);
            Label label = new Label("Pane "+(content.getChildren().size()+1));
            AnchorPane.setLeftAnchor(label, 5.0);
            AnchorPane.setTopAnchor(label, 5.0);
            
            
            Button button = new Button("Remove");
            button.setOnAction(evt -> content.getChildren().remove(anchorPane));
            AnchorPane.setRightAnchor(button, 5.0);
            AnchorPane.setTopAnchor(button, 5.0);
            AnchorPane.setBottomAnchor(button, 5.0);
            anchorPane.getChildren().addAll(label, button);
            content.getChildren().add(anchorPane);
        });
 
        Scene scene = new Scene(new BorderPane(scroller, nullnull, addButton, null), 400400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}
cs

 

 

 

 

728x90