【问题标题】:How do I use a Map as a TableView ObservableMap object parameter?如何使用 Map 作为 TableView ObservableMap 对象参数?
【发布时间】:2015-11-02 03:50:17
【问题描述】:

我目前正在开发一个应用程序,该应用程序在内部有一个 HashMap,它存储与字符串关联的已创建任务,声明如下:

private Map<String, Task> _tabs = new HashMap<String,Task>();

它在终端中运行良好,但目前我正在为所述应用程序开发一个 javafx GUI,起初,我认为我需要一个 ListView 对象来列出任务,我做了如下:

    @FXML
    private ListView<Task> lstView = new ListView<Task>();
    @FXML
    private CheckBox verified;
    @FXML
    private CheckBox finished;
    @FXML
    private TextField name;
    @FXML
    private TextArea description;
    @FXML
    private Button refresh;
    @FXML 
    private TextField tf;
    @FXML
    private TextField taskName;
    @FXML
    private TextField assignee;
    @FXML
    private TextArea comment;
    @FXML
    private TableColumn taskName;
    @FXML
    private TableColumn taskAuthor;
    @FXML
    private TableColumn taskAssignee;

    
    ScreenController controller;


    @FXML
    public void refreshList() {
    
        lstView.setItems(FXCollections.observableArrayList(shl.mapToArray())); //shl is my Shell object that stores the Map and is inherited by this javaFX controller class.
        lstView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        lstView.setOnMouseClicked(new EventHandler<MouseEvent>() {
            
            @Override
            public void handle(MouseEvent event) {
                System.out.println("clicked on " + lstView.getSelectionModel().getSelectedItem());
                shl.setCurrentTab((Task) lstView.getSelectionModel().getSelectedItem());
                taskName.setText(shl.getCurrentTab().getName());
                description.setText(shl.getCurrentTaskDescription());
                name.setText(shl.getCurrentTab().getAssignee());
                comment.setText(shl.getCurrentTab().getComment());
                
            }
        });
    }

这也有效。但是,请注意我使用了我编写的mapToAray() 方法,它基本上返回一个任务列表。

我这样写是为了让 ListView 显示这样的元素。

任务名称 - AssignedUser

这很好,但现在我还要显示任务的创建者,我不再将 ListView 视为我需要的对象。所以我试图切换到 TableView,但我无法让它工作,接收地图......

@FXML
private TableView<String,Task> taskTable = new TableView<String,Task>();

@FXML
    public void refreshList() {
    
        taskTable.setItems((FXCollections.observableMap(shl.getTabs())); //I know that setItems() requires a ListView object, I just don't  see how to do this without it
        taskTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        taskTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
            
            @Override
            public void handle(MouseEvent event) {
                System.out.println("clicked on " + taskTable.getSelectionModel().getSelectedItem());
                shl.setCurrentTab((Task) taskTable.getSelectionModel().getSelectedItem());
                taskName.setText(shl.getCurrentTab().getName());
                description.setText(shl.getCurrentTaskDescription());
                name.setText(shl.getCurrentTab().getAssignee());
                comment.setText(shl.getCurrentTab().getComment());
                
            }
        });
    }

注意:三个表格列是c1,c2c3

我需要我的表格显示如下内容:

任务名称 |任务作者 |任务分配人

攀岩 | 道恩·约翰逊 | 绿巨人霍根

编辑

我忘了粘贴我的任务类,这里是:

 package main.entities;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NoPermissionException;

public class Task implements Serializable{   
    /**
     * 
     */
    private static final long serialVersionUID = -5416272475989116821L;
    private List<File> _files = new ArrayList<File>();
    private User _assignee;
    private boolean _status = false;
    private Shell _shl;
    private String _name;
    private String _description;
    private String _lastEditDate;
    private User _lastEditor;
    private String comment;
    private String author;
    
    /**
     * @param shl
     * @param name
     * @param description
     * @param assignee
     */
    public Task(Shell shl, String name, String description, String assignee){
        this._shl = shl;
        this._name = name;
        this._description = description;
        this._assignee = shl.findUser(assignee);
        this.author = shl.getCurrentUser().getName();
        shl.addTask(this);
    }
    
    /**
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    public String toString(){
        return _name+" - "+_assignee;
    }
    
    /**
     * @return description string
     */
    public String getDescription(){
        return this._description;
    }
    
    /**
     * @param description
     */
    public void setDescription(String description){
        this._description = description;
    }
    
