In the program I download a picture, check the folder, there it is there. I try to draw it, throws a java.lang.NullPointerException .
I restart the prog, the picture does not download, since there is a check for its existence. I try to draw - everything works.

Does java roughly say "screenshot" of the system at startup, and then does not respond to new files? If so, how to fix it?

 //сначала происходит Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠ° с сайта private void getPictureFromWeatherSite(Forecast forecast){ String fileName = "C:\\Users\\alexandr\\Desktop\\Java\\weather\\src\\main\\java\\pictures\\" + forecast.returnUrlForecastImage(). substring(forecast.returnUrlForecastImage().lastIndexOf("/")); if (!(new File(fileName)).exists()) { new Downloader("http:"+ forecast.returnUrlForecastImage(), fileName); } } //Π·Π°Ρ‚Π΅ΠΌ созданиС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° Π½Π° основС скачанной ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ weatherTable.getColumnModel().getColumn(0).setCellRenderer( new ImageRenderer(data, "pictures" + forecast.returnUrlForecastImage(). substring(forecast.returnUrlForecastImage().lastIndexOf("/")))); 

But the class that deals with rendering

 class ImageRenderer extends DefaultTableCellRenderer { private JLabel lbl = new JLabel(); private Object[][] data; private String picture; ImageRenderer(Object[][] data, String picture){ this.picture = picture; this.data = data; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(row == 1) { ImageIcon icon = new ImageIcon(getClass().getResource(picture)); lbl.setText(""); lbl.setIcon(icon); } else { lbl.setText((String) data[row][column]); lbl.setIcon(null); } return lbl; } } // ΠΊΠΎΠ΄ измСнСния ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ (model - DefaultTableModel) public void changeData(String date){ for(int i=3; i>=0; i--) model.removeRow(i); setData(date); for(int i=0; i<data.length; i++){ model.insertRow(i, data[i]); } weatherTable.setModel(model); Forecast forecast = getCurrentForecast(sinoptik.returnForecasts(), date); weatherTable.getColumnModel().getColumn(0).setCellRenderer( new ImageRenderer(data, "pictures" + forecast.returnUrlForecastImage(). substring(forecast.returnUrlForecastImage().lastIndexOf("/")))); forecast = getCurrentForecast(gismeteo.returnForecasts(), date); weatherTable.getColumnModel().getColumn(1).setCellRenderer( new ImageRenderer(data, "pictures" + forecast.returnUrlForecastImage(). substring(forecast.returnUrlForecastImage().lastIndexOf("/")))); } 
  • Add the download and render code, as well as the error message - Vlad Mamaev
  • How will this help you? I mentioned that when you restart the program, everything works. The error lies in the fact that the compiler does not see the downloaded file. - Vasya Pupkin
  • The compiler does not see the downloaded file? ;) It seems that your program creates an object in which there must be a picture. At the time of launch of the program, this picture is not present, and during operation the state of the object is not updated, therefore NPE. After the restart, the picture is there, so everything is fine. The code in the studio. - Bakhuss
  • Yes, you are completely right! The code has loaded, please tell me how to solve the problem. - Vasya Pupkin
  • ImageRenderer is created before each drawing or when starting the program? When creating this object in the constructor, the String picture is hard-coded, on the basis of which the image is then loaded. ImageIcon icon = new ImageIcon (getClass (). GetResource (picture)); - Bakhuss

1 answer 1

Here is a simple example: clicking a button saves an image to a hard disk, loads an image from a hard disk, displays it in a table.

