TableView has more columns than specified

2020-08-10 07:00发布

When using a TableView in JavaFX 2, there seems to be magically one column added instead of resizing the existing ones. Please see the following screenshot.

What I would expect/want: Both column shall have 50% of space, no third (unnamed/empty) column shall be added.

enter image description here

Created using Scene Builder, FXML code:

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>

<BorderPane id="BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
  <top>
    <TableView prefHeight="200.0" prefWidth="200.0">
      <columns>
        <TableColumn prefWidth="75.0" text="Column X" />
        <TableColumn prefWidth="75.0" text="Column X" />
      </columns>
    </TableView>
  </top>
</BorderPane>

3条回答
在下西门庆
2楼-- · 2020-08-10 07:28

Use

table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

By doing this you ensure that the extra space in table column header will be distributed among the columns. In this distribution the columns' max and min widths are taken into account of course.
By default the TableView.UNCONSTRAINED_RESIZE_POLICY is used where the tablecolumns will take their preferred width initially.

查看更多
时光不老,我们不散
3楼-- · 2020-08-10 07:36

Uluk Bly's answer is absolutely correct for the code.

Additionally, using Scenebuilder, make sure to set the policy in the Properties dropdown window to the same (CONSTRAINED), and it should show up in your FXML file like so:

    <columnResizePolicy>
    <TableView fx:constant = "CONSTRAINED_RESIZE_POLICY"/>
    </columnResizePolicy>
查看更多
爷的心禁止访问
4楼-- · 2020-08-10 07:41

That was good for me in javafx 2.2

table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
查看更多
登录 后发表回答