我有一个TreeItem<String>对象.

我想在其中放一个按钮.
Button button = new Button("Hello!");
root.setGraphic(button); // root is the TreeItem object
Run Code Online (Sandbox Code Playgroud)

还不错,但我想自由定位这个按钮.我想要"Root"的权利.
更改按钮的布局X似乎没有做任何事情.那怎么办呢?
您可以使用Label和Button初始化创建自定义类扩展HBox类并包含构造函数声明.接下来,您可以使用此类来指定TreeView<T>和TreeItem<T>泛型类型.这种简单的HBox自定义类的示例如下所示:
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
public class CustomItem extends HBox {
private Label boxText;
private Button boxButton;
CustomItem(Label txt) {
super();
this.boxText = txt;
this.getChildren().add(boxText);
this.setAlignment(Pos.CENTER_LEFT);
}
CustomItem(Label txt, Button bt) {
super(5);
this.boxText = txt;
this.boxButton = bt;
this.getChildren().addAll(boxText, boxButton);
this.setAlignment(Pos.CENTER_LEFT);
}
}
Run Code Online (Sandbox Code Playgroud)
在实践中使用它可能如下所示:
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TreeViewDemo extends Application {
public Parent createContent() {
/* layout */
BorderPane layout = new BorderPane();
/* layout -> center */
/* initialize TreeView<CustomItem> object */
TreeView<CustomItem> tree = new TreeView<CustomItem>();
/* initialize tree root item */
TreeItem<CustomItem> root = new TreeItem<CustomItem>(new CustomItem(new Label("Root")));
/* initialize TreeItem<CustomItem> as container for CustomItem object */
TreeItem<CustomItem> node = new TreeItem<CustomItem>(new CustomItem(new Label("Node 1"), new Button("Button 1")));
/* add node to root */
root.getChildren().add(node);
/* set tree root */
tree.setRoot(root);
/* add items to the layout */
layout.setCenter(tree);
return layout;
}
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.setWidth(200);
stage.setHeight(200);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
效果将如下所示:

| 归档时间: |
|
| 查看次数: |
3989 次 |
| 最近记录: |