Resize JavaFX table


Question

I have this simple example of a table.

   import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;


public class MainApp extends Application
{

    private TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data
        = FXCollections.observableArrayList(
            new Person("Processor", "72"),
            new Person("RAM", "78"),
            new Person("HDD Free Space", "890"),
            new Person("Lan Adapter NIC 1", "36"),
            new Person("Lan Adapter NIC 2", "67"));

    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(850);
        //stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(false);
        Callback<TableColumn, TableCell> cellFactory
            = new Callback<TableColumn, TableCell>()
            {
                @Override
                public TableCell call(TableColumn p)
                {
                    return new EditingCell();
                }
            };

        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn firstNameCol = new TableColumn("Credentials");
        //firstNameCol.setPrefWidth(300);
        firstNameCol.setMinWidth(50);
        //firstNameCol.prefWidthProperty().bind(table.widthProperty().divide(2)); // w * 1/2

        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
        firstNameCol.setCellFactory(cellFactory);
        firstNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>()
            {
                @Override
                public void handle(CellEditEvent<Person, String> t)
                {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setFirstName(t.getNewValue());
                }
            }
        );

        TableColumn lastNameCol = new TableColumn("Value");
        //lastNameCol.setPrefWidth(300);
        lastNameCol.setMinWidth(50);
        //lastNameCol.prefWidthProperty().bind(table.widthProperty().divide(2));  // w * 1/2

        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
        lastNameCol.setCellFactory(cellFactory);
        lastNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>()
            {
                @Override
                public void handle(CellEditEvent<Person, String> t)
                {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setLastName(t.getNewValue());
                }
            }
        );

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        final VBox vbox = new VBox();
        VBox.setVgrow(table, Priority.ALWAYS);
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person
    {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName)
        {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName()
        {
            return firstName.get();
        }

        public void setFirstName(String fName)
        {
            firstName.set(fName);
        }

        public String getLastName()
        {
            return lastName.get();
        }

        public void setLastName(String fName)
        {
            lastName.set(fName);
        }

    }

    class EditingCell extends TableCell<Person, String>
    {

        private TextField textField;

        public EditingCell()
        {
        }

        @Override
        public void startEdit()
        {
            if (!isEmpty())
            {
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();
            }
        }

        @Override
        public void cancelEdit()
        {
            super.cancelEdit();

            setText((String) getItem());
            setGraphic(null);
        }

        @Override
        public void updateItem(String item, boolean empty)
        {
            super.updateItem(item, empty);

            if (empty)
            {
                setText(null);
                setGraphic(null);
            }
            else
            {
                if (isEditing())
                {
                    if (textField != null)
                    {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                }
                else
                {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }

        private void createTextField()
        {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.focusedProperty().addListener(new ChangeListener<Boolean>()
            {
                @Override
                public void changed(ObservableValue<? extends Boolean> arg0,
                    Boolean arg1, Boolean arg2)
                {
                    if (!arg2)
                    {
                        commitEdit(textField.getText());
                    }
                }
            });
        }

        private String getString()
        {
            return getItem() == null ? "" : getItem().toString();
        }
    }
}

I want resize the table and fit the main stage when I resize the window. How I can do this?

P.S I tested to add table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); but nothing is changed.

1
4
12/27/2013 9:34:35 AM

Accepted Answer

use vbox as root for scene and set vgrow constraint for table to always.

Sample Code :

Scene scene = new Scene(vbox);
vbox.setVgrow(table, Priority.ALWAYS);
9
12/27/2013 2:10:10 AM

If you are using Scenebuilder, then you can easily anchor the anchorpane (where your tableview is residing) to the sides. Or you can set it programatically in the controller.

Select the sides whichever direction you want the table to grow.

AnchorPane.setTopAnchor(<anchorpane>,0.0);
AnchorPane.setBottomAnchor(<anchorpane>,0.0);
AnchorPane.setLeftAnchor(<anchorpane>,0.0);
AnchorPane.setRightAnchor(<anchorpane>,0.0);

ColumnResizePolicy will only resize the tablecolumn according to your tableview size.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon