6 svar
164 visningar
MC_Javista21 4 – Fd. Medlem
Postad: 27 jan 2021 06:39

Hjälp med felmeddelande, JAVA

1#:-Jag håller för att lösa en övning i JavaFX.

Jag ska göra tre knappar, Update, Add och Delete. Så länge jag har gjort Add- och Delete-knappar. Add fungerar ok. Men när jag trycker på Delete-knapp då får jag fel meddelande 'NullPointerException'. Min kod är bild på två separat filer. En filen som har ’main’ command line metod som kör programmet (UPPGIFT4D_Personhanteraren.java) och den andra filen som anropar som objekt av den första (Person.java). Här kommer det båda två filer i tur ordning och den felmeddelande efter:

1#:-FIL (UPPGIFT4D_Personhanteraren.java):

package application;

import java.util.Arrays;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.stage.Stage;

/**
* @author Carlos 12/19/2020
*
*/
public class UPPGIFT4D_Personhanteraren extends Application {

private final TableView<Person> table = new TableView<>();
private final ObservableList<Person> personManagerList = FXCollections.observableArrayList();

final VBox root = new VBox();

public static void main(String[] args) {
System.out.println("UPPGIFT#4:- JavaFX with Serialition. This program will"
+ "management the people behavior:\n");

Application.launch();

}

//Define the button cell.

@SuppressWarnings("unchecked")

@Override
public void start(Stage stage) {

stage.setTitle("JavaFX GridPane and Table LAYOUT");

/**
* TODO Turn on multi-row selection for the TableView.
*/
TableViewSelectionModel tsm = table.getSelectionModel();
tsm.setSelectionMode(SelectionMode.MULTIPLE);

stage.setWidth(800);
stage.setHeight(800);

table.setEditable(true);

table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setPlaceholder(new Label("No visible columns and/or data exist."));

/**
* § Connection 'GridPane' with 'Table'
*/
GridPane gridPaneTable = this.createGridPane();// § Connection 'GridPane' with 'Table'

root.setSpacing(5);
root.setPadding(new Insets(10, 0, 0, 10));
root.getChildren().addAll(gridPaneTable, table);

root.setSpacing(5);

root.setStyle("-fx-padding: 10; -fx-border-style: solid inside;"
+ "-fx-border-width: 2;"
+ "-fx-border-insets: 5;"
+ "-fx-border-radius: 5;"
+ "-fx-border-color: blue;");

/**
* TO CREATE: Create the Scene.
*/
Scene scene = new Scene(root);

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

table.setEditable(true);

TableColumn<Person, String> firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));

TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));

TableColumn aGeCol = new TableColumn("Age");
aGeCol.setMinWidth(100);
aGeCol.setCellValueFactory(new PropertyValueFactory<>("email"));

table.setItems(personManagerList);

/**
* ADD: Add columns to the TableView.
*/
table.getColumns().addAll(firstNameCol, lastNameCol, aGeCol);

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 addAge = new TextField();
addAge.setMaxWidth(aGeCol.getPrefWidth());
addAge.setPromptText("Age");

stage.setScene(scene);

stage.show();

}

@SuppressWarnings({ "rawtypes", "unchecked" })
public GridPane createGridPane() {

GridPane grid = new GridPane();
grid.setPadding(new Insets(10));
grid.setHgap(10);
grid.setVgap(10);

Text txt = new Text("PERSON MANAGER");
txt.setFont(Font.font("Dialog", FontWeight.BOLD, 12));

grid.add(txt, 0, 0, 1, 1);
grid.add(new Separator(), 0, 1, 3, 1);

grid.add(new Label("First name"), 0, 2, 1, 1);
TextField addFirstName;
grid.add(addFirstName = new TextField(), 1, 2, 1, 1);

grid.add(new Label("Last name"), 0, 3, 1, 1);
TextField addLastName;
grid.add(addLastName = new TextField(), 1, 3, 1, 1);

grid.add(new Label("Age"), 0, 4, 1, 1);
TextField addAge;
grid.add(addAge = new TextField(), 1, 4, 1, 1);

grid.add(new Separator(), 0, 5, 3, 1);

FlowPane fp = new FlowPane(Orientation.HORIZONTAL, 10, 10);
fp.setAlignment(Pos.CENTER_RIGHT);

Button updateButton;
Button addButton;
Button deleteButton;

fp.getChildren().addAll(updateButton = new Button("Update"),
addButton = new Button("Add"),
deleteButton = new Button("Delete"));
grid.add(fp, 0, 6, 3, 1);

/**
* PUT IN ACTION The ' Add' button.
*/
addButton.setOnAction((ActionEvent e) -> {
personManagerList.add(new Person(addFirstName.getText(),
addLastName.getText(),
addAge.getText()));
addFirstName.clear();
addLastName.clear();
addAge.clear();

});

/**
* The first way to delete action.
*/
deleteButton.setOnAction(new EventHandler() {

@Override
public void handle(Event e) {
// TODO Auto-generated method stub
deletePerson(); // ERROR...ERROR...ERROR...ERROR...ERROR...ERROR

}

});

return grid;

}

