问题描述
我有一项任务需要合并 2 个以上的单元格,使用以下代码我只能合并 Word 文档下表格标题中的 2 个单元格。
public static class CustomDialog extends Dialog<ButtonType> {
public CustomDialog(Task<?> task) {
DialogPane pane = this.getDialogPane(); {
pane.getButtonTypes().addAll(ButtonType.CANCEL);
//construct custom header
GridPane headerRoot = new GridPane(); {
Label headerText = new Label();
//headerText is the label containing the header text
headerText.textproperty().bind(task.titleproperty());
headerRoot.add(headerText,0);
}
headerRoot.getStyleClass().addAll("header-panel");
pane.setHeader(headerRoot);
pane.setContentText("Placeholder content");
pane.getScene().getwindow().setonCloseRequest(event -> {
if (!task.isDone()) {
event.consume();
}
});
}
}
解决方法
虽然你贴出来的代码没有编译通过,但看起来问题出在这里:
if (j == 0 || j == 2)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Restart };
}
else if (j == 1 || j == 3)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Continue };
}
我假设 j
是列的循环索引。您的代码说在第 0 列开始新的水平合并并继续到第 1 列,然后在第 2 列上重新开始合并并继续到第 3 列。这正是我们在您提供的输出图像中看到的。如果您希望合并所有四个单元格,则第一个单元格应具有 MergedCellValues.Restart
,其他三个单元格应具有 MergedCellValues.Continue
。
我还注意到您正在创建一个全新的 TableCellProperties
来设置 HorizontalMerge
,而不是将它添加到您之前在代码中为相同单元格创建的 TableCellProperties
。因此,这意味着您之前设置的属性(例如 TableCellVerticalAlignment
)对于这些单元格将丢失。
我认为如果你将上面的代码段改为以下,它会解决这两个问题:
if (j < 4)
{
var merge = j == 0 ? MergedCellValues.Restart : MergedCellValues.Continue;
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = merge };
}