how to save the value of a jspinner from change listener
-
04-06-2021 - |
Question
I wish to use the value created called spinnerModel but cannot seem to do so, I believe I have to declare it as a certain type which I am not sure. I want to make it into a double as it will be used later in the program. I have the following as it stands,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class UI {
//Need to use the spinnerModel here but cannot :(
private void weightSpinnerMetricStateChanged(ChangeEvent e) {
JSpinner weightSpinnerMetric = (JSpinner) e.getSource();
SpinnerModel spinnerModel = weightSpinnerMetric.getModel();
System.out.println(spinnerModel.getValue());
}
stonesSpinnerImperial = new JSpinner(); //Spinner created here.
stonesSpinnerImperial.setModel(new SpinnerNumberModel(3, 3, 31, 1));
stonesSpinnerImperial.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
stonesSpinnerStateChanged(e);
stonesSpinnerImperialStateChanged(e);
}
});
}
Solution
You should retrieve the value from the spinner model, and not trying to save the event.
This is all explained in the Swing tutorial about spinners. A small copy paste of the code from that turial
public void stateChanged(ChangeEvent e) {
SpinnerModel dateModel = dateSpinner.getModel();
if (dateModel instanceof SpinnerDateModel) {
setSeasonalColor(((SpinnerDateModel)dateModel).getDate());
}
Of course you will need to adjust this code to match your current setup (e.g. change the cast to SpinnerDataModel
to your spinner model)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow