2017年3月22日 星期三

JavaFX : TableView簡單範例

如何使用TableView 並且新增資料,將在下面做介紹 



寫好FXML檔案 :

main.fxml

main2.fxml

我做了2個FXML檔,第一個是純粹用來顯示TableView而已,第二個是用來新增和刪除資料
當在第一個視窗點選選編輯按鈕時,會跑出第二個編輯視窗讓你可以編輯,當然在編輯視窗新增的資料,第一個視窗也會顯示。

程式碼如下 :

FileChooserSample.java(抓到main.fxml並且顯示出來)

package example;
import java.io.IOException;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
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.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
 
public class FileChooserSample extends Application {
 
   
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws IOException {
     Parent root = FXMLLoader.load(getClass().getResource("/example/main.fxml"));
     
        Scene scene = new Scene(root);
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(550);
        stage.setScene(scene);
        stage.show();
    }
} 

Person.java

package example;

import javafx.beans.property.SimpleStringProperty;

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

    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);
    }
}

mainController.java

package example;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
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.control.cell.TextFieldTableCell;
import javafx.stage.Stage;

public class mainController implements Initializable{
 

 
 @FXML
 private TableView tableview;
 
 @FXML
 private Button btnsend;
 
 static ObservableList 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"));;
 
 

 @Override
 public void initialize(URL arg0, ResourceBundle arg1) {
  // TODO Auto-generated method stub
  
  TableView table = new TableView();
     
  
       tableview.setEditable(true);
       
         TableColumn firstNameCol = new TableColumn("First Name");
         firstNameCol.setMinWidth(100);
         firstNameCol.setCellValueFactory(
             new PropertyValueFactory("firstName"));
         firstNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
         firstNameCol.setOnEditCommit(
             new EventHandler>() {
                 @Override
                 public void handle(CellEditEvent t) {
                     ((Person) t.getTableView().getItems().get(
                             t.getTablePosition().getRow())
                             ).setFirstName(t.getNewValue());
                 }
             }
         );
  
  
         TableColumn lastNameCol = new TableColumn("Last Name");
         lastNameCol.setMinWidth(100);
         lastNameCol.setCellValueFactory(
             new PropertyValueFactory("lastName"));
         lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
         lastNameCol.setOnEditCommit(
             new EventHandler>() {
                 @Override
                 public void handle(CellEditEvent t) {
                     ((Person) t.getTableView().getItems().get(
                         t.getTablePosition().getRow())
                         ).setLastName(t.getNewValue());
                 }
             }
         );
  
         TableColumn emailCol = new TableColumn("Email");
         emailCol.setMinWidth(200);
         emailCol.setCellValueFactory(
             new PropertyValueFactory("email"));
         emailCol.setCellFactory(TextFieldTableCell.forTableColumn());
         emailCol.setOnEditCommit(
             new EventHandler>() {
                 @Override
                 public void handle(CellEditEvent t) {
                     ((Person) t.getTableView().getItems().get(
                         t.getTablePosition().getRow())
                         ).setEmail(t.getNewValue());
                 }
             }
         );
         tableview.setItems(data);
         tableview.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
        
         
         btnsend.setOnAction(new EventHandler() {
             @Override
             public void handle(ActionEvent e) {
              Parent root = null;
              try {
         root = FXMLLoader.load(getClass().getResource("/example/main2.fxml"));
        } catch (Exception e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
        }
              Scene secondscene = new Scene(root);
              Stage secondstage = new Stage();
              secondstage.setScene(secondscene);
              secondstage.show();
             }
         });

 }
  
}


main2Controller.java

package example;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;

public class main2Controller implements Initializable{
 
 @FXML
 private TableView tableview2;
 
 @FXML
 private TextField first,last,email;
 
 @FXML
 private Button btnsendto1,btnclose,btndelete;
 
 @FXML
 private ComboBox combobox;

 @Override
 public void initialize(URL location, ResourceBundle resources) {
  // TODO Auto-generated method stub
  tableview2.setEditable(true);
  
  TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
            new PropertyValueFactory("firstName"));
        firstNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
        firstNameCol.setOnEditCommit(
            new EventHandler>() {
                @Override
                public void handle(CellEditEvent t) {
                    ((Person) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                            ).setFirstName(t.getNewValue());
                }
            }
        );
 
 
        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
            new PropertyValueFactory("lastName"));
        lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
        lastNameCol.setOnEditCommit(
            new EventHandler>() {
                @Override
                public void handle(CellEditEvent t) {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setLastName(t.getNewValue());
                }
            }
        );
 
        TableColumn emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
            new PropertyValueFactory("email"));
        emailCol.setCellFactory(TextFieldTableCell.forTableColumn());
        emailCol.setOnEditCommit(
            new EventHandler>() {
                @Override
                public void handle(CellEditEvent t) {
                    ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setEmail(t.getNewValue());
                }
            }
        );
  
  tableview2.setItems(mainController.data);
  tableview2.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  
  btnsendto1.setOnAction(new EventHandler() {
            @Override
            public void handle(ActionEvent e) {
                mainController.data.add(new Person(
                  first.getText(),
                  last.getText(),
                  email.getText()));
                first.clear();
                last.clear();
                email.clear();
                
            }
        });
  btnclose.setOnAction(new EventHandler() {
            @Override
            public void handle(ActionEvent e) {
             Stage stage = (Stage) btnclose.getScene().getWindow();
             stage.close();
                
            }
        });
  
  combobox.getItems().addAll("1","2","3");
  combobox.setOnAction(event ->{
   switch(combobox.getValue().toString()){
   case "1":
    mainController.data.add(new Person("1","1","1"));
    break;
   case "2":
    mainController.data.add(new Person("2","2","2"));
    break;
   case "3":
    mainController.data.add(new Person("3","3","3"));
    break;
   }
  });
  btndelete.setOnAction(new EventHandler() {
            @Override
            public void handle(ActionEvent e) {
                  Object selectedItem = tableview2.getSelectionModel().getSelectedItem();
                 tableview2.getItems().remove(selectedItem);
                 
            }


   
        });
 }

}

執行結果如下 :



另外下面的combobox也可以做新增的動作喔~

1 則留言: