While developing a scene switch program in JavaFX, I encountered an error when attempting to switch scenes. Interestingly, the error disappears when CSS is not used – the program works perfectly without

Here is My Main.java File

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage stage) {
       try {
           Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
           Scene scene = new Scene(root);
           String css= this.getClass().getResource("application.css").toExternalForm();
           scene.getStylesheets().add(css);
           stage.setScene(scene);
           stage.show();
       } catch (Exception e) {
           e.printStackTrace();
      }
  }
   public static void main(String[] args) throws Exception {
       Application.launch(args);
  }
 }

This is my SwitchController.java file

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SceneSwitcher {

private Stage stage;
private Scene scene;
private Parent parent;

public void switchToMain(ActionEvent event) throws IOException {
    parent = FXMLLoader.load(getClass().getResource("Main.fxml"));
    stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
    String css = this.getClass().getResource("application.css").toExternalForm();
    scene.getStylesheets().add(css);
    scene = new Scene(parent);
    stage.setScene(scene);
    stage.show();
}

public void switchToAnotherApp(ActionEvent event) throws IOException {
    parent = FXMLLoader.load(getClass().getResource("AnotherApp.fxml"));
    stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
    String css = this.getClass().getResource("application.css").toExternalForm();
    scene.getStylesheets().add(css);
    scene = new Scene(parent);
    stage.setScene(scene);
    stage.show();
 }
}

this is my application.css file

.main{
    -fx-background-color: "red";
    
}
#sc1{
    -fx-alignment: center;
}
#sc2{
    -fx-alignment: center;
    -fx-text-fill: "GREEN";
    -fx-outline:none;
}

.label{
    -fx-font-size: 20;
    -fx-font-family: "Lucida Console";
    -fx-text-fill: "white";
    -fx-alignment: center;
}

#titleLabel{
    -fx-font-size: 60;
}

this is AnotherApp.fxml file

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?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/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SceneSwitcher">
<children>
<Button fx:id="sc1" layoutX="197.0" layoutY="272.0" mnemonicParsing="false" onAction="#switchToMain" prefHeight="84.0" prefWidth="187.0" text="Switch to Main Scene" />
  <Label layoutX="1.0" layoutY="50.0" prefHeight="17.0" prefWidth="600.0" text="This is Scene 2" />
</children>
</AnchorPane>

This is my Main.fxml file

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?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/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SceneSwitcher">
  <children>
  <Label fx:id="titleLabel" layoutX="1.0" layoutY="143.0" prefHeight="17.0" prefWidth="600.0" text="Level 1" />
  <Label fx:id="secondLevelLabel" layoutX="2.0" layoutY="242.0" prefHeight="17.0" prefWidth="600.0" text="this has some CSS styles" />
  <Button fx:id="sc2" layoutX="213.0" layoutY="292.0" mnemonicParsing="false" onAction="#switchToAnotherApp" prefHeight="78.0" prefWidth="177.0" text="Switch to Another App" />
</children>
</AnchorPane>

I am just starting to learn JavaFX and Java, inspired by [Bro code] https://www.youtube.com/watch?v=9XJicRt_FaI&ab_channel=BroCode. If you have any tips or suggestions for me, please comment below. Thank you!

Answer №1

Following the advice of @n247s and @kleopatra, it is important to specify the error you are encountering and use clear naming conventions for better understanding by readers.

Upon closer inspection, one issue that stands out is the order in which the stylesheet is assigned. It seems that you are assigning the stylesheet to the scene before creating or initializing it, leading to either a NullPointerException or having no impact on the scene at all. To rectify this, the stylesheet should be assigned after the scene has been created.

You can modify the code as shown below:

public class SceneController {

    private Stage stage;
    private Scene scene;
    private Parent parent;

    public void switchToApp(ActionEvent event) throws IOException {
        parent = FXMLLoader.load(getClass().getResource("App.fxml"));
        addScene(event);
    }

    public void switchToApp2(ActionEvent event) throws IOException {
        parent = FXMLLoader.load(getClass().getResource("App2.fxml"));
        addScene(event);
    }
     
