프라퍼티는 속성을 말한다. 자바FX에서 프라퍼티 클래스를 사용하면 한 클래스의 값이 바뀌었을 때 이와 바인딩 되어 있는 다른 하나의 클래스 값도 바꿀 수 있다.

 

이렇게 말하니 어려운데 바인딩은 우리 일상생활에서 쉽게 볼 수 있다. 반응형 웹을 보면 텍스트나 버튼 등 화면에 배치된 요소의 위치가 항상 중앙에 고정되어 있다. 사이즈를 변경해도 중앙에 정렬이 된다면 화면의 창 사이즈 값이 변할 때 마다 요소의 위치가 변하도록 바인딩 되어 있는 것이다.

 

 

바인딩을 하기 위해 Property 클래스들이 준비되어 있다.

 

아래의 코드는 3의 값을 x에 넣고 y는 x의 변경에 따라 자동으로 업데 되도록 바인드한다. bind 메소드를 사용한다.

 

x값을 바꾸면 y는 자동으로 10배로 바뀐다. 주의할 점은 바인딩은 x에서 y로 했다면 거꾸로 y를 변경하면 오류가 발생한다. bind 메소드는 방향성을 가진다.

        IntegerProperty x = new SimpleIntegerProperty(3);
        IntegerProperty y = new SimpleIntegerProperty();

        y.bind(x.multiply(10));
        System.out.println("x : " + x.getValue());
        System.out.println("y : " + y.getValue() + "\n");

        x.setValue(9);
        System.out.println("x : " + x.getValue());
        System.out.println("y : " + y.getValue() + "\n");

 

* Label 에 바인딩 하기

 

사용자의 입력을 Label 에 바인딩하는 방법도 있다.

 

아래와 같은 GUI 창을 만들고...

 

텍스트를 입력하는 즉시 레이블에 바인딩 된다.

 

 

예제코드는 아래와 같다.

 

비어있는 레이블에 아래 코드를 입력한다.

(코드 한 줄이라지만 체이닝을 한 메서드의 수가 3개니 실제로는 3줄이다.)

 

유저 입력 텍스트 필드의 프라퍼티를 세컨드 레이블의 텍스트 프라퍼티에 바인드 한다는 뜻이다.

        secondLabel.textProperty().bind(userInput.textProperty());

 

*예제 코드

package com;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Scene scene;

    @Override
    public void start(Stage primaryStage) throws Exception{

        window = primaryStage;
        window.setTitle("JavaFX Layout");

        TextField userInput = new TextField();
        userInput.setMaxWidth(200);

        Label firstLabel = new Label("Hello and Welcome! ");
        Label secondLabel = new Label();

        Button bt1 = new Button("submit");

        HBox bottomText = new HBox(firstLabel, secondLabel);
        bottomText.setAlignment(Pos.CENTER);

        VBox layout = new VBox(10, userInput, bottomText, bt1);
        layout.setAlignment(Pos.CENTER);

        secondLabel.textProperty().bind(userInput.textProperty());

        scene = new Scene(layout, 500, 300);
        // CSS 파일 적용
        scene.getStylesheets().add(getClass().getResource("theme.css").toString());
        window.setScene(scene);
        window.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

 

공유하기

facebook twitter kakaoTalk kakaostory naver band