Skip to content

Instantly share code, notes, and snippets.

@jewelsea
Created December 9, 2011 05:57
Show Gist options
  • Save jewelsea/1450394 to your computer and use it in GitHub Desktop.
Save jewelsea/1450394 to your computer and use it in GitHub Desktop.
JavaFX Table example which keeps it's columns at a fixed with in proportion to the scene.
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/** Sample data for a table view */
public class LoremIpsum {
final public static ObservableList data = FXCollections.observableArrayList(
new LoremIpsum("Lorem","ipsum","dolor"),
new LoremIpsum("sit","amet,","consectetur"),
new LoremIpsum("adipiscing","elit.","Fusce"),
new LoremIpsum("adipiscing","dui","et"),
new LoremIpsum("tellus","ornare","adipiscing.")
);
final private String a,b,g;
LoremIpsum(String a, String b, String g) {
this.a = a; this.b = b; this.g = g;
}
public String getA() { return a; }
public String getG() { return g; }
public String getB() { return b; }
}
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
/** Table bound to a proportional width */
public class ProportionalTable extends Application {
final static private TableView<LoremIpsum> table = new TableView(LoremIpsum.data);
private Scene scene;
/** Place a table in the scene. */
public void start(final Stage stage) throws Exception {
scene = new Scene(table, 300, 200);
table.getColumns().addAll(makeColumn("alpha"), makeColumn("beta"), makeColumn("gamma"));
stage.setScene(scene);
stage.show();
}
/** Create a table column of LoremIpsum text fixed to 1/3 the size of the scene (less a fraction for padding) */
private TableColumn<LoremIpsum, String> makeColumn(String name) {
TableColumn<LoremIpsum, String> column = new TableColumn<LoremIpsum, String>(name);
column.prefWidthProperty().bind(scene.widthProperty().divide(3).subtract(2.1/3));
column.maxWidthProperty().bind(column.prefWidthProperty());
column.setResizable(false);
column.setCellValueFactory(new PropertyValueFactory<LoremIpsum, String>(name.substring(0, 1)));
return column;
}
public static void main(String[] args) throws Exception { launch(args); }
}
@jewelsea
Copy link
Author

jewelsea commented Dec 9, 2011

@jewelsea
Copy link
Author

Modified LorumIpsum example to use an standard ObservableList rather than wrapping it in FXCollections.unmodifiabledObservaleList as the sorting algorithm on the table requires write access to the list to do the sorting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment