我需要让我的用户能够调整JavaFX 8中TableView的列的大小。
以下是代码的简化版本:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class TableViewSample extends Application {
private TableView table = new TableView();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(300);
stage.setHeight(500);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
table.setEditable(true);
TableColumn firstNameCol = new TableColumn("First Name");
TableColumn lastNameCol = new TableColumn("Last Name");
final Button button = new Button("Resize!");
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
System.out.println("Pref Width before resizing: "+firstNameCol.getPrefWidth());
System.out.println("Width before resizing: "+firstNameCol.getWidth());
firstNameCol.setPrefWidth(100);
System.out.println("Pref Width after resizing: "+firstNameCol.getPrefWidth());
System.out.println("Width after resizing: "+firstNameCol.getWidth());
}
});
table.getColumns().addAll(firstNameCol, lastNameCol);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label,button, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
}
如果单击该按钮,则第一列会调整大小。如果手动调整第一列的大小然后单击按钮,则第一列不会调整大小,getWidth和getPrefWidth会返回不同的值!
我理解它是&#34;首选&#34;宽度,但没有&#34; setWidth&#34;方法,只有&#34; getWidth&#34;。
如果我设置了maxWidth和minWidth,则该列不再可调整大小,因此我无法使用这些方法。
有谁知道我可以做些什么来设置列的有效宽度?
答案 0 :(得分:2)
解决方案是设置最小和最大宽度,然后立即将它们设置为“默认”值。
column.setPrefWidth(newWidth);
column.setMinWidth(newWidth);
column.setMaxWidth(newWidth);
column.setMinWidth(0);
column.setMaxWidth(5000);
这样,前三条指令强制调整列的大小并保持正确的宽度;最后两条指令确保列仍可以任何方式调整大小。