JavaFX TitledPane

JavaFX教程 - JavaFX TitledPane


标题窗格是具有标题的面板,窗格可以打开和关闭。我们可以添加Node(如UI控件或图像)和一组元素到窗格。

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
//from  w w w . j  a v  a 2 s  .  c o m
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 350, 250);
    TitledPane titledPane = new TitledPane("My Title", new CheckBox("OK"));

    HBox hbox = new HBox(10);
    hbox.setPadding(new Insets(20, 0, 0, 20));
    hbox.getChildren().setAll(titledPane);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(hbox);
    stage.setScene(scene);
    stage.show();
  }
}

上面的代码生成以下结果。

null


创建标题窗格

要创建一个TitledPane控件,请调用其构造函数。

以下代码使用TitledPane的双参数构造函数。它将标题窗格命名为“我的窗格",并用一个Button控件填充窗格。

TitledPane tp = new TitledPane("My Pane", new Button("Button"));

接下来的几行做了与上面的代码相同的事情,而没有使用构造函数带参数。 它创建一个带有默认空构造函数的TittedPane并设置标题并进行内容控制。

TitledPane tp = new TitledPane();
tp.setText("My Titled Pane");
tp.setContent(new Button("Button"));

以下代码使用GridPane在TitledPane中布局控件。

TitledPane gridTitlePane = new TitledPane();
GridPane grid = new GridPane();
grid.setVgap(4);
grid.setPadding(new Insets(5, 5, 5, 5));
...
gridTitlePane.setText("Grid");
gridTitlePane.setContent(grid);

我们可以定义标题窗格的打开和关闭方式。默认情况下,所有标题窗格都是可折叠的,打开和关闭操作都是动画。

setCollapsible(false)关闭Collapsible状态。setAnimated(false)停止动画。

TitledPane tp = new TitledPane();
tp.setCollapsible(false);//remove closing action
tp.setAnimated(false);//stop animating

完整的源代码

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/*from   ww w . j a  v a 2s  .  c  o  m*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    TitledPane titledPane = new TitledPane("My Title", new CheckBox("OK"));
    titledPane.setCollapsible(false);//remove closing action
    titledPane.setAnimated(false);//stop animating
    
    HBox hbox = new HBox(10);
    hbox.setPadding(new Insets(20, 0, 0, 20));
    hbox.getChildren().setAll(titledPane);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(hbox);
    stage.setScene(scene);
    stage.show();
  }
}

上面的代码生成以下结果。

null


0.1185s