2층 - 앞지름과 되새김의 장/문제의 고찰
JAVA FX - Pane(컨테이너)의 원리의 대한 고찰(FlowPane) (2022-08-15)
상이태상
2022. 8. 15. 21:51
1. 서론
이번엔 FlowPane에 대해 가볍게 알아보자
2. 본론
2-1. FlowPane
씬에 어떠한 오브젝트를 순서대로 나열했을 때, 그 씬의 공간이 부족하면
아래쪽으로 오브젝트를 개행하여 다시 나열해주는 것을 말한다.
그러면 버튼을 6개 생성하고 초기 씬의 크기를 가로 150, 세로 100으로 설정하여 씬을 나타내보자.
코드는 아래와 같다.
package layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneEx1 extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Button button1 = new Button("버튼1");
Button button2 = new Button("버튼2");
Button button3 = new Button("버튼3");
Button button4 = new Button("버튼4");
Button button5 = new Button("버튼5");
Button button6 = new Button("버튼6");
FlowPane flow = new FlowPane();
//어떠한 오브젝트(label, button)를 추가할 땐 getChildren을 써주도록 하자.
flow.getChildren().add(button1);
flow.getChildren().addAll(button2, button3, button4, button5);
flow.getChildren().add(button6);
primaryStage.setScene(new Scene(flow, 150, 100));
primaryStage.setTitle("Button Test");
primaryStage.show();
}
}
버튼 1,2,3이 배치되어 옆이 칸이 부족해 개행되어 4,5,6이 표시되었다.
창을 늘리면?
개행되었던 애들이 일렬로 배치되었다.
현재 작성일이 8월 달이라 더워 죽겠는데 버튼이 붙어 있으니 너무 더워보인다.
저 버튼들에게 퍼스널스페이스를 줄 순 없을까?
그 전에...오브젝트가 5개 정도면 하나하나 정의를 부여할 수 있는데
이게 수십개가 되면....너무 노가다일 뿐더러, 코드가 한 없이 길어진다.
어떻게 안될까?
이럴 때 컬렉션함수인 ArrayList로 해결할 수 있다.
그리고 여기서는 setHgap과 setVgap 오브젝트 들에게 퍼스널스페이스를 주도록 해보자.
코드는 다음과 같다.
package layouts;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneEx2 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FlowPane flow = new FlowPane();
// 참조변수(button)에 담기는 것들은 주소값이므로
// ArrayList를 사용하여 객체를 담을 수 있다.
ArrayList<Button> buttons = new ArrayList<>();
for (int i = 0; i < 15; i++) {
buttons.add(new Button("버튼" + (i+1)));
flow.getChildren().add(buttons.get(i));
}
flow.setHgap(10); //수평(세로)
flow.setVgap(10); //수직(가로)
primaryStage.setScene(new Scene(flow, 250, 200));
primaryStage.setTitle("Button Test");
primaryStage.show();
}
}
결과는 어떻까?
어우... 좀 살 것같다...
마치 출,퇴근길 1호선마냥 따닥따닥 붙어있던 번호들이 일정한 간격으로 떨어져 있고, ArrayList를 통해 오브젝트도 정상적으로 출력된 것을 볼 수 있다.