There are two files. ColorVal.java contains the structure to be displayed: one String and 3 integers. It also has the getters and setters needed by JavaFX.
package ex24;
public class ColorVal {
private String color;
private int r;
private int g;
private int b;
public ColorVal(String color, int r, int g, int b){
this.color = color;
this.r = r;
this.g = g;
this.b = b;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public int getG() {
return g;
}
public void setG(int g) {
this.g = g;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
We create the 4 columns and add it to the table object. Finally, we call setItems method with the ObservableList returned from getColor.
package ex24;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class Ex24 extends Application {
TableView table;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Example 24. TableView");
Group root = new Group();
Scene scene = new Scene(root, 500, 500);
TableColumn colorCol = new TableColumn<>("Color");
colorCol.setMinWidth(200);
colorCol.setCellValueFactory(new PropertyValueFactory<>("color"));
TableColumn rCol = new TableColumn<>("R");
rCol.setMinWidth(100);
rCol.setCellValueFactory(new PropertyValueFactory<>("r"));
TableColumn gCol = new TableColumn<>("G");
gCol.setMinWidth(100);
gCol.setCellValueFactory(new PropertyValueFactory<>("g"));
TableColumn bCol = new TableColumn<>("B");
bCol.setMinWidth(100);
bCol.setCellValueFactory(new PropertyValueFactory<>("b"));
table = new TableView<>();
table.setItems(getColor());
table.getColumns().addAll(colorCol, rCol, gCol, bCol);
root.getChildren().addAll(table);
primaryStage.setScene(scene);
primaryStage.show();
}
public ObservableList getColor(){
ObservableList colors = FXCollections.observableArrayList();
colors.add(new ColorVal("Black",0,0,0));
colors.add(new ColorVal("White",255,255,255));
colors.add(new ColorVal("Red",255,0,0));
colors.add(new ColorVal("Lime",0,255,0));
colors.add(new ColorVal("Blue",0,0,255));
colors.add(new ColorVal("Yellow",255,255,0));
colors.add(new ColorVal("Cyan",0,255,255));
colors.add(new ColorVal("Magenta",255,0,255));
return colors;
}
public static void main(String[] args) {
launch(args);
}
}
This is the output:
No comments:
Post a Comment