刷新表/树中的单元格

时间:2015-10-29 07:26:23

标签: javafx tree refresh

我正在寻找一种方法来触发TableView或树中单个单元格的刷新。 我知道我可以将属性与TableCell链接并更新此属性,但我不希望以这种方式创建大量属性。我从相反的方向看。 我想在我的表包装器上有方法: tableWrapper.refresh(T rowItem, String attributeNameOfMyItem)。有没有办法实现这个目标? 我可以从特定TreeTableCell这样的地方访问它来调用它的方法updateItem(),然后更新单元格的表示吗? 或者唯一的方法是通过属性TreeTableCell链接并更新属性?


package ks.javafx.table.refresh;

import java.util.HashMap;
import java.util.Map;

import javafx.scene.paint.Color;

public class Validator
{
    private Map person2col = new HashMap();
    private Color[] colors = new Color[] { Color.RED, Color.ORANGE, Color.BLUE, Color.VIOLET, Color.MAGENTA };

    public Validator()
    {
    }

    public void forceValidation(Person person)
    {
        int length = person.getLastName().length();
        Color color = colors[length % colors.length];
        person2col.put(person, color);
    }

    public Color getValidation(Person person)
    {
        return person2col.get(person);
    }
}
package ks.javafx.table.refresh;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import ks.javafx.util.ColorUtil;

public class EditingCell extends TableCell<Person, String>
{
    private Validator validator;
    private TextField textField;

    public EditingCell(Validator validator)
    {
        this.validator = validator;
    }

    @Override
    public void startEdit()
    {
        if(!isEmpty())
        {
            super.startEdit();
            createTextField();
            setText(null);
            setGraphic(textField);
            textField.selectAll();
        }
    }

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

        setText(getItem());
        setGraphic(null);
    }

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

        if(empty)
        {
            setText(null);
            setGraphic(null);
        }
        else
        {
            if(isEditing())
            {
                if(textField != null)
                {
                    textField.setText(getString());
                }
                setText(null);
                setGraphic(textField);
            }
            else
            {
                setText(getString());
                int index = getIndex();
                Person person = getTableView().getItems().get(index);

                Color color = validator.getValidation(person);
                // color = Color.ALICEBLUE;
                if(color != null)
                {
                    String webColor = ColorUtil.toWebString(color);
                    setStyle("-fx-background-color:" + webColor + ";");
                }
                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> arg0, Boolean arg1, Boolean arg2)
            {
                if(!arg2)
                {
                    commitEdit(textField.getText());
                }
            }
        });
    }

    private String getString()
    {
        return getItem() == null ? "" : getItem().toString();
    }
}
package ks.javafx.table.refresh;

import javafx.beans.property.SimpleStringProperty;

public class Person
{
    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private final SimpleStringProperty email;

    public Person(String fName, String lName, String email)
    {
        this.firstName = new SimpleStringProperty(fName);
        this.lastName = new SimpleStringProperty(lName);
        this.email = new SimpleStringProperty(email);
    }

    public String getFirstName()
    {
        return firstName.get();
    }

    public void setFirstName(String fName)
    {
        firstName.set(fName);
    }

    public String getLastName()
    {
        return lastName.get();
    }

    public void setLastName(String fName)
    {
        lastName.set(fName);
    }

    public String getEmail()
    {
        return email.get();
    }

    public void setEmail(String fName)
    {
        email.set(fName);
    }
}
package ks.javafx.table.refresh;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;

public class RefreshTableApp extends Application
{
    private Validator validator = new Validator();

    private TableView<Person> table = new TableView<Person>();
    private static final Person PERSON_A = new Person("Anna", "Rogowska", "anna.rogowska@example.com");
    private final ObservableList<Person> data = FXCollections.observableArrayList(new Person("Jacob", "Smith",
          "jacob.smith@example.com"), new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
          new Person("Ethan", "Williams", "ethan.williams@example.com"), new Person("Emma", "Jones",
                "emma.jones@example.com"), new Person("Michael", "Brown", "michael.brown@example.com"),
          PERSON_A);
    final HBox hb = new HBox();

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

    @Override
    public void start(Stage stage)
    {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);
        Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>()
        {
            @Override
            public TableCell call(TableColumn p)
            {
                return new EditingCell(validator);
            }
        };

        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
        firstNameCol.setCellFactory(cellFactory);
        firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>()
        {
            @Override
            public void handle(CellEditEvent<Person, String> t)
            {
                t.getTableView().getItems().get(t.getTablePosition().getRow()).setFirstName(t.getNewValue());
            }
        });

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
        lastNameCol.setCellFactory(cellFactory);
        lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>()
        {
            @Override
            public void handle(CellEditEvent<Person, String> t)
            {
                t.getTableView().getItems().get(t.getTablePosition().getRow()).setLastName(t.getNewValue());
            }
        });

        TableColumn emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
        emailCol.setCellFactory(cellFactory);
        emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>()
        {
            @Override
            public void handle(CellEditEvent<Person, String> t)
            {
                t.getTableView().getItems().get(t.getTablePosition().getRow()).setEmail(t.getNewValue());
            }
        });

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

        final TextField addFirstName = new TextField();
        addFirstName.setPromptText("First Name");
        addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
        final TextField addLastName = new TextField();
        addLastName.setMaxWidth(lastNameCol.getPrefWidth());
        addLastName.setPromptText("Last Name");
        final TextField addEmail = new TextField();
        addEmail.setMaxWidth(emailCol.getPrefWidth());
        addEmail.setPromptText("Email");

        final Button addButton = new Button("Add");
        addButton.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent e)
            {
                data.add(new Person(addFirstName.getText(), addLastName.getText(), addEmail.getText()));
                addFirstName.clear();
                addLastName.clear();
                addEmail.clear();
            }
        });

        hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
        hb.setSpacing(3);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table, hb, createButtons());

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();

    }

    private Node createButtons()
    {
        Button but = new Button("validate last person");
        but.setOnAction(e -> {
            validator.forceValidation(data.get(data.size() - 1));
        });


        FlowPane pane = new FlowPane(but);
        return pane;
    }

}
package ks.javafx.util;

import javafx.scene.paint.Color;

public final class ColorUtil
{
    /**
     * Translates provided {@link Color} to web string (#RRGGBB).
     * @param aColor
     * @return
     */
    public static String toWebString(final Color aColor)
    {
        final int r = (int) Math.round(aColor.getRed() * 255.0);
        final int g = (int) Math.round(aColor.getGreen() * 255.0);
        final int b = (int) Math.round(aColor.getBlue() * 255.0);
        final String res = String.format("#%02x%02x%02x", r, g, b);
        return res;
    }

}

0 个答案:

没有答案