Skip to content

Instantly share code, notes, and snippets.

@skrb
Created July 4, 2013 11:33
Show Gist options
  • Select an option

  • Save skrb/5926959 to your computer and use it in GitHub Desktop.

Select an option

Save skrb/5926959 to your computer and use it in GitHub Desktop.
package labeldemo;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LabelDemo extends Application {
@Override
public void start(Stage stage) throws IOException {
AnchorPane root = FXMLLoader.load(getClass().getResource("view.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Label Demo");
stage.setScene(scene);
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.shape.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="100.0" prefWidth="400.0" xmlns:fx="http://javafx.com/fxml" fx:controller="labeldemo.ViewController">
<children>
<TextField fx:id="field" onAction="#action" prefWidth="200.0" AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="14.0" AnchorPane.topAnchor="14.0" />
<Pane fx:id="pane" AnchorPane.bottomAnchor="14.0" AnchorPane.leftAnchor="14.0" AnchorPane.topAnchor="60.0">
<children>
<Rectangle fx:id="rect" fill="cadetblue" />
<Label fx:id="label" />
</children>
</Pane>
</children>
</AnchorPane>
package labeldemo;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
public class ViewController implements Initializable {
@FXML
private TextField field;
@FXML
private Pane pane;
@FXML
private Label label;
// pane の大きさが分かるように、paneと同じ大きさの四角形を配置する
@FXML
private Rectangle rect;
@FXML
private void action(ActionEvent event) {
// テキストフィールドに入力した文字をラベルにセットする
label.setText(field.getText());
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// 四角形のサイズをpaneのサイズとバインドさせる
rect.widthProperty().bind(pane.widthProperty());
rect.heightProperty().bind(pane.heightProperty());
// paneの幅をlabelの幅にバインドさせる
// ただし、PaneクラスにはwidthProperty()は定義されていないので、
// 代わりにprefWidthProperty()にバインドする
pane.prefWidthProperty().bind(label.widthProperty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment