how to get value from JSpinner as it updates?

297 Views Asked by At
// amount JLabels
    JLabel amount0 = new JLabel("Amount");
    JSpinner amount1= new JSpinner(new SpinnerNumberModel(0,0,50,1));
    JSpinner amount2= new JSpinner(new SpinnerNumberModel(0,0,50,1)); 
    JSpinner amount3 = new JSpinner(new SpinnerNumberModel(0,0,50,1));
    JSpinner amount4= new JSpinner(new SpinnerNumberModel(0,0,50,1));
    JSpinner amount5 = new JSpinner(new SpinnerNumberModel(0,0,50,1));
    
    //cost JLabels
  
    
    
    
    JLabel cost0 = new JLabel("Cost");
    
   
  int price = 2;
 
  int value = (Integer)(amount1.getValue());
  int total = price * value;
  JLabel cost1 = new JLabel();
   cost1.setText( "$" +total);

This code gives me the initial value of the spinner and multiplies it by price but I want it to record the updated value as it updates and multiply it with price. Any suggestions?

1

There are 1 best solutions below

2
camickr On

but I want it to record the updated value as it updates and multiply it with price.

You need to add a ChangeListener to each JSpinner.

An event will be generated when the value is changed and you can then respond to the event.

Read the section from the Swing tutorial on Detecting Spinner Value Changes for a working example.

Note, this is the way Swing works. There are different listeners that can be added to each Swing component to listen for user interaction.

The tutorial has basic example for all Swing components.

The tutorial also has a section on Implementing Listener For Commonly Handled Events that you should read.