1

I am working on a JavaFX form. The form is supposed to take the Value and add it to a data base. Whenever I try to get the value by .getValue it creates an error

Incompatible Types: Object cannot be converted to Int

Here is the FXML Code:

<Spinner fx:id="spinner" layoutX="494.0" layoutY="528.0" maxWidth="100.0" minWidth="100.0" prefWidth="100.0">
    <valueFactory>
       <SpinnerValueFactory.IntegerSpinnerValueFactory min="0" max="30" initialValue="20" amountToStepBy="1"/>
    </valueFactory>
</Spinner>

Java Code:

 Spinner mySpinner=(Spinner) spinner;
        int value = mySpinner.getValue;

Thanks for your help

Helena Ann
  • 21
  • 1
  • 6

2 Answers2

2

Just posting the comment as an answer. To resolve this question:

Don't ever use raw types. Use something like this instead:

Spinner<Integer> mySpinner = (Spinner<Integer>) spinner; 
Lino
  • 19,604
  • 6
  • 47
  • 65
  • There shouldn't really be a need for the cast, either. – James_D Nov 03 '17 at 11:06
  • @James_D i don't know the api, and there isn't much information, so I'm guessing that spinner is of type `Object`. I might be wrong though ;) – Lino Nov 03 '17 at 11:16
  • 1
    Since it's declared in the FXML file (via the `fx:id`), it must be injected in to the controller (via a `@FXML` annotation). So it just needs to be injected with the correct type, i.e. `@FXML private Spinner spinner ;` and then `int value = spinner.getValue();` via unboxing. – James_D Nov 03 '17 at 11:23
  • @James_D you might want to make an answer yourself? – Lino Nov 03 '17 at 11:57
2

As stated in another answer, you should never use raw types. Spinner is a generic type: it's defined as Spinner<T>, where T is a type parameter that stands for "the type of the value that the spinner holds". More formally, the documentation states

T - The type of all values that can be iterated through in the Spinner. Common types include Integer and String.

When using a class that is generic, you should always specify the type, e.g. in your case you should use

Spinner<Integer>

to refer to a spinner that iterates through integers; you should never just use the "raw type"

Spinner

Since you've defined the spinner in FXML with

<Spinner fx:id="spinner" ... >

you are presumably injecting it into the controller. Just use the parameterized type when you inject it:

public class MyController {

    @FXML
    private Spinner<Integer> spinner ;

    // ...

}

Now the compiler is assured that spinner holds Integers as the value, so you can just do

int value = spinner.getValue();

Also see Java Generics: List, List<Object>, List<?>

James_D
  • 201,275
  • 16
  • 291
  • 322