Reputation: 17
I'm relatively new to JavaFX and I've been pretty confused in why my code below does not produce the intended result being the label added to the grid.
What I'm trying to do is run a test for adding a JavaFX Label to my FXML GridPane as I would like to construct a method in the near-future which will allow the user to choose a file, then generate a label when the user has selected a file and add that Label to the GridPane.
Thanks in advance,
Code:
private Label label1;
@FXML
private GridPane gridPane;
@FXML
public void handle() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select File");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Video Files", "*.mp4", "*.avi"),
new FileChooser.ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new FileChooser.ExtensionFilter("All Files", "*.*"));
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
try {
System.out.println(file.getPath());
System.out.println(file.getName());
label1.setText(file.getName());
gridPane.add(label1, 1, 1);
} catch (Exception e) {
}
}
The FXML Code is a standard file with a defined GridPane with the fx:id listed above.
Upvotes: 0
Views: 2202
Reputation: 209225
You don't initialize your label anywhere, so it is null. Since you're squashing the exception, you don't see the NullPointerException that's generated when you call label1.setText(...)
Upvotes: 1