     private void addScene(ActionEvent event){
        stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        scene = new Scene(parent);
        String css = this.getClass().getResource("application.css").toExternalForm();
        // Set the stylesheet after the scene creation
        scene.getStylesheets().add(css);
        stage.setScene(scene);
        stage.show();
     }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

Sending special characters like umlauts from an Angular client to a Java server

When passing values like Weiß from the user interface to the MPC controller, I'm experiencing issues where the value gets corrupted along the way and becomes Weià I've been trying to resolve this problem by setting UTF-8 encoding somewhere, bu ...

What is the best way to eliminate unwanted white space at the top of the page?

I'm new to web development and I'm exploring the concept of white space at the top of a webpage. Here is a snippet of my code: HTML: <div> <p>lorem ipsum</P> </div> CSS: div { background-color: black; } I attem ...

Contrasting the process of generating DOM elements by using createElement, setting properties, etc., versus constructing a string of elements and then appending them

I am curious about the distinction between these two methods for creating HTML elements. I cannot seem to find any difference. I simply want to understand if there are any variations based on performance or any other factors. The first technique involves ...

Getting a value from strings.xml within a retrofit interface - a simple guide

We have been utilizing the retrofit android client library for handling network requests to our server. However, I am facing a challenge in trying to access values stored in the strings.xml file from the interface class we designed for retrofit. Below is ...

The div does not allow elements to be centered

I am facing an issue where elements are not centering on my div. I have tried numerous solutions (so many that I finally decided to create a Stack Overflow account), but nothing seems to work. Interestingly, the elements center on PC but for some reason, ...

Designing a personalized confirmation pop-up following the submission of an AJAX form

I am currently utilizing the AJAX JQuery validation plugin to submit a form. Below is a snippet of the code: $(document).ready(function(){ $("#myform").validate({ debug: false, rules: { fname: {required: true}, sname: {required: t ...

Creating a customizable Sass Mixin for animation keyframes that incorporates various stages and the transform property

My goal is to generate the standard CSS using a SASS Mixin for efficiency. STANDARD CSS @-webkit-keyframes crank-up { 100% { -webkit-transform: rotate(360deg);} } @-moz-keyframes crank-up { 100% { -moz-transform: rotate(360deg);} } @-o-keyframes cran ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

How can you implement a one-time superuser access request in your Android app?

As I venture into creating my inaugural android application, I am focused on the task of altering both the MAC address and device hostname. One challenge I face is the repeated request for superuser access every time the user initiates a change. Currently ...

Preventing the background color from exceeding the text boundaries using CSS

I'm having trouble containing the background color within the text content. I want the right spacing to be equal to the left, but as you can see in this screenshot, the right side is not adjusting: https://i.sstatic.net/cD4GK.png Here's the cod ...

Incorporating a scrollbar into a CSS content accordion for enhanced user experience

Currently, I am exploring a tutorial for coding a content accordion which can be found here: I am wondering about the possibility of adding endless content to each section while incorporating a scroll bar. Any suggestions on how to achieve this? Apprecia ...

UPDATE: The catch block in my code is not functioning properly for exception handling

MODIFIED I made some changes to my code, implementing the following function in my page object. public void searchItem(String keyword) throws Exception { driver.findElement(searchBoxLocator).sendKeys(keyword); try { new WebDriverWait(driv ...

Retrieve information from the $http response utilizing AngularJS

My Java server generates JSON objects using the following code: @Override public void serialize(Net net, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { try { Set<Place> places = net.getPlaces(); ...

Tips for maintaining a Java program continuously running all day and night

I created a Java program and converted it into a jar file. Now, I am looking to run it constantly on my AWS server without any interruptions. To achieve this, I am using the 'screen' application to keep it running even after I log out. The comman ...

What is the best way to determine the identifier of an object in Java programming language?

Currently grappling with a coding issue where I am attempting to utilize System.out.println() in order to display the name of an object. For instance, given the code snippet String foo = new String("Hi");, my goal is to output "foo". Any suggestions on h ...

Is there a way to simulate the screen resolution and size of a Windows laptop on a Macbook Retina screen in order to test frontend

Currently developing a web app frontend on my MacBook with a Retina screen. However, the majority of app users use Windows laptops with 13/14" screens and the frontend appears too large for them. How can I accurately simulate the screen size and pixel den ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

CSS tip: Keep the bottom of the screen always visible in an overflow window

My webpage has a continuously updating element where new data is added to the bottom. I currently have 'overflow: scroll' enabled for users to manually scroll down and view this new information. However, I am looking for a way to display these up ...

Choosing a value in the second dropdown menu based on the selection made in the first dropdown menu can be achieved by retrieving both values from the database using a common list

I have a scenario where I am utilizing two drop-down menus with the same data sourced from a database. When a particular item is selected in the first drop-down, it should not be available in the second drop-down. For instance, the values in the first dro ...