好的,我创建了一个表格视图,并且有按钮(ADDROW)。当我按下该按钮时,会打开一个新窗口,我可以在其中 填充这些文本字段,这些文本字段的信息将添加到表格中,但它无法添加该信息。我的所有方法都是正确的,因为我尝试在该方法上打印出一些内容,并且它正确地打印了这些内容。怎么解决?
--这是代码
package javafxtableviewaddrows;
import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.event.ActionEvent; 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.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.paint.Color; import javafx.stage.Stage; import javafx.stage.StageStyle;
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@FXML private TextField filterField;
@FXML private TableView<Customer> tableview;
Button []rbutton=new Button[400];
@FXML public ObservableList<Customer> dataList = FXCollections.observableArrayList();
private void calculation(){
TableColumn id=new TableColumn("ID");
TableColumn name=new TableColumn("NAME");
TableColumn address=new TableColumn("ADDRESS");
TableColumn description=new TableColumn("DESCRIPTION");
TableColumn quantity=new TableColumn("QUANTITY");
TableColumn transiction=new TableColumn("TRANSICTION");
TableColumn payment=new TableColumn("PAYMENT");
TableColumn button=new TableColumn("PREVIEW");
tableview.getColumns().addAll(id,name,address,description,quantity,transiction,payment,button);
for(int i=0;i<rbutton.length;i++){
rbutton[i]=new Button();
}
dataList = FXCollections.observableArrayList(
new Customer("1", "AMIT", "east west", "batman tshirt", "= 1","/NO","NOT COMPLETED",rbutton[0]),
new Customer("2", "AMIT", "east west", "batman tshirt", "= 1","/NO","NOT COMPLETED",rbutton[1]),
new Customer("3", "AMIT", "east west", "batman tshirt", "= 1","/NO","NOT COMPLETED",rbutton[2]),
new Customer("4", "AMIT", "east west", "batman tshirt", "= 1","/NO","NOT COMPLETED",rbutton[3])
);
id.setCellValueFactory(new PropertyValueFactory("id"));
name.setCellValueFactory(new PropertyValueFactory("name"));
address.setCellValueFactory(new PropertyValueFactory("address"));
description.setCellValueFactory(new PropertyValueFactory("description"));
quantity.setCellValueFactory(new PropertyValueFactory("quantity"));
transiction.setCellValueFactory(new PropertyValueFactory("transiction"));
payment.setCellValueFactory(new PropertyValueFactory("payment"));
button.setCellValueFactory(new PropertyValueFactory("button"));
FilteredList<Customer> filteredData = new FilteredList<>(dataList, b -> true);
// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(employee -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}
// Compare first name and last name of every person with filter text.
String lowerCaseFilter = newValue.toLowerCase();
if (employee.getId().toLowerCase().indexOf(lowerCaseFilter) != -1 ) {
return true; // Filter matches first name.
} else if (employee.getName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true; // Filter matches last name.
}
else if (employee.getPayment().toLowerCase().indexOf(lowerCaseFilter) != -1)
return true;
else
return false; // Does not match.
});
});
SortedList<Customer> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tableview.comparatorProperty());
tableview.setItems(sortedData);
}
public void initialize(URL url, ResourceBundle rb) {
calculation();
}
@FXML private void deleteRow(ActionEvent event) throws IOException{
dataList.remove(tableview.getSelectionModel().getSelectedItem());
} @FXML public void addrows(String id, String name, String address, String description, String quantity, String transiction, String payment) { Customer customer = new Customer(id, name, address, description, quantity, transiction, payment,rbutton[4]); dataList.add(customer); Platform.runLater(() -> {
int row = tableview.getItems().size() - 1;
tableview.getSelectionModel().select(row);
tableview.scrollTo(row);
});
} @FXML public void addRow(ActionEvent event) throws IOException{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("dashbord.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root1));stage.show(); }
}
--Customer 类代码
package javafxtableviewaddrows;
import javafx.beans.property.SimpleStringProperty; import javafx.scene.control.Button;
public class Customer { private SimpleStringProperty id; private SimpleStringProperty name; private SimpleStringProperty address; private SimpleStringProperty description; private SimpleStringProperty quantity; private SimpleStringProperty transiction; private SimpleStringProperty payment; private Button button;
public Customer(String id, String name, String address, String description, String quantity, String transiction, String payment, Button button) {
this.id = new SimpleStringProperty(id);
this.name = new SimpleStringProperty(name);
this.address = new SimpleStringProperty(address);
this.description = new SimpleStringProperty(description);
this.quantity = new SimpleStringProperty(quantity);
this.transiction = new SimpleStringProperty(transiction);
this.payment = new SimpleStringProperty(payment);
this.button = button;
this.button.setText("Preview");
}
public String getId() {
return id.get();
}
public String getName() {
return name.get();
}
public String getAddress() {
return address.get();
}
public String getDescription() {
return description.get();
}
public String getQuantity() {
return quantity.get();
}
public String getTransiction() {
return transiction.get();
}
public String getPayment() {
return payment.get();
}
public Button getButton() {
return button;
}
public void setId(String id) {
this.id.set(id);
}
public void setName(String name) {
this.name.set(name);
}
public void setAddress(String address) {
this.address.set(address);
}
public void setDescription(String description) {
this.description.set(description);
}
public void setQuantity(String quantity) {
this.quantity.set(quantity);
}
public void setTransiction(String transiction) {
this.transiction.set(transiction);
}
public void setPayment(String payment) {
this.payment.set(payment);
}
public void setButton(Button button) {
this.button = button;
}
}
--dashboardController代码
package javafxtableviewaddrows;
import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import javafx.stage.Stage;
public class DashbordController implements Initializable {
@FXML
private TextField id;
@FXML
private TextField name;
@FXML
private TextField address;
@FXML
private TextField description;
@FXML
private TextField quantity;
@FXML
private TextField transiction;
@FXML
private TextField payment;
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void addtotable(ActionEvent event) throws IOException {
FXMLLoader loader=new FXMLLoader (getClass().getResource("FXMLDocument.fxml"));
Parent root=loader.load();
FXMLDocumentController nd=loader.getController();
nd.addrows(id.getText(), name.getText(), address.getText(), description.getText(), quantity.getText(), transiction.getText(), payment.getText());
}
}
我期待信息会进入表格视图,它会显示我从另一个阶段输入的信息......
我建议你了解@James_D 和@jewelsea 的提议。我认为这些想法可以带来更好的
JavaFX
编程。如果您目前没有时间研究这些想法,我建议使用 Custom Login Dialog
。
import java.util.Optional;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class App extends Application {
TableView<Person> table = new TableView();
ObservableList<Person> items;
Button btnAddPerson = new Button("Add Person");
public static void main(String[] args) {
App.launch(args);
}
@Override
public void start(Stage stage) {
setupTableView();
setupButton();
HBox root = new HBox( table, btnAddPerson);
root.setPadding(new Insets(5));
stage.setTitle("TableView and ListView");
Scene scene = new Scene(root, 450, 300);
stage.setScene(scene);
stage.show();
}
private void setupTableView()
{
// Create column UserName (Data type of String).
TableColumn<Person, String> idCol = new TableColumn("ID");
TableColumn<Person, String> firstNameCol = new TableColumn("First Name");
TableColumn<Person, String> lastNameCol = new TableColumn("Last Name");
TableColumn<Person, String> emailCol = new TableColumn("Email");
table.getColumns().addAll(idCol, firstNameCol, lastNameCol, emailCol);
// Get value from property of Person. .
idCol.setCellValueFactory(cellData -> cellData.getValue().idProperty().asString());
firstNameCol.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
lastNameCol.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
emailCol.setCellValueFactory(cellData -> cellData.getValue().emailProperty());
// Display row data
items = getUserList();
table.setItems(items);
}
private ObservableList<Person> getUserList() {
Person user1 = new Person(1, "Susan", "smith", "[email protected]");
Person user2 = new Person(2, "Anne", "mcneil", "[email protected]");
Person user3 = new Person(3, "Kenvin", "white", "[email protected]");
return FXCollections.observableArrayList(user1, user2, user3);
}
private void setupButton()
{
btnAddPerson.setOnAction((actionEvent) -> {
showCustomDialog();
});
}
private void showCustomDialog()
{
// Create the custom dialog.
Dialog<Person> dialog = new Dialog<>();
dialog.setTitle("Add Person Dialog");
dialog.setHeaderText("Add Person");
// Set the icon (must be included in the project).
//dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType btntAdd = new ButtonType("Add", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(btntAdd, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField tfId = new TextField();
TextField tfFirstName = new TextField();
TextField tfLastName = new TextField();
TextField tfEmail = new TextField();
grid.add(new Label("ID:"), 0, 0);
grid.add(tfId, 1, 0);
grid.add(new Label("First Name:"), 0, 1);
grid.add(tfFirstName, 1, 1);
grid.add(new Label("Last Name:"), 0, 2);
grid.add(tfLastName, 1, 2);
grid.add(new Label("Email Name:"), 0, 3);
grid.add(tfEmail, 1, 3);
// Enable/Disable login button depending on whether a username was entered.
Button btnAdd = (Button)dialog.getDialogPane().lookupButton(btntAdd);
btnAdd.disableProperty().bind(
Bindings.isEmpty(tfId.textProperty())
.or(Bindings.isEmpty(tfFirstName.textProperty()))
.or(Bindings.isEmpty(tfLastName.textProperty()))
.or(Bindings.isEmpty(tfEmail.textProperty()))
);
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> tfId.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == btntAdd) {
return new Person(Integer.parseInt(tfId.getText()), tfFirstName.getText(), tfLastName.getText(), tfEmail.getText());
}
return null;
});
Optional<Person> result = dialog.showAndWait();
result.ifPresent(items::add);
}
}
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final IntegerProperty id;
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty email;
public Person(int id, String fName, String lName, String email) {
this.id = new SimpleIntegerProperty(id);
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public int getId()
{
return id.get();
}
public void setId(int id)
{
this.id.set(id);
}
public IntegerProperty idProperty()
{
return id;
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public StringProperty firstNameProperty()
{
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public StringProperty lastNameProperty()
{
return lastName;
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
public StringProperty emailProperty()
{
return email;
}
@Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("id: ").append(this.id.get())
.append("\tName:").append(this.firstName.get()).append(" ").append(this.lastName.get())
.append("\temail: ").append(this.email.get());
return stringBuilder.toString();
}
}