JavaFX填充了仅从文件的最后一列填充表格

时间:2017-12-19 14:17:40

标签: file javafx tableview scenebuilder

我正在努力在从文件中读取数据后填充表的所有列。仅填充最后一列。我担心这很简单,但看不出错误在哪里。我已阅读了许多其他示例,并观看了几个YouTube视频。我的代码如下:

电话簿课程:

public class PhoneBook {
private SimpleStringProperty lastNm;
private SimpleStringProperty firstNm;
private SimpleStringProperty phoneNum;

public PhoneBook(String last, String first, String num)
{
    lastNm = new SimpleStringProperty(last);
    firstNm = new SimpleStringProperty(first);
    phoneNum = new SimpleStringProperty( "("+num.substring(0, 3)+ ") " +num.substring(3, 6) +
            "-" +num.substring(6));
}

public String getLast()
{
    return lastNm.get();
}

public String getFirst()
{
    return firstNm.get();
}
public String getPhoneNum()
{
    return phoneNum.get();
}

public void setLast(String last)
{
    lastNm = new SimpleStringProperty(last);
}

public void setFirst(String first)
{
    firstNm = new SimpleStringProperty(first);
}
public void setPhoneNum(String num)
{
    phoneNum = new SimpleStringProperty(num);
}

}

控制器代码:

public class ListExampleController  implements Initializable{

@FXML
private TableView<PhoneBook> tblView;
@FXML
private TableColumn<PhoneBook, String> colLastNm;
@FXML
private TableColumn<PhoneBook, String> colFirstNm;
@FXML
private TableColumn<PhoneBook, String> colPhoneNum;

public ArrayList <PhoneBook> book = new ArrayList<>();
public ObservableList <PhoneBook> bookList = FXCollections.observableArrayList(book); 

@Override
public void initialize(URL url, ResourceBundle rb) {
    ArrayList <PhoneBook> book = new ArrayList<>();

    try {
        // Create an Array list of data
        book = readPhoneBk();
    } catch (IOException ex) {
        Logger.getLogger(ListExampleController.class.getName()).log(Level.SEVERE, null, ex);
    }
    ObservableList <PhoneBook> bookList = FXCollections.observableArrayList(book);
    colLastNm.setCellValueFactory(new PropertyValueFactory<PhoneBook, String>("lastNm"));
    colFirstNm.setCellValueFactory(new PropertyValueFactory<PhoneBook, String>("firstNm"));
    colPhoneNum.setCellValueFactory(new PropertyValueFactory<PhoneBook, String>("phoneNum"));

    tblView.setItems(bookList);
}

public ArrayList<PhoneBook> readPhoneBk() throws IOException
{
    // Open the file
    String fileName = "phoneBook.txt";
    File file = new File(fileName);
    ArrayList<PhoneBook> book = new ArrayList();

    try ( // Create a Scanner object for file input
            Scanner inputFile = new Scanner(file)) {
        while (inputFile.hasNext()) {
            String str = inputFile.nextLine();
            // Get the tokens from the string
            String[ ] tokens = str.split("\t") ;

            book.add(new PhoneBook (tokens[0], tokens[1], tokens[2]));
        }
        // Close the file
    }

    return book;
}    

}

0 个答案:

没有答案