I want to write some code that receives input from two JSpinners. I want it so that I can change the values of the JSpinners and get the string value from whats shown in the Spinners. I did this by adding a ChangeListener. However in the actual application I can't change the values on the spinner, or in other words, I can't move the Spinner up or down
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SalesApplication extends JFrame {
SpinnerModel model1;
JSpinner spinner1;
SpinnerModel model2;
JSpinner spinner2;
public SalesApplication(){
model1 = new SpinnerDateModel();
spinner1 = new JSpinner(model1);
//Sub any date you want
Date firstDate1 = null;
model1 = new SpinnerDateModel(firstDate1, null, null, Calendar.DAY_OF_MONTH);
class SpinnerListener1 implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner) e.getSource();
initialDate = (String) spinner.getValue();
}
};
spinner1.addChangeListener(new SpinnerListener1());
model2 = new SpinnerDateModel();
spinner2 = new JSpinner(model2);
Date firstDate2 = null ;
model2 = new SpinnerDateModel(firstDate2, null, null, Calendar.DAY_OF_MONTH);
class SpinnerListener2 implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner) e.getSource();
endDate = (String) spinner.getValue();
}
};
spinner2.addChangeListener(new SpinnerListener2());
JPanel rightPanel = new JPanel();
rightPanel.add(spinner1);
rightPanel.add(spinner2);
add(rightPanel, java.awt.BorderLayout.EAST);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 300);
setVisible(true);
You're creating two SpinnerDateModel's with this code:
The spinner1 JSpinner only holds the first SpinnerDateModel object, and no JSpinner holds the second one, and so that object is simply ignored and is wasted. If you need to use the 2nd model, then don't even create the first one:
You've the exact same problem for the model2 variable.
The key issue above is that you seem to be equating variable with the object it holds. Once you pass the SpinnerDateModel into the JSpinner, then changing the variable that your model1 SpinnerDateModel holds will have no effect on the model object held by the JSpinner itself.