How to write Test cases for Javafx Controllers?
I have written this test class for javafx application.
class HelloApplicationTest extends GuiTest {
@Override
protected Parent getRootNode() {
Parent parent = null;
try {
parent = FXMLLoader.load((getResource("hello-view.fxml")));
return parent;
}
catch (IOException ex) {
}
return parent;
}
@Test
void add_button() {
Button add_btn_1=find("#add_btn");
assertFalse(add_btn_1.disableProperty().get());
FxAssert.verifyThat("#add_btn", LabeledMatchers.hasText("Add"));
}
}
I am getting error like this -> java.lang.NoSuchMethodError: 'java.util.Iterator javafx.stage.Window.impl_getWindows()'
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="350.0" prefWidth="666.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.fxml_db.HelloController">
<children>
<Label layoutX="14.0" layoutY="14.0" prefHeight="39.0" prefWidth="295.0" text="Add and View Employee:">
<font>
<Font name="System Bold" size="24.0" />
</font>
</Label>
<Label layoutX="22.0" layoutY="93.0" prefHeight="27.0" prefWidth="124.0" text="Name:" />
<Label layoutX="22.0" layoutY="136.0" prefHeight="27.0" prefWidth="124.0" text="Address:" />
<Label layoutX="22.0" layoutY="181.0" prefHeight="27.0" prefWidth="124.0" text="Age:" />
<TextField fx:id="name" layoutX="106.0" layoutY="94.0" />
<TextField fx:id="address" layoutX="106.0" layoutY="137.0" />
<TextField fx:id="age" layoutX="106.0" layoutY="182.0" />
<Button fx:id="add_btn" layoutX="127.0" layoutY="223.0" mnemonicParsing="false" onAction="#add_details" text="Add" />
<TableView fx:id="table" layoutX="342.0" layoutY="51.0" prefHeight="260.0" prefWidth="305.0">
<columns>
<TableColumn fx:id="idcol" prefWidth="39.33331298828125" text="ID" />
<TableColumn fx:id="namecol" prefWidth="111.3333740234375" text="Name" />
<TableColumn fx:id="addresscol" prefWidth="110.00003051757812" text="Address" />
<TableColumn fx:id="agecol" prefWidth="40.6666259765625" text="Age" />
</columns>
</TableView>
<Button fx:id="connect_db" layoutX="14.0" layoutY="310.0" mnemonicParsing="false" onAction="#connect" text="Connect DB" />
<Button layoutX="200.0" layoutY="223.0" mnemonicParsing="false" onAction="#clear_data" text="Clear" />
</children>
</AnchorPane>
I am not able to fetch the components form the .fxml file. this is my .fxml code
do you know?
how many words do you know
See also questions close to this topic
-
build spring boot (mvnw) with docker can not use cache
Spring Boot Docker Experimental Features Docker 18.06 comes with some “experimental” features, including a way to cache build dependencies. To switch them on, you need a flag in the daemon (dockerd) and an environment variable when you run the client. With the experimental features, you get different output on the console, but you can see that a Maven build now only takes a few seconds instead of minutes, provided the cache is warm.
my dockerfile can not use cache.
dockerfile
# syntax=docker/dockerfile:experimental FROM openjdk:8-jdk-alpine as build WORKDIR /workspace/app COPY mvnw . COPY .mvn .mvn COPY pom.xml . COPY src src RUN --mount=type=cache,target=/root/.m2 ./mvnw install -DskipTests -s .mvn/wrapper/settings.xml RUN mkdir -p target/extracted && java -Djarmode=layertools -jar target/*.jar extract --destination target/extracted FROM openjdk:8-jre-alpine ENV TZ Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN addgroup -S spring && adduser -S spring -G spring USER spring:spring ARG EXTRACTED=/workspace/app/target/extracted ARG JAVA_OPTS="-Xmx100m -Xms100m" COPY --from=build ${EXTRACTED}/dependencies/ ./ COPY --from=build ${EXTRACTED}/spring-boot-loader/ ./ COPY --from=build ${EXTRACTED}/snapshot-dependencies/ ./ COPY --from=build ${EXTRACTED}/application/ ./ ENTRYPOINT ["sh", "-c","java ${JAVA_OPTS} org.springframework.boot.loader.JarLauncher"]
run shell
DOCKER_BUILDKIT=1 docker build -t org/spring-boot .
every time use many minutes
-
"no main manifest attribute" in .jar Netbeans 13
I recently just started toying around with Maven in java. Time comes to test my project, it works fine in the NetBeans window, running the main class found in App.java (com.MyCompany.App), but when I try to run it from a command line I get an error:
"no main manifest attribute"
I'm using Apache Netbeans 13 with Maven to build the project
Any help will be apreciated Thanks in advance
-
Spring Boot - nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '' available
I'm trying to add the following statement to a Spring Boot service:
@Autowired private ApELDatabasePublisherService eventPublisher;
The dependency for eventPublisher is contained in maven, in this jar file:
.m2\repository\com\xxxx\bip\bip-event-logging\1.5.3.7-RELEASE.jar
It compiles, builds and updates the local maven repository, but when I launch the application, it terminates with an error message.
Initially, the error message was this:
No qualifying bean of type 'com.xxxx.bip.components.el.services.ApELDatabasePublisherService' available
However, that disappeared when I added
com.xxxx.bip.components.el.services
to the component scan.The next message was this:
No qualifying bean of type 'com.xxxx.bip.components.el.dao.services.IApElTypeNameLookupService' available:
So I added
com.xxxx.bip.components.el.dao.services
to the component scan, and that error went away.But now I have a third message which is not going away, as follows:
No qualifying bean of type 'com.xxxx.bip.components.el.repository.IApELEventTypeRepository' available
This message stays even when I add the following to component scan:
com.xxxx.bip.components.el.repository
So my current scan looks like this:
@EnableRetry @EnableScheduling @SpringBootApplication(exclude = { HibernateJpaAutoConfiguration.class }) @ComponentScan(basePackages = { "com.xxxx.bip.components.el.services", "com.xxxx.bip.components.el.dao.services", "com.xxxx.bip.components.el.repository",
I've verified that the class in question,
IApELEventTypeRepository
is included in the jar file and is annotated as "@Repository"Why would it not find it when it finds the previous two packages?
-
Adding 2nd fxml within pane of 1st fxml
I'm brand new to javafx so apologies for the basic question!
My question is how to add a 2nd fxml inside a pane from the 1st fxml.
I've got a mini program here.
public class Main extends Application { @Override public void start(Stage primaryStage) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml1.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
and FXML1 controller
@FXML private Button button; @FXML private Pane pane; @FXML void load(ActionEvent event) throws IOException { Pane fp = FXMLLoader.load(getClass().getResource("/fxml2.fxml")); System.out.println("This should load fxml2"); pane.getChildren().add(fp); } @Override public void initialize(URL arg0, ResourceBundle arg1) { // TODO Auto-generated method stub } }
I keep getting NPE from the FXML field pane Hope this makes any sense
cheers
Edit --
Here's the complete stack trace
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at javafx.fxml@18/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1857) at javafx.fxml@18/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1724) at javafx.base@18/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at javafx.base@18/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234) at javafx.base@18/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at javafx.base@18/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at javafx.base@18/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.base@18/javafx.event.Event.fireEvent(Event.java:198) at javafx.graphics@18/javafx.scene.Node.fireEvent(Node.java:8797) at javafx.controls@18/javafx.scene.control.Button.fire(Button.java:203) at javafx.controls@18/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208) at javafx.controls@18/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274) at javafx.base@18/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247) at javafx.base@18/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at javafx.base@18/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234) at javafx.base@18/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at javafx.base@18/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at javafx.base@18/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at javafx.base@18/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at javafx.base@18/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) at javafx.base@18/javafx.event.Event.fireEvent(Event.java:198) at javafx.graphics@18/javafx.scene.Scene$MouseHandler.process(Scene.java:3881) at javafx.graphics@18/javafx.scene.Scene.processMouseEvent(Scene.java:1874) at javafx.graphics@18/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2607) at javafx.graphics@18/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411) at javafx.graphics@18/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301) at java.base/java.security.AccessController.doPrivileged(AccessController.java:399) at javafx.graphics@18/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450) at javafx.graphics@18/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424) at javafx.graphics@18/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449) at javafx.graphics@18/com.sun.glass.ui.View.handleMouseEvent(View.java:551) at javafx.graphics@18/com.sun.glass.ui.View.notifyMouse(View.java:937) at javafx.graphics@18/com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at javafx.graphics@18/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:77) at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at javafx.base@18/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275) at javafx.fxml@18/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:84) at javafx.fxml@18/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1852) ... 46 more Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.layout.Pane.getChildren()" because "this.pane" is null at application.fxml1_controller.load(fxml1_controller.java:26) ... 57 more
and the fxml's
fxml1
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.layout.BorderPane?> <?import javafx.scene.layout.Pane?> <?import javafx.scene.text.Text?> <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.fxml1_controller"> <top> <Text strokeType="OUTSIDE" strokeWidth="0.0" text="This is fxml1" BorderPane.alignment="CENTER" /> </top> <center> <Pane fx:id="pane" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" /> </center> <left> <Button fx:id="button" mnemonicParsing="false" onAction="#load" text="load fxml2" BorderPane.alignment="CENTER" /> </left> </BorderPane>
fxml2
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.text.Text?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.fxml2_controller"> <children> <Text layoutX="277.0" layoutY="196.0" strokeType="OUTSIDE" strokeWidth="0.0" text="This is fxml2" /> </children> </AnchorPane>
-
JavaFX label.getText() returns nothing in another class
I need that label values (num, cost) to be displayed in Bank.java from Work-window.java
num = random int value
cost = int valueCode Work-window.java
package s.lab9; import java.io.IOException; import java.util.Random; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; public class WorkWindow { @FXML private Button enter; @FXML private Button payment; public int a; @FXML private TextField ticket; private ActionEvent event; private Stage stage; private Scene scene; private Parent root; @FXML public Label num; @FXML public Label cost; public WorkWindow(){ } public void click(ActionEvent event) throws IOException { String b= (ticket.getText()); Random rnd= new Random(); if (b.equals(String.valueOf(1))){ a= rnd.nextInt(1000); num.setText(String.valueOf(a)); cost.setText(String.valueOf(500)); } if (b.equals(String.valueOf(2))){ a= rnd.nextInt(1000); num.setText(String.valueOf(a)); cost.setText(String.valueOf(10000)); } if (b.equals(String.valueOf(3))){ a= rnd.nextInt(1000); num.setText(String.valueOf(a)); cost.setText(String.valueOf(10)); } } public void switchtoPay(ActionEvent event) throws IOException{ FXMLLoader loader = new FXMLLoader(getClass().getResource("Bank.fxml")); root = loader.load(); Bank bank = loader.getController(); bank.display2(num.getText(), cost.getText()); payment.getScene().getWindow().hide(); root = FXMLLoader.load(getClass().getResource("Payment.fxml")); Stage stage = new Stage(); stage.setTitle("Payment"); stage.setScene(new Scene(root)); stage.show(); } }
Code Bank.java
package s.lab9; import javafx.fxml.FXML; import javafx.scene.control.Label; public class Bank { @FXML private Label cart; @FXML public Label ticket; @FXML public Label cost1; public void display(String numcart){ cart.setText(numcart); } public void display2(String num, String cost){ ticket.setText(num); cost1.setText(cost); } }
Btw method display1 works correct, but display 2 isn't, Idk where i did mistake. fx:id:controllers assigned correctly, there are have prefWidth, so they cannot be "empty"
-
Using ImageView.setImage(image) with event handler not working JavaFX
public class JohnsonGuessingGame extends Application{ private ImageView d; private Image one; private Image two; private Image three; private Image four; private Image five; private Image six; private TextField input; public static void main(String[] args){ launch(args); } public void start(Stage primaryStage) { TextField input = new TextField(); Button button = new Button("PLAY"); Label prompt = new Label(); int dice = 6; Image one = new Image("1.png"); Image two = new Image("2.png"); Image three = new Image("3.png"); Image four = new Image("4.png"); Image five = new Image("5.png"); Image six = new Image("6.png"); ImageView d = new ImageView(six); HBox hbox = new HBox(prompt, input); VBox vbox = new VBox(hbox, d, button); button.setOnAction(new ButtonHandler()); Scene scene = new Scene(vbox); primaryStage.setScene(scene); primaryStage.show(); } class ButtonHandler implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent event) { // Get the kilometers. int inp = Integer.parseInt(input.getText()); if(inp == 1){ d.setImage(one); } else if(inp == 2){ d.setImage(two); } else if(inp == 3){ d.setImage(three); } else if(inp == 4){ d.setImage(four); } else if(inp == 5){ d.setImage(five); } else if(inp == 6){ d.setImage(six); } } } }
everything works fine until i hit the button. then it gives me this error:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.scene.control.TextField.getText()" because "this.this$0.input" is null
I don't even know what I'm doing wrong please tell me, thanks.
-
How can i test this void method with junit?
I'm new in testing, and i have to test this especific void method with Junit, any thoughts? thanks!
public void createExcel(TarifaSurchargeResponse tarifaResponse, int rowCount, HSSFSheet sheet) { for (TarifaSurcharge tarifa : tarifaResponse.getTarifaSurcharge()) { if (Validator.isNotNull(tarifa)) { Row row = sheet.createRow(++rowCount); int columnCount = 0; Cell _cell = row.createCell(columnCount); _cell.setCellValue(TarifasSurchargeLocalUtil.reformatDate(tarifa.getFechaVenta())); _cell = row.createCell(++columnCount); _cell.setCellValue(tarifa.getCodigoComercio()); _cell = row.createCell(++columnCount); _cell.setCellValue(tarifa.getMontoVenta()); _cell = row.createCell(++columnCount); _cell.setCellValue("-"); } } }
-
Java.lang.NoClassDefFoundError: junit/framework/TestCase
After upgrading from JUnit 4 to JUnit 5 getting this error when i am trying to run test as JUnit in eclipse. Getting warning: failed to load class 'org.eclipse.jdt.internal.junit.runner.junit3.junit3TestLoader$1'
-
"message":"Head \"https://registry-1.docker.io/v2/testcontainers/ryuk/manifests/0.3.0\": unauthorized: incorrect username or password" when run test
I have added testcontainer in spring boot app
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @Testcontainers @AutoConfigureMockMvc class ProductServiceApplicationTests { @Container static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.4.2"); @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @DynamicPropertySource static void setProperties(DynamicPropertyRegistry dynamicPropertyRegistry) { dynamicPropertyRegistry.add("spring.data.mongodb.uri",mongoDBContainer::getReplicaSetUrl); } @Test void shouldCreateProduct() throws Exception { ProductRequest productRequest = getProductRequest(); String productRequestString = objectMapper.writeValueAsString(productRequest); mockMvc.perform(MockMvcRequestBuilders.post("/api/product") .contentType(MediaType.APPLICATION_JSON) .content(productRequestString) ).andExpect(status().isCreated()) ; } private ProductRequest getProductRequest() { return ProductRequest.builder() .name("Iphone 13") .description("Iphone 13") .price(BigDecimal.valueOf(1200)) .build(); } }
When Running it Getting the below error
com.github.dockerjava.api.exception.InternalServerErrorException: Status 500: {"message":"Head \"https://registry-1.docker.io/v2/testcontainers/ryuk/manifests/0.3.0\": unauthorized: incorrect username or password"} at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:247) at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.lambda$executeAndStream$1(DefaultInvocationBuilder.java:269) at java.lang.Thread.run(Thread.java:748)