To test the original data, create a temp folder on drive temp

 import javafx.application.Application; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.stage.Stage; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main extends Application { @Override public void start(Stage primaryStage) { TableColumn<MyImageObject, Image> imageTableColumn = new TableColumn<>("Image"); imageTableColumn.setCellValueFactory(param -> param.getValue().image); imageTableColumn.setCellFactory(param -> new ImageCell()); TableColumn<MyImageObject, String> urlTableColumn = new TableColumn<>("URL"); urlTableColumn.setCellValueFactory(param -> param.getValue().url); TableColumn<MyImageObject, String> filePathTableColumn = new TableColumn<>("File path"); filePathTableColumn.setCellValueFactory(param -> param.getValue().filePath); final TableView<MyImageObject> tableView = new TableView<>(); tableView.getColumns().addAll(imageTableColumn, urlTableColumn, filePathTableColumn); // ΠΏΠΎΠ»Π΅ для указания url исходного изобраТСния final TextField urlTextField = new TextField("https://hsto.org/web/c90/c58/4ad/c90c584ad04e44249bb11d97461ee0e3.png"); // ΠΏΡƒΡ‚ΡŒ Π΄ΠΎ Ρ„Π°ΠΉΠ»Π°, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ это ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ Π½Π°Π΄ΠΎ Π±ΡƒΠ΄Π΅Ρ‚ ΡΠΎΡ…Ρ€Π°Π½ΠΈΡ‚ΡŒ // для тСста Π½Π΅ Π·Π°Π±ΡƒΠ΄ΡŒ ΡΠΎΠ·Π΄Π°Ρ‚ΡŒ ΠΏΠ°ΠΏΠΊΡƒ temp Π½Π° дискС Π‘ final TextField filePathTextField = new TextField("/temp/example.png"); Button addItemButton = new Button("Add item"); addItemButton.setOnAction(event -> { try { tableView.getItems().add(loadMyImageObject(urlTextField.getText(), filePathTextField.getText())); } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }); primaryStage.setScene(new Scene(new BorderPane(tableView, new HBox(10, new Text("URL:"), urlTextField, new Text("File path:"), filePathTextField, addItemButton), null, null, null))); primaryStage.show(); } // ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ нашСго ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ»ΡŒΠ½ΠΎΠ³ΠΎ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° static MyImageObject loadMyImageObject(String url, String filePath) throws IOException { // сохраняСм ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ Π½Π° ТСсткий диск Path path = saveImage(url, filePath); // Π·Π°Π³Ρ€ΡƒΠΆΠ°Π΅ΠΌ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ ΠΈΠ· Ρ„Π°ΠΉΠ»Π° Π½Π° ТСстком дискС Image image = new Image(new FileInputStream(path.toFile())); MyImageObject myImageObject = new MyImageObject(); myImageObject.url = new SimpleStringProperty(url); myImageObject.filePath = new SimpleStringProperty(filePath); myImageObject.image = new SimpleObjectProperty<>(image); return myImageObject; } // сохранСниС изобраТСния ΠΈΠ· url Π² Ρ„Π°ΠΉΠ» static Path saveImage(String url, String filePath) throws IOException { Path path; try(InputStream in = new URL(url).openStream()){ Files.copy(in, path = Paths.get(filePath)); } return path; } // простой ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ для хранСния Π΄Π°Π½Π½Ρ‹Ρ… ΠΈ дальнСйшСго отобраТСния static class MyImageObject { ObjectProperty<Image> image; StringProperty url, filePath; } // ячСйка Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹, ΠΎΡ‚ΠΎΠ±Ρ€Π°ΠΆΠ°ΡŽΡ‰Π°Ρ изобраТСния static class ImageCell extends TableCell<MyImageObject, Image> { private ImageView imageView; public ImageCell() { setContentDisplay(ContentDisplay.GRAPHIC_ONLY); } @Override protected void updateItem(Image item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setGraphic(null); } else { if (imageView == null) { imageView = new ImageView(); } imageView.setImage(item); setGraphic(imageView); } } } } 
  • Everything works, thanks a lot for the help! - Vasya Pupkin
  • In this forum, it is customary to mark the answer as correct if it resolves the issue. Stick to forum ethics. - Alexander Savostyanov
  • Thank you, but I already noted yesterday. "Ratings of participants with a reputation below 15 are not shown." - Vasya Pupkin
  • @VasyaPupkin To the left of the answer, look for a gray check. Click on it to mark the answer as correct. Read: www.stackoverflow.com/help/someone-answers - default locale