JavaFX中TableView中的一列多个组件(Multiple Components in on

2019-07-05 02:58发布

我使用JavaFX 2.2的工作。 我有,我不能够把不同的组件在TableView中列有问题。 例如,我有两列

1)答案

2)AnswerType

如果AnswerType包含“选择题”,然后在回答栏相应的电池应该显示的ComboBox否则它应该显示文本字段。

我具有低于码的例子,但其在同一列的不同细胞中显示任一组合框或文本字段而不是两者。

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.control.cell.ComboBoxTableCell;

public class TableCellWithMultipleComponent extends Application {

     @SuppressWarnings("rawtypes")
TableColumn answerTypeCol; 
@SuppressWarnings("rawtypes")
TableColumn answerCol; 
ObservableList<String> namesChoiceList;

public static void main(String[] args) {
    launch(args);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void start(final Stage primaryStage) {
    primaryStage.setTitle("Table Cell With Multiple Components");

     TableView<Person> table = new TableView<Person>();
     table.setEditable(true);
      final ObservableList<Person> data = 
                FXCollections.observableArrayList(
                    new Person("A", "Multiple Choice"),
                    new Person("JOHN", "Free Text"),
                    new Person("123", "Free Text"),
                    new Person("D", "Multiple Choice")
                );

    GridPane gridpane = new GridPane();
    gridpane.setPadding(new Insets(5));
    gridpane.setHgap(5);
    gridpane.setVgap(5);


    namesChoiceList = FXCollections.observableArrayList("A", "B", "C", "D", "INVALID_ANSWER", "NO_ANSWER");

    answerCol = new TableColumn();
    answerCol.setText("Answers");
    answerCol.setMinWidth(210);
    answerCol.setEditable(true);
    answerCol.setCellValueFactory(new PropertyValueFactory("answers"));


    answerCol.setCellFactory( new Callback<TableColumn<String, String>, TableCell<String, String>>() {
        @Override
        public TableCell<String, String> call(TableColumn<String, String> arg0) {
            return new anyMethod();
        }
    });



    answerTypeCol = new TableColumn();
    answerTypeCol.setText("Answers Type");
    answerTypeCol.setMinWidth(210);
    answerTypeCol.setEditable(true);
    answerTypeCol.setCellValueFactory(new PropertyValueFactory("answersType"));



    table.setItems(data);
    table.getColumns().addAll(answerCol, answerTypeCol);

    StackPane root = new StackPane();

    Scene scene =new Scene(root, 500, 550);

    gridpane.add(table, 1, 5,1,20 );


    root.getChildren().addAll(gridpane);
    primaryStage.setScene(scene);
    primaryStage.show();

   }


  private class anyMethod extends TableCell <String, String>{


    @SuppressWarnings("unchecked")
    @Override
    protected void updateItem(String item, boolean arg1) {
        super.updateItem(item, arg1);

        answerCol.setCellFactory(ComboBoxTableCell.<String, String>forTableColumn(namesChoiceList));

        /****  I have to execute this commented code so that if the column cell has text "Multiple Choice" then
         * it displays the comboBox otherwise it displays the text field in the Table View cell

        if (item.equalsIgnoreCase("Multiple Choice")){
            answerCol.setCellFactory(ComboBoxTableCell.<String, String>forTableColumn(namesChoiceList));
        }
        else{
            //answerCol.setCellFactory(TextFieldTableCell.<String>forTableColumn());
        }
    ****/
    }

}


public static class Person {
    private final SimpleStringProperty answers;
    private final SimpleStringProperty answersType;


    private Person(String answers, String answersType) {
        this.answers = new SimpleStringProperty(answers);
        this.answersType = new SimpleStringProperty(answersType);
    }

    public String getAnswers() {
        return answers.get();
    }
    public void setAnswers(String answers) {
        this.answers.set(answers);
    }

    public String getAnswersType() {
        return answersType.get();
    }
    public void setAnswersType(String answersType) {
        this.answersType.set(answersType);
    }
   }



}

Answer 1:

下面是一个EditingCell样品这使得根据由所述细胞的支持字段(字符串或布尔值)所表示的数据的类型在所述细胞中不同的控制(文本编辑字段或复选框)。 完整的可执行代码可以作为一个依据 。

为特定的例子中,使用相同的概念,除了查询是一个字符串=>的TextField或ObservableList =>组合框的类型。 此外,为您的特定样品,ChoiceBox可能是一个简单的控制比组合框使用。

class EditingCell extends TableCell<NamedProperty, Object> {
private TextField textField;
private CheckBox checkBox;
public EditingCell() {}

@Override public void startEdit() {
  if (!isEmpty()) {
    super.startEdit();

    if (getItem() instanceof Boolean) {
      createCheckBox();
      setText(null);
      setGraphic(checkBox);
    } else {
      createTextField();
      setText(null);
      setGraphic(textField);
      textField.selectAll();
    }  
  }
}

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

