coloring only one cell in a tableview

问题: I worked the whole day for this solution. I hope I can find any help. So I have a tableview. when I click a cell I get a context menu by right click. By right click the m...

问题:

I worked the whole day for this solution. I hope I can find any help.

So I have a tableview. when I click a cell I get a context menu by right click. By right click the menu item, a text input dialog opens. I show the text as a tooltip after typing something. I would like to display the tooltip only at the selected cell. The background color should change in red for example. this is supposed to signal that there is a tooltip.

I can show the textinput text as an tooltip but not in the selected cell, unfortunately just in the whole tableview. I cant coloring the cell and I cant display that the cell has an tooltip. I'm using css as well. I hope I could explain it.

public class CreateScheme extends Application {

    // Variablen
    ContextMenu contextMenu = new ContextMenu();
    MenuItem item1 = new MenuItem("Tooltip erstellen");
    private Model model;
    private Pane root;
    TableView<Model> tableview = new TableView<Model>();
    VBox vbox3 = new VBox();
    private Tooltip tooltip = new Tooltip();
    TableCell<Model, String> cell = new TableCell<>();


    @Override
    public void start(Stage secondStage) throws Exception {

        // Scene / root
        root = new Pane(); // Layout -> alle Elmente haben die Position 0/0
        Scene scene = new Scene(root, 800, 600);

        // Variablen erstellen
        VBox vbox = new VBox();
        VBox vbox2 = new VBox();
        HBox hbox = new HBox();
        HBox hbox2 = new HBox();
        HBox hbox3 = new HBox();
        Label label = new Label("Bewertungsschema erstellen: ");
        Button button = new Button("New");
        TextField textField1 = new TextField();
        CheckBox checkbox = new CheckBox();
        Button addButton = new Button("Erstellen");
        Button cancelButton = new Button("Abbrechen");
        Button saveButton = new Button("Speichern");
        Button addTextFieldButton = new Button("+");
        Button bold = new Button("F");
        Button redButton = new Button("Fehler markieren");


        ObservableList<Model> list = FXCollections.observableArrayList();

        model = new Model();
        model.addListener(e -> {
            while (e.next()) {
                if (e.wasAdded()) {
                    int ix = model.size() - 1; // fängt bei Überschrift Table 1 an.
                    for (Model m : list) {
                        if (m.size() <= ix) {
                            m.add("");
                        }
                    }
                    TableColumn<Model, String> column = new TableColumn<Model, String>("Table" + (ix + 1));

                    column.setCellFactory(TextFieldTableCell.<Model>forTableColumn());
                    column.setCellValueFactory(feature -> feature.getValue().get(ix));
                    column.setEditable(true);
                    tableview.getColumns().add(column);

                }
            }
        });

        cell.getStyleClass().add("cellmy");

        tableview.setItems(list);
        tableview.setEditable(true);

        textField1.setVisible(false);
        checkbox.setVisible(false);
        vbox2.setVisible(false);

        hbox.setSpacing(10.0);
        hbox.getChildren().addAll(button, textField1, checkbox);

        vbox.setLayoutX(10.0);
        vbox.setLayoutY(30.0);
        vbox.setSpacing(30.0);
        vbox.setPadding(new Insets(10.0, 20.0, 30.0, 10.0));
        vbox.getChildren().addAll(label, hbox, redButton, bold);

        vbox2.setLayoutX(300.0);
        vbox2.setLayoutY(30.0);
        vbox2.setSpacing(30.0);
        vbox2.setMaxHeight(200.0);
        vbox2.setPadding(new Insets(50.0, 30.0, 30.0, 30.0));
        vbox2.getChildren().add(tableview);

        hbox2.setLayoutX(10.0);
        hbox2.setLayoutY(500.0);
        hbox2.setSpacing(20.0);

        hbox3.setLayoutX(10.0);
        hbox3.setLayoutY(550.0);
        hbox3.setSpacing(20.0);
        hbox3.getChildren().addAll(addButton, cancelButton, saveButton, addTextFieldButton);

        contextMenu.getItems().addAll(item1);

        button.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent e) {
                textField1.setVisible(true);
                checkbox.setVisible(true);
            }
        });

        checkbox.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent e) {
                vbox2.setVisible(true);
                textField1.setEditable(false);
            }
        });

        addTextFieldButton.setOnAction(event -> {
            TextField textfield = new TextField();
            int ix = model.size();
            model.add("");
            textfield.textProperty().bindBidirectional(model.get(ix));
            hbox2.getChildren().add(textfield);
        });

        addButton.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent e) {

                // list.add(new Model());
                tableview.refresh();
            }
        });

        addButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                model.addTo(list);
                model.reset();
            }
        });

        saveButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                FileChooser fileChooser = new FileChooser();

                // Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
                fileChooser.getExtensionFilters().add(extFilter);

                // Show save file dialog
                File file = fileChooser.showSaveDialog(secondStage);

                if (file != null) {
                    saveTextToFile(root, file);
                }
            }
        });

        tableview.setTooltip(tooltip);
        item1.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                showInputTextDialog();


            }
        });

        tableview.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {

            @Override
            public void handle(ContextMenuEvent event) {
                contextMenu.show(tableview, event.getScreenX(), event.getScreenY());

            }
        });

        root.getChildren().addAll(vbox, vbox2, hbox2, hbox3);

        scene.getStylesheets().add("style.css");
        secondStage.setTitle("Bewertungsschema erstellen");
        secondStage.setScene(scene);
        secondStage.show();
    }

    private void showInputTextDialog() {

        TextInputDialog dialog = new TextInputDialog("Tran");

        dialog.setTitle("Bemerkung");
        dialog.setHeaderText("Meine Notiz:");
        dialog.setContentText("Bemerkung:");

        Optional<String> result = dialog.showAndWait();

        result.ifPresent(name -> {
            this.tooltip.setText(name);
        });

        if (result != null) {
            tableview.setStyle("-fx-background-color: red;");
        }
    }


    private void saveTextToFile(Pane pane2, File file) {
        try {
            PrintWriter writer;
            writer = new PrintWriter(file);
            writer.println(pane2);
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(CreateScheme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Pane getPane2() {
        return this.root;
    }

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


public class Model {


    private final ObservableList<SimpleStringProperty> properties = FXCollections.observableArrayList();

    public void addListener(ListChangeListener<? super SimpleStringProperty> listener) {
        properties.addListener(listener);
    }

    public void add(String value) {
        properties.add(new SimpleStringProperty(value));
    }

    public int size() {
        return properties.size();
    }

    public Property<String> get(int ix) {
        return properties.get(ix);
    }

    public void addTo(List<Model> list) {
        Model copy = new Model();
        for (SimpleStringProperty prop : properties) {
            copy.add(prop.getValue());
        }
        list.add(copy);
    }

    public void reset() {
        for (SimpleStringProperty prop : properties) {
            prop.setValue("");
        }
    }
}

tooltip

text input

after text input-tooltip


回答1:

You can set a cell factory to your TableView and set the background color style and Tooltip for each cell individually. But you have to set the selected state in the your cell item.

You can use something like this:

column.setCellFactory(e -> new TableCell<LineItem, String>() {
    @Override
    public void updateItem(Item item, boolean empty) {
        super.updateItem(item, empty);
        setStyle(null);
        setTooltip(null);
        if (item == null || empty) {
            setText(null);
        } else {
            setText(item.getText());
            if (item.isSelected()) {
                setStyle("-fx-background-color: red;");
                setTooltip(new Tooltip("My Tooltip"));
            }
        }
    }
});

You have to set the cell factory to each column of your table.


回答2:

So, i tried some Codes but couldn't really get an solution. this ist what i've tried.

private void showInputTextDialog() {

    TextInputDialog dialog = new TextInputDialog("Tran");

    dialog.setTitle("Bemerkung");
    dialog.setHeaderText("Meine Notiz:");
    dialog.setContentText("Bemerkung:");

    Optional<String> result = dialog.showAndWait();

    result.ifPresent(name -> {
        this.tooltip.setText(name);
    });

    if(result != null) {
        for (TableColumn<Model, ?> column : tableview.getColumns()) {
            addTooltipToColumnCells(column);
        }
    }
}


private <T> void addTooltipToColumnCells(TableColumn<Model,T> column) {

    Callback<TableColumn<Model, T>, TableCell<Model,T>> existingCellFactory 
        = column.getCellFactory();

    column.setCellFactory(c -> {
        TableCell<Model, T> cell = existingCellFactory.call(c);

        Tooltip tooltip = new Tooltip();

        tooltip.textProperty().bind(cell.itemProperty().asString());
        cell.setTooltip(tooltip);
        return cell ;
    });
}

so i can show every table cell text as tooltip, but i want to show the text input dialog text as tooltip, for cells which i selected.

I am really confused how i get this fixed.

  • 发表于 2019-03-29 01:40
  • 阅读 ( 148 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除