java fx can't image doesn't show - image

i have a problem with displaying images in java fx.I want to simply display image which i get from string path.My image in this case images.jpg is in src folder of the project.
so far i got code like this:
FXML FILE:
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com /javafx/8">
<children>
<ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" />
</children>
</AnchorPane>
CONTROLLER CLASS:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class MainPaneController implements Initializable {
#FXML
private ImageView imageView;
private Image image;
String path;
#Override
public void initialize(URL location, ResourceBundle resources) {
String path = "indeks.jpg";
imageView = new ImageView();
image = new Image(path);
imageView.setImage(image);
}
public ImageView getImageView() {
return imageView;
}
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
}
MAIN CLASS:
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Parent parent = (Parent) FXMLLoader.load(getClass().getResource(
"/pl/gallery/view/MainPane.fxml"));
Scene scene = new Scene(parent);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I have no idea what i'm doing wrong here.

Related

JavaFX Image and ImageViewer not supporting jpeg

I created an fxml file with an ImageView on an AnchorPane using SceneBuilder and through controller class I set the image with the code somewhat like...
#FXML ImageView;
...
void func(File file) {
Image image = new Image(file.toURI().toString());
ImageView.setImage(image);
}
But the thing is whenever the file is a jpeg it doesn't show. Though it works completely fine with png. I looked up the openjfx doc for Image. It says that jpeg's are supported. What's the catch here?
FXML code (test.fxml):
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="1080.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="client.Testctrl">
<children>
<ImageView fx:id="imageView" fitHeight="1080.0" fitWidth="1440.0" pickOnBounds="true" preserveRatio="true" />
</children>
</AnchorPane>
Controller Class code (Testctrl.java):
package client;
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.io.File;
public class Testctrl {
#FXML ImageView imageView;
private Main main;
public void setMain(Main main) {
this.main = main;
}
public void load() {
File file = new File("image.jpg");
Image image = new Image(file.toURI().toString());
imageView.setImage(image);
imageView.setFitHeight(1080);
imageView.setPreserveRatio(true);
}
}
Main Class code (Main.java):
package client;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main extends Application {
private Testctrl testctrl;
private Stage stage;
#Override
public void start(Stage primaryStage) throws Exception{
stage = primaryStage;
stage.setFullScreen(true);
stage.setResizable(false);
showTest();
}
public void showTest(){
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("test.fxml"));
Parent root=null;
try {
root = loader.load();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
testctrl = loader.getController();
testctrl.setMain(this);
testctrl.load();
stage.setScene(new Scene(root, 1920, 1080));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Dependency injection with JavaFX gives NullPointerExceptions

I want to mix Java FX and Spring Data. I found video about this problem https://www.youtube.com/watch?v=u0dEf-QN-90&t=3s and I implemented it in my code. In consequence my UI working but I couldn't inject dependency to TaskRepository. I had been trying in difrent ways to inject anything and always I get same error, that my dependency is null. What am I doing wrong?
addingWindow.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pl.projektyjava.listToDoJavaFX.fxmlcontrollers.AddingWindowController">
<children>
<VBox prefHeight="400.0" prefWidth="473.0" HBox.hgrow="ALWAYS">
<children>
<Label alignment="TOP_CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Tytuł" textAlignment="CENTER" />
<TextField fx:id="title" VBox.vgrow="ALWAYS" />
<Label alignment="TOP_CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Opis" textAlignment="CENTER" />
<TextArea fx:id="description" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="200.0" prefWidth="200.0" VBox.vgrow="ALWAYS" />
<HBox maxHeight="-Infinity" VBox.vgrow="ALWAYS">
<children>
<Button fx:id="listOfQuest" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Lista Zadań" HBox.hgrow="ALWAYS" />
<Button fx:id="addQuest" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Dodaj zadanie" HBox.hgrow="ALWAYS" />
</children>
</HBox>
</children>
</VBox>
<Slider fx:id="priority" blockIncrement="1.0" majorTickUnit="1.0" max="5.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minorTickCount="0" orientation="VERTICAL" showTickLabels="true" showTickMarks="true" snapToTicks="true" HBox.hgrow="ALWAYS" />
</children>
</HBox>
pl.projektyjava.listToDoJavaFX.appinitialization. Initialization
package pl.projektyjava.listToDoJavaFX.appinitialization;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
#Component
public class Initialization implements ApplicationListener<StarterClass.StageReadyEvent>{
#Override
public void onApplicationEvent(StarterClass.StageReadyEvent event) {
Stage stage = event.getStage();
HBox mainPane= null;
try {
mainPane = FXMLLoader.load(getClass().getResource("/addingWindow.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Scene scene=new Scene(mainPane);
stage.setScene(scene);
stage.show();
}
}
pl.projektyjava.listToDoJavaFX.appinitialization.ListToDoJavaFXApplication
package pl.projektyjava.listToDoJavaFX.appinitialization;
import javafx.application.Application;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ListToDoJavaFxApplication {
public static void main(String[] args) {
Application.launch(StarterClass.class, args);
}
}
pl.projektyjava.listToDoJavaFX.appinitialization.StarterClass
package pl.projektyjava.listToDoJavaFX.appinitialization;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class StarterClass extends Application {
private ConfigurableApplicationContext applicationContext;
#Override
public void init() {
applicationContext=new SpringApplicationBuilder(ListToDoJavaFxApplication.class).run();
}
#Override
public void start(Stage stage) {
applicationContext.publishEvent(new StageReadyEvent(stage));
}
#Override
public void stop() {
applicationContext.close();
Platform.exit();
}
static class StageReadyEvent extends ApplicationEvent {
public StageReadyEvent (Stage stage){
super(stage);
}
public Stage getStage(){
return ((Stage) getSource());
}
}
}
pl.projektyjava.listToDoJavaFX.body.Task
package pl.projektyjava.listToDoJavaFX.body;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
private double priority;
public Task(String title, String description, double priority) {
this.title = title;
this.description = description;
this.priority = priority;
}
public Task() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPriority() {
return priority;
}
public void setPriority(double priority) {
this.priority = priority;
}
}
pl.projektyjava.listToDoJavaFX.body.TaskRepository
package pl.projektyjava.listToDoJavaFX.body;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TaskRepository extends CrudRepository<Task, Long> {
}
pl.projektyjava.listToDoJavaFX.fxmlcontrollers.AddingWindowController
package pl.projektyjava.listToDoJavaFX.fxmlcontrollers;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.projektyjava.listToDoJavaFX.body.Task;
import pl.projektyjava.listToDoJavaFX.body.TaskRepository;
#Controller
public class AddingWindowController {
#Autowired
TaskRepository taskRepository;
#FXML
private TextField title;
#FXML
private TextArea description;
#FXML
private Button listOfQuest;
#FXML
private Button addQuest;
#FXML
private Slider priority;
public void initialize() {
addQuest.setOnAction(event -> {
String titleText = title.getText();
String descriptionText = description.getText();
double priorityVal = priority.getValue();
Task task = new Task(titleText, descriptionText, priorityVal);
taskRepository.save(task);
});
}
}
and ERROR:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "pl.projektyjava.listToDoJavaFX.body.TaskRepository.save(Object)" because "this.taskRepository" is null
at pl.projektyjava.listToDoJavaFX.fxmlcontrollers.AddingWindowController.lambda$initialize$0(AddingWindowController.java:41)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8792)
at javafx.scene.control.Button.fire(Button.java:203)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
at com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3861)
at javafx.scene.Scene.processMouseEvent(Scene.java:1854)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2587)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:413)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
at com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at com.sun.glass.ui.View.notifyMouse(View.java:942)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
After adding ControlerFactory to FXMLLoader I have this:
javafx.fxml.LoadException:
/B:/Projekty/1%20PROJEKT/listToDo-JavaFX/listToDo-JavaFX/target/classes/addingWindow.fxml:11
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2685)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2517)
at pl.projektyjava.listToDoJavaFX.appinitialization.Initialization.onApplicationEvent(Initialization.java:28)
at pl.projektyjava.listToDoJavaFX.appinitialization.Initialization.onApplicationEvent(Initialization.java:14)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378)
at pl.projektyjava.listToDoJavaFX.appinitialization.StarterClass.start(StarterClass.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:849)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'pl.projektyjava.listToDoJavaFX.fxmlcontrollers.AddingWindowController' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:940)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:982)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:229)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:754)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2808)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2634)
... 19 more
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
2021-04-23 19:47:00.791 INFO 12928 --- [lication Thread] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-04-23 19:47:00.794 INFO 12928 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-04-23 19:47:00.800 INFO 12928 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:903)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.NullPointerException: Root cannot be null
at javafx.scene.Scene.<init>(Scene.java:345)
at javafx.scene.Scene.<init>(Scene.java:207)
at pl.projektyjava.listToDoJavaFX.appinitialization.Initialization.onApplicationEvent(Initialization.java:32)
at pl.projektyjava.listToDoJavaFX.appinitialization.Initialization.onApplicationEvent(Initialization.java:14)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378)
at pl.projektyjava.listToDoJavaFX.appinitialization.StarterClass.start(StarterClass.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:849)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Process finished with exit code 1
By default, the FXMLLoader will create controller instances by calling the no-argument constructor. Consequently, the AddingWindowController instance that's created is not managed by Spring, and Spring cannot inject #Autowired dependencies into it. (Basically, the Spring ApplicationContext has no knowledge that the AddingWindowController instance exists.)
You can supply a ControllerFactory to the FXMLLoader which asks that the controller is created by the spring application context:
#Component
public class Initialization implements ApplicationListener<StarterClass.StageReadyEvent>{
#Autowired
private ApplicationContext applicationContext ;
#Override
public void onApplicationEvent(StarterClass.StageReadyEvent event) {
Stage stage = event.getStage();
HBox mainPane= null;
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/addingWindow.fxml"));
fxmlLoader.setControllerFactory(applicationContext::getBean);
mainPane = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
Scene scene=new Scene(mainPane);
stage.setScene(scene);
stage.show();
}
}
Also note that you should create a new controller instance each time the FXML is loaded, so JavaFX controllers should have prototype scope. It probably doesn't matter too much, but the #Controller annotation in Spring is really intended for MVC controllers in a web application, so the #Component stereotype is really more appropriate here:
#Component
#Scope("prototype")
public class AddingWindowController {
// ...
}
By default #SpringBootApplication does componentscan in its own folder and underneath. So just place ur ListToDoJavaFxApplication one folder up into pl.projektyjava.listToDoJavaFX
Alternatively just add #ComponentScan(“pl.projektyjava.listToDoJavaFX”) right above #SpringBootApplication defining component scan explicitly.
In general whenever auto wiring fails silently without BeanCreationException at startup it is a sign that ur component is not being found by component scan