  if (getItem() instanceof Boolean) {
    setText(getItem().toString());
  } else {
    setText((String) getItem());
  }  
  setGraphic(null);
}

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

  if (empty) {
    setText(null);
    setGraphic(null);
  } else {
    if (isEditing()) {
      if (getItem() instanceof Boolean) {
        if (checkBox != null) {
          checkBox.setSelected(getBoolean());
        }
        setText(null);
        setGraphic(checkBox);
      } else {
        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> observable, Boolean oldValue, Boolean newValue) {
      if (!newValue) {
        commitEdit(textField.getText());
      }
    }
  });
}

private void createCheckBox() {
  checkBox = new CheckBox();
  checkBox.setSelected(getBoolean());
  checkBox.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
  checkBox.focusedProperty().addListener(new ChangeListener<Boolean>() {
    @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
      if (!newValue) {
        commitEdit(checkBox.isSelected());
      }
    }
  });
}

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

private Boolean getBoolean() {
  return getItem() == null ? false : (Boolean) getItem();
}
}  


Answer 2:

贝娄是我的问题的工作代码。 谢谢jewelsea

    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.TextField;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;

    public class TableCellWithMultipleComponent extends Application {
        @SuppressWarnings("rawtypes")
        TableColumn answerTypeCol; 
        @SuppressWarnings("rawtypes")
        TableColumn answerCol; 
        ObservableList<String> namesChoiceList;
        @SuppressWarnings("rawtypes")
        ComboBox comboBox;
        TextField textField;

        public static void main(String[] args) {
            launch(args);
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public void start(final Stage primaryStage) {
            primaryStage.setTitle("Table Cell With Multiple Components");

             TableView<Person> table = new TableView<Person>();
             table.setEditable(true);
              final ObservableList<Person> data = 
                        FXCollections.observableArrayList(
                            new Person("A", "Multiple Choice"),
                            new Person("JOHN", "Free Text"),
                            new Person("123", "Free Text"),
                            new Person("D", "Multiple Choice")
                        );



            GridPane gridpane = new GridPane();
            gridpane.setPadding(new Insets(5));
            gridpane.setHgap(5);
            gridpane.setVgap(5);


            namesChoiceList = FXCollections.observableArrayList("A", "B", "C", "D", "INVALID_ANSWER", "NO_ANSWER");

            answerCol = new TableColumn();
            answerCol.setText("Answers");
            answerCol.setMinWidth(210);
            answerCol.setEditable(true);
            answerCol.setCellValueFactory(new PropertyValueFactory("answers"));


            answerCol.setCellFactory( new Callback<TableColumn<String, String>, TableCell<String, String>>() {
                @Override
                public TableCell<String, String> call(TableColumn<String, String> arg0) {
                    return new anyMethod();
                }
            });



            answerTypeCol = new TableColumn();
            answerTypeCol.setText("Answers Type");
            answerTypeCol.setMinWidth(210);
            answerTypeCol.setEditable(true);
            answerTypeCol.setCellValueFactory(new PropertyValueFactory("answersType"));



            table.setItems(data);
            table.getColumns().addAll(answerCol, answerTypeCol);

            StackPane root = new StackPane();

            Scene scene =new Scene(root, 500, 550);

            gridpane.add(table, 1, 5,1,20 );


            root.getChildren().addAll(gridpane);
            primaryStage.setScene(scene);
            primaryStage.show();


       }


        private class anyMethod extends TableCell <String, String>{

            @SuppressWarnings({ "unchecked", "rawtypes" })
            public anyMethod(){

                comboBox = new ComboBox();
                textField = new TextField();
                comboBox.setItems(namesChoiceList);
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                     if (empty) {
                    setText(null);
                   setGraphic(null);
                    System.out.println("In empty");
                 } else {
                    if( getTableView().getColumns().get(1).getCellData(getIndex()).toString().startsWith("M")){

                     System.out.println("Making ComboBox");
                     setGraphic(comboBox);
                    }
                    else{
                        setGraphic(textField);
                    }
                 }

            }

        }


        public static class Person {
            private final SimpleStringProperty answers;
            private final SimpleStringProperty answersType;


            private Person(String answers, String answersType) {
                this.answers = new SimpleStringProperty(answers);
                this.answersType = new SimpleStringProperty(answersType);
            }

            public String getAnswers() {
                return answers.get();
            }
            public void setAnswers(String answers) {
                this.answers.set(answers);
            }

            public String getAnswersType() {
                return answersType.get();
            }
            public void setAnswersType(String answersType) {
                this.answersType.set(answersType);
            }
        }



    }


文章来源: Multiple Components in one column of JavaFX TableView