我有一个TreeItem<String>
对象。
我想在其中放置一个按钮。
Button button = new Button("Hello!");
root.setGraphic(button); // root is the TreeItem object
还不错,但我想自由地定位这个按钮。我想把它放在“根”右边。
更改按钮的布局X似乎没有任何作用。那么我该怎么办呢?
我有一个TreeItem<String>
对象。
我想在其中放置一个按钮。
Button button = new Button("Hello!");
root.setGraphic(button); // root is the TreeItem object
还不错,但我想自由地定位这个按钮。我想把它放在“根”右边。
更改按钮的布局X似乎没有任何作用。那么我该怎么办呢?
你可以创建一个继承自 HBox 类的自定义类,并包含带有 Label 和 Button 初始化的构造函数声明。然后,你可以使用这个类来指定 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);
}
}
实际应用中,其使用方法如下所示:
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);
}
}
快速的方法是不设置树形项的valueProperty
,并将所需的值作为文本(或标签)添加到graphicProperty
中。
root.setValue("");
Text text = new Text("Root");
Button button = new Button("Hello!");
HBox hbox = new HBox(5);
hbox.getChildren().addAll(text, button);
root.setGraphic(vbox);
另一种长远的方法是查找树形项目的子节点,并相应地更改其属性。
编辑说明:嗯,使用HBox而不是VBox会更合适。我当时很匆忙 :)
HBox
作为节点(然后在HBox
中放置一个按钮和一个标签,标签上显示"Root"的文本)。 - Michael Berry