/**
* DECLARE 'deletePerson' method.
*/
public void deletePerson() {

TableViewSelectionModel<Person> tsm = table.getSelectionModel();//Original shows so 'TableViewSelectionModel tsm ='

// Check, if any rows are selected.
if (tsm.isEmpty()) {

System.out.println("Please select a row to delete.");
return;

}

// Get all selected row indices in an array.
ObservableList<Person> list = tsm.getSelectedItems();

// TODO
System.out.println("\nThe table elemens are: " + tsm.getSelectedItems());

Integer[] selectedIndices = new Integer[list.size()];

// Sort the array
Arrays.sort(selectedIndices);

// Delete rows (last to first)
for(int i = selectedIndices.length - 1; i >= 0; i--) {
//TODO Print out
System.out.println("\nThe table element are: " + selectedIndices[i].intValue());
tsm.clearSelection(selectedIndices[i].intValue());// ERROR...ERROR...ERROR
table.getItems().remove(selectedIndices[i].intValue());

}

}

}

 

2#:-FIL (UPPGIFT4D_Person.java):

package application;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Person {

/**
* SOLUTION to the problem can not retrieve property.
*/
// private final SimpleStringProperty firstName; // SOURCE TO THE PROBLEM.
private StringProperty firstName = new SimpleStringProperty();
public final StringProperty firstNameProperty() {
return firstName;
}

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

public final void SetFirstName(String value) {
firstName.set(value);
}

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 getFirsName() {
return firstName.getName();
}

public void setFirsName(String fName) {
this.firstName.setValue(fName);
}

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

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

public String getEmail() {
return email.get();
}
public void setEmail (String emailA) {
email.set(emailA);
}
}

 

3#:-Fel meddelande:

UPPGIFT#4:- JavaFX with Serialition. This program willmanagement the people behavior:

Please select a row to delete.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at application.UPPGIFT4D_Personhanteraren.deletePerson(UPPGIFT4D_Personhanteraren.java:321)
at application.UPPGIFT4D_Personhanteraren$1.handle(UPPGIFT4D_Personhanteraren.java:219)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8886)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3856)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1851)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2584)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:832)

The table elemens are: [application.Person@2bb27d5]

 

Jag undrar vad denna felmeddelande betyder och varför?

Laguna Online 30472
Postad: 27 jan 2021 08:24

Tydligen sker felet någonstans i deletePerson. Du ser hela kedjan av funktionsanrop från inuti javafx och till din kod. Första raden i utskriften pekar ut deletePerson och dessutom radnumret (321). Radnumren verkar inte stämma med texten här, men du kanske har utelämnat en del kod. Om du tittar i din egen fil bör du se exakt var det händer.

Det som händer är att antingen table eller tsm är en null-pekare. Vad det beror på vet jag inte. Ser koden för add likadan ut?

MC_Javista21 4 – Fd. Medlem
Postad: 28 jan 2021 11:29

Hej Laguna, tack att du svarade. Jag förstår inte riktigt vad du menar med  att -Radnumren verkar inte stämma med texten här, men du kanske har utelämnat en del kod.-

Kod action för ADD knapp kommer ner:

 

/**
* PUT IN ACTION The ' Add' button.
*/
addButton.setOnAction((ActionEvent e) -> {
personManagerList.add(new Person(addFirstName.getText(),
addLastName.getText(),
addAge.getText()));
addFirstName.clear();
addLastName.clear();
addAge.clear();

});

Laguna Online 30472
Postad: 28 jan 2021 11:42

Kunde du identifiera raden det blir fel på? Använder du en sån här tsm nån annanstans? 

MC_Javista21 4 – Fd. Medlem
Postad: 30 jan 2021 15:52

Hej Laguna, 'tsm' är det ett objekt från klassen 'TableViewSelectionModel' för att sätta 'table' objekt MULTIPLE model.

Du kan ser under. Jag skapa den här objekt i början av @Override metod start(Stage stage).

Jag har inte hittat felet än men jag ser att program stannar när den försöker att returnerar index och den stå i null.

Mvh

Julio

 

/**
* TODO Turn on multi-row selection for the TableView.
*/
TableViewSelectionModel tsm = table.getSelectionModel();
tsm.setSelectionMode(SelectionMode.MULTIPLE);

Laguna Online 30472
Postad: 30 jan 2021 16:53

Med identifiera raden menade jag att se vad som står på rad 321.

Det här javafx kan jag inte, men om vi vet om det är table eller tsm som är null så kanske jag kan gissa bättre.

MC_Javista21 4 – Fd. Medlem
Postad: 30 jan 2021 18:50

Hej Laguna, tack så mycket för hjälp. Jag hittade felet. Jag hade anropar fel metod. Rätt metod är:

table.getItems().remove(i);

Hela 'deletePerson()' deklarerade metod ser ut nu slå här:

 

public void deletePerson() {

TableViewSelectionModel<Person> tsm = table.getSelectionModel();

// Check, if any rows are selected.
if (tsm.isEmpty()) {

System.out.println("Please select a row to delete.");
return;

}

// Get all selected row indices in an array.
ObservableList<Person> list = tsm.getSelectedItems();

// TODO
Integer[] selectedIndices = new Integer[list.size()];

// Delete rows (last to first)
for(int i = selectedIndices.length - 1; i >= 0; i--) {

// tsm.clearSelection();
table.getItems().remove(i);

}

Tack en gång till. Du gav mig bra sök spår för att hitta felet.

Mvh

JULIO

Svara
Close