No response from PokeAPI

I am trying to get JSONObject from the Pokeapi in my Pokedex app, but it seems that there is no response and the volley error is produced. However, the link opens perfectly fine in my browser showing the JSON. I tried different links to the JSON, still it does not work. Permission to use internet is added to AndroidManifest. Request is added to RequestQueue. Where could be the problem?
Here is my PokedexAdapter class:
package com.example.pokedex;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> {
public static class PokedexViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PokedexViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.pokedex_row);
textView = view.findViewById(R.id.pokedex_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pokemon current = (Pokemon) containerView.getTag();
Intent intent = new Intent(v.getContext(), PokemonActivity.class);
intent.putExtra("name", current.getName());
//intent.putExtra("number", current.getNumber());
v.getContext().startActivity(intent);
}
});
}
}
private List<Pokemon> pokemon = new ArrayList<>();
private RequestQueue requestQueue;
public PokedexAdapter(Context context) {
requestQueue = Volley.newRequestQueue(context);
loadPokemon();
}
public void loadPokemon() {
String url = "https://pokeapi.co/api/v2/pokemon?limit=151";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
pokemon.add(new Pokemon(
result.getString("name"),
result.getString("url")));
}
notifyDataSetChanged();
} catch (JSONException e) {
Log.e("cs50", "onResponse: ", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("cs50", "onErrorResponse: pokemon list error");
}
});
requestQueue.add(request);
}
#NonNull
#Override
public PokedexViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pokedex_row, parent, false);
return new PokedexViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokedexViewHolder holder, int position) {
Pokemon current = pokemon.get(position);
holder.textView.setText(current.getName());
holder.containerView.setTag(current);
}
#Override
public int getItemCount() {
return pokemon.size();
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pokedex">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".PokemonActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Result - nothing is shown on the screen and this error is produced:
2020-06-09 19:09:37.469 15137-15137/com.example.pokedex D/cs50: onErrorResponse: pokemon list error
The problem was solved by reinstalling the app.
This thread was helpful:
java.net.SocketException: socket failed: EPERM (Operation not permitted)

JavaFX progress bar component activated from Spring Listener Method

I have three layer(gui->services->dao) desktop application (JavaFX+Spring 4).
Some of my methods realized in my services layer (without fx dependency) have long time computing. I'd like to report their progress in gui.
But there is a problem. My service layer hasn't got direct access to gui, make a log of IO operations and returns only summarize of it. GUI layer, doesn't know about progress of intermediate operations.
I try to make a generic progress component. It could be realized as a Spring Bean with listener method located id GUI layer. My services can publish ApplicationEvent, which can be received via progress component in gui. When it gets the event, should activate progress bar and report next events.
In init methods I have started ProgressTask, and bind progressProperty with my gui progress bar control.
Call method of my ProgressTask runs while actual counter is less that max number of steps.
There is my component:
#Component
#Controller
public class ProgressBarComponent {
#FXML
private ProgressBar progressBar;
private ProgressTask actTask;
#FXML
public void initialize(){
}
private void initProgressBar(int aMax){
actTask=new ProgressTask();
actTask.initState(aMax);
progressBar.progressProperty().bind(actTask.progressProperty());
new Thread(actTask).start();
}
#EventListener
public void handleProgressEvent(ProgressEvent event) {
if(event.getGetActStep()==0){
initProgressBar(event.getMaxStep());
}
actTask.changeState(event.getGetActStep());
}
class ProgressTask extends Task<Object>{
private int max=100;
private int act=0;
private volatile boolean cancelled;
public void initState(int aMax){
this.max=aMax;
}
public void changeState(int newVal){
act=newVal;
updateProgress(act, max);
updateMessage("progress: " + act);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalArgumentException(e);
}
}
#Override
protected Object call() throws Exception {
while(act<max){
}
return null;
}
}
}
But it doesn't work.
Progress bar control is activated but in one step and at once it has a 100 percent value.
I have found a lot of examples Progress Bar FX control, but all of them assume that main logic is computed inside call() method of ProgressTask. In my case it isn't possible.
It is possible to make a ProgressBar Component, which is activated from listener method ? If yes, what code should be in ProgressTask.call() method ?
The point of a Task is to define some functionality that should be run on a background thread. So if this functionality is already implemented elsewhere, there is no need for a task.
Assuming the service is being invoked on a background thread (i.e. not on the FX Application Thread), you should just be able to do:
#Component
#Controller
public class ProgressBarComponent {
private int max ;
#FXML
private ProgressBar progressBar;
#FXML
public void initialize(){
}
private void initProgressBar(int aMax){
this.max = aMax ;
}
#EventListener
public void handleProgressEvent(ProgressEvent event) {
if(event.getGetActStep()==0){
Platform.runLater(() -> initProgressBar(event.getMaxStep()));
}
Platform.runLater(() ->
progressBar.setProgress(1.0 * event.getGetActStep() / max));
}
}
Here's a complete SSCCE:
ProgressViewer.java:
package springevent;
import org.springframework.context.event.EventListener;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ProgressViewer {
private Stage stage = new Stage();
private Scene scene ;
private ProgressBar progressBar ;
public ProgressViewer() {
progressBar = new ProgressBar();
StackPane root = new StackPane(progressBar);
root.setPadding(new Insets(20));
scene = new Scene(root);
stage.setScene(scene);
}
#EventListener
public void progressUpdate(ProgressEvent event) {
if (event.getCurrent() < event.getMax()) {
Platform.runLater(stage::show);
} else {
Platform.runLater(stage::hide);
}
final double progress = 1.0 * event.getCurrent() / event.getMax() ;
Platform.runLater(() -> progressBar.setProgress(progress));
}
}
Service.java:
package springevent;
import javax.inject.Inject;
import org.springframework.context.ApplicationContext;
public class Service {
#Inject
private ApplicationContext context ;
public void runService() {
context.publishEvent(new ProgressEvent(0, 100));
try {
for (int i = 1 ; i <= 100; i++) {
Thread.sleep(200);
context.publishEvent(new ProgressEvent(i, 100));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
ProgressEvent.java
package springevent;
public class ProgressEvent {
private final int current ;
private final int max ;
public ProgressEvent(int current, int max) {
this.current = current ;
this.max = max ;
}
public int getCurrent() {
return current ;
}
public int getMax() {
return max ;
}
}
MainController.java
package springevent;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import org.springframework.context.event.EventListener;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
public class MainController {
#Inject
private Executor exec ;
#Inject
private Service service ;
#FXML
private Button startButton ;
public void startProcess() {
exec.execute(service::runService);
}
#EventListener
public void progressUpdate(ProgressEvent event) {
startButton.setDisable(event.getCurrent() < event.getMax());
}
}
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<StackPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="springevent.MainController">
<padding>
<Insets top="20" bottom="20" left="20" right="20"/>
</padding>
<Button fx:id="startButton" text="Start process" onAction="#startProcess" />
</StackPane>
Main.java
package springevent;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
private AbstractApplicationContext context ;
#Override
public void start(Stage primaryStage) throws IOException {
context = new AnnotationConfigApplicationContext(AppConfig.class);
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
loader.setControllerFactory(context::getBean);
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
and AppConfig.java:
package springevent;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
#Bean
public Service service() {
return new Service();
}
#Bean
public MainController mainController() {
return new MainController();
}
#Bean
public ProgressViewer progressViewer() {
return new ProgressViewer();
}
#Bean
public Executor exec() {
return Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
}
}

JavaFX MVC controller not work

i'm beginner with javaFX and i try to develop an application with MVC. In this application i use two controllers, one for menuBar and for panelCenter which contain button and label. When i click on Button (CenterControler) "It works" but when i click on File->Quit (MainControler) it don't works.
Here the file Main.java :
package application;
import java.io.IOException;
import controler.CenterControler;
import controler.MainControler;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
CenterControler ctrl_Center;
MainControler ctrl_Main;
Stage primaryStage;
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/themain.fxml"));
Parent root = (Parent) fxmlLoader.load();
ctrl_Main = (MainControler)fxmlLoader.getController();
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("FXML Welcome");
primaryStage.setScene(scene);
primaryStage.show();}
public static void main(String[] args) {
launch(args);
}
}
MainControler.java
package controler;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
public class MainControler implements Initializable{
#FXML
private Menu File;
#FXML
private MenuBar barreMenu;
#FXML
private Menu sousMenu;
#FXML
private MenuItem menuQuit;
#FXML
private CenterControler centreControle;
#Override
public void initialize(URL location, ResourceBundle resources) {
assert File != null : "fx:id=\"File\" was not injected: check your FXML file 'themain.fxml'.";
assert menuQuit != null : "fx:id=\"menuQuit\" was not injected: check your FXML file 'themain.fxml'.";
}
public void setCenterControle(CenterControler cc){this.centreControle = cc; }
#FXML
protected void onClick2()
{
centreControle.show("IT WORKS !!! FROM MAIN CONTROLER");
}
}
CenterControler.java
package controler;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
public class CenterControler implements Initializable{
#FXML
private AnchorPane monFonds;
#FXML
private Button btn_1;
#FXML
private Label labelMSG;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
assert btn_1 != null : "fx:id=\"btn_1\" was not injected: check your FXML file 'part2.fxml'.";
assert labelMSG != null : "fx:id=\"labelMSG\" was not injected: check your FXML file 'part2.fxml'.";
}
public void setBTN(Button btn){ this.btn_1 = btn;}
public void setLabel(Label lb) {this.labelMSG = lb; }
public Button getBTN(){ return this.btn_1; }
public Label getLabel(){ return this.labelMSG;}
#FXML
protected void onClickShowMSG()
{
labelMSG.setText("PUSH FROM CENTER CONTROLER");
}
public void show(String msg)
{
labelMSG.setText(msg);
}
}
themain.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controler.MainControler">
<children>
<MenuBar fx:id="barreMenu" VBox.vgrow="NEVER">
<menus>
<Menu fx:id="sousMenu" mnemonicParsing="false" text="File">
<items>
<MenuItem fx:id="menuQuit" mnemonicParsing="false" onAction="#onClick2" text="Quit" />
</items>
</Menu>
</menus>
</MenuBar>
<fx:include fx:id="p2" source="part2.fxml" />
</children>
</VBox>
part2.fxml
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controler.CenterControler">
<children>
<Button fx:id="btn_1" layoutX="274.0" layoutY="188.0" mnemonicParsing="false" onAction="#onClickShowMSG" text="Button" />
<Label fx:id="labelMSG" layoutX="286.0" layoutY="128.0" text="Label" />
</children>
</AnchorPane>
Thanks in advance.
The name of the field where the controller is injected is constructed by taking the value of the fx:id attribute of the fx:include element and concatenating "Controller". Therefore the name of the field where the nested controller is injected has to be p2Controller and not centreControle:
public class CenterControler implements Initializable {
//...
#FXML
private CenterControler p2Controller;
//...
}
Unfortunately this is not well documented... (I had to look at the source code to find out)

Resources