Search code examples
javajavafxlocalizationlocale

How can I get Locale.setDefault() to work in my JavaFX application


I am working on a project and need to test that the localization is working if a Locale.getDefault() call returns something other than my own locale. I have come across examples using Locale.setDefault() to set the default locale for testing but it is not working in my code. I keep getting an error.

Locale.setDefault(new Locale("es"));

The line above should, from what I understand, set the default locale to Spanish. Instead, I am getting an error inside of Netbeans that is saying Illegal start of type. I am not sure what is causing this or if I need to set the default locale somewhere else in my code. Below is everything up until that line of code

import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;

/**
* FXML Controller class
*
* @author Aaron
*/
public class FXMLDocumentController implements Initializable 
{
    Locale.setDefault(new Locale("es"));

Any help with this is greatly appreciated


Solution

  • The line

    Locale.setDefault(new Locale("es"));
    

    is not contained in an executable section of your class file. Since it is a method invocation and not an assignment it needs to be in a method or constructor. If you want to run it when the class is loaded, wrap it in a static block:

    static {
        Locale.setDefault(new Locale("es"));
    }
    

    Since this is an FXML controller class, so you could also put it in the initialize method.

    @FXML
    void initialize() {
        Locale.setDefault(new Locale("es"));
        ...
    }