JavaFX TableView填充数组按钮

时间:2018-05-10 12:54:50

标签: button javafx tableview tablecolumn

所以我试图让TableView代表座位行。因此,一行表示“Reihe”类(德语“行”)的对象.Reihe有一系列Sitzplatz(“座位”)。每个座位都有一个按钮,应该显示在座位单元中。 所以我对TableColumns的cellFactories有点困惑。如何告诉列从row.seat [columnIdx]显示座位按钮? 我不能返回一个ObservableValue<按钮>对?那么我作为CellFactories使用的是什么?

Class“Reihe”(= row):

public class Reihe implements DataObject
{
  private Sitzplatz[] seats;

 public Reihe(int seats,int saal)
 {
    this.seats=new Sitzplatz[seats];
    for(int i=0; i<this.seats.length; i++)
    {
        this.seats[i]=new Sitzplatz();
        this.seats[i].setSaal_SID(""+saal);
    }
 }

 public Sitzplatz getSeat(int idx)
 {
    return seats[idx];
 }
    ...

班级“Sitzplatz”(“席位”):

 public class Sitzplatz implements DataObject
 {
  private SimpleStringProperty platz, reihe,saal_SID, reservierung_REID;
  private SeatButton button;

  public Sitzplatz()
  {
    this.platz=new SimpleStringProperty();
    this.saal_SID=new SimpleStringProperty();
    this.reihe=new SimpleStringProperty();
    this.reservierung_REID=new SimpleStringProperty();
    button=new SeatButton();
  }

  public SeatButton getButton()
  {
    return button;
  }
    ...

列的初始化:

   for(int j=0; j<seatColumns; j++)
   {
       TableColumn<Reihe,Button> nColumn=new TableColumn<>("Seat"+j);
       //final int idx=j;
       nColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Reihe, Button>, ObservableValue<Button>>() {

            @Override
            public ObservableValue<Button> call(TableColumn.CellDataFeatures<Reihe, Button> p) {
                    // ???
                }
            });
         nColumn.setMinWidth(50);
         nColumn.setEditable(true);
         //getColumns().add(nColumn);
         getColumns().add(nColumn);
        }

我发现了一些关于使用Button扩展TableCell的内容,但我又无法弄清楚它应该如何工作:

public class SeatButton extends TableCell<Reihe, Button>
{
  Button cellButton;
 //private Sitzplatz seat;

 public SeatButton()
 {
    //seat=row.getSeat(column);
    cellButton=new Button();

    cellButton.setMinWidth(30);
    cellButton.setOnAction(new EventHandler<ActionEvent>(){
        @Override
        public void handle(ActionEvent t) {

            //....
        }
    });
 }
}

1 个答案:

答案 0 :(得分:0)

您不应该在模型中放置GUI元素。在这种情况下,它更没意义,因为SeatButton扩展TableCellTableCell创建独立于项目。另外,itemTableCell分配给TableViewTableCell的项目可能会被更改/删除。

使用cellValueFactory返回给定列的Sitzplatz,并使用返回cellFactory的{​​{1}}:

TableCell<Reihe, Sitzplatz>
for(int j=0; j<seatColumns; j++) {
    final index = j;
    TableColumn<Reihe, Sitzplatz> nColumn = new TableColumn<>("Seat"+j);
    nColumn.setCellValueFactory(p -> new SimpleObjectProperty<>(p.getValue().getSeat(index)));
    nColumn.setCellFactory(c -> new SeatButton<>());
    nColumn.setMinWidth(50);
    nColumn.setEditable(false); // you want to modify items not replace them
    getColumns().add(nColumn);
}
相关问题