16

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>
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270
  • See [http://stackoverflow.com/q/11033404/682495](http://stackoverflow.com/q/11033404/682495) – Uluk Biy Oct 17 '12 at 12:13
  • Thanks Uluk, that helped! Please post as answer, so I can select it as the correct one :-) Do you have any idea for this strange behaviour? – stefan.at.kotlin Oct 17 '12 at 12:52
  • 2
    This happens because default column width behavior adjust column to widest element in the column. Thus empty space left not used. – Sergey Grinev Oct 17 '12 at 14:25

2 Answers2

40

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.

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
2

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>
DevOpsSauce
  • 1,319
  • 1
  • 20
  • 52