    /**
     * @param String fileName: name of the file that will be created with the tab saved object locally
     */
    public void save(String fileName){
        try{
            ObjectOutputStream stream =
                new ObjectOutputStream(
                new BufferedOutputStream(
                new FileOutputStream(fileName)));
            
            
            this.setTabName(fileName);
            stream.writeObject(this);
            stream.flush();
            stream.close();
        }catch(IOException ioe){
            ioe.printStackTrace();
        }
    }
    
    /**
     * @param name
     */
    private void setTabName(String name) {
        this.setName(name);
    }

    /**
     * @param file name: String
     * @param userID: String
     */
    public void deleteFile(String fileName, String uID){
        _shl.removeFile(_shl.getFile(fileName));
    }
        
    /**
     * @param fileName
     * @return null
     * @throws IOException
     */
    public File downloadFile(String fileName) throws IOException{
        return null;
        //TODO
        //This method is probably deprecated by javaFX fileChooser
    }   
    
    /**
     * @param trabalhador
     * @throws NoPermissionException
     */
    public void setAssignee(User trabalhador) {
        this._assignee = trabalhador;
    }
    
    /**
     * @param Verification
     * @return boolean status
     */
    public boolean checkStatus(){
        return _status;
    }
    
    /**
     * changes status to opposite
     * @throws NoPermissionException
     */
    public void changeStatus() throws NoPermissionException{
        if (_shl.getCurrentUser() instanceof Manager){
            if (this._status == true)
                this._status = false;
            else this._status = true;
        }
        else throw new NoPermissionException("You need Manager rights to change Status");   
    }
    
    /**
     * @return void;
     */
    public String getAssignee(){
        return this._assignee.getID();
    }
    
    /**
     * @return task name
     */
    public String getName() {
        return _name;
    }
    
    /**
     * @param _name
     */
    public void setName(String _name) {
        this._name = _name;
    }
    
    /**
     * @param f
     */
    public void addFile(File f) {
        this._files.add(f);
    } 
    
    /**
     * @return date of last edition
     */
    public String getLastEditDate() {
        return _lastEditDate;
    }
    
    /**
     * @param _lastEditDate
     */
    public void setLastEditDate(String _lastEditDate) {
        this._lastEditDate = _lastEditDate;
    }
    
    /**
     * @return last editor
     */
    public User getLastEditor() {
        return _lastEditor;
    }
    
    /**
     * @param _lastEditor
     */
    public void setLastEditor(User _lastEditor) {
        this._lastEditor = _lastEditor;
    }

    public File getFile() {
        //TODO
        return null;
        
    }

    public void setComment(String text) {
        this.comment = text;
    }

    public String getComment() {
        return this.comment;
    }
}

【问题讨论】:

标签: java dictionary javafx


【解决方案1】:

您可以通过这种方式将地图用作表格视图:

请提及我在这里使用字符串作为示例数据,而不是任务。

public class MapTableView extends Application {

@Override
public void start(Stage stage) {

    // sample data
    Map<String, String> map = new HashMap<>();
    map.put("one", "One");
    map.put("two", "Two");
    map.put("three", "Three");


    // use fully detailed type for Map.Entry<String, String> 
    TableColumn<Map.Entry<String, String>, String> column1 = new TableColumn<>("Key");
    column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {

        @Override
        public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
            // this callback returns property for just one cell, you can't use a loop here
            // for first column we use key
            return new SimpleStringProperty(p.getValue().getKey());
        }
    });

    TableColumn<Map.Entry<String, String>, String> column2 = new TableColumn<>("Value");
    column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {

        @Override
        public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
            // for second column we use value
            return new SimpleStringProperty(p.getValue().getValue());
        }
    });

    ObservableList<Map.Entry<String, String>> items = FXCollections.observableArrayList(map.entrySet());
    final TableView<Map.Entry<String,String>> table = new TableView<>(items);

    table.getColumns().setAll(column1, column2);

    Scene scene = new Scene(table, 400, 400);
    stage.setScene(scene);
    stage.show();
}

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

【讨论】:

  • 考虑到我最近的编辑,如果您能完成您的回答,我将不胜感激:) @Coder55
  • @Coder55 你可以直接指向this SO link 而不是再次回复代码
猜你喜欢
  • 2013-06-01
  • 2021-07-26
  • 1970-01-01
  • 2022-07-12
  • 2023-01-07
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多