-1

I have used JButton setActionCommand(String str) function to detect event for a specific button. I want to do the same thing for a variable of type JSpinner, So i will be able to listen for a spinner that i know.

this code work for JButton

JButton myButton = new JButton("O.k");
myButton.setActionCommand("ok");

How i can translate the above code to JSpinner contexte.

abdou amer
  • 819
  • 2
  • 16
  • 43
  • 1
    Generally speaking, apply a single, dedicated, ActionListener to the JSpinner rather then relying on general purpose, check everything blob listeners. They are easier to maintain and manage. You can use the ActionEvent#getSource to determine the object which generated the event if you really need to – MadProgrammer Jan 07 '15 at 21:26
  • Let's say that i have 10 JSpinner fields, And i want to handle each one independently from others, How i will be able to know witch one of whome ? – abdou amer Jan 07 '15 at 21:29
  • Apart from the fact that `JSpinner` doesn't support the `ActionListener` API directly, you would look at the source that generated the event `java.util.EventObject` (which most of the AWT/Swing events are based on) has a `getSource` method which returns the source of the event. If you are creating single use, dedicated listeners, you can almost negate this, as you should only be focused on the control you applied it to. – MadProgrammer Jan 07 '15 at 21:43

1 Answers1

2

Here is a complete example, as #MadProgrammer said you can't directly set the action command, I used setName method instead, it's like a trick and it works.

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class MultiSpinner extends JFrame implements ChangeListener{
    JSpinner []sp ;
    public MultiSpinner(){
        sp = new JSpinner[10];

        //initialize spinners
        for(int i=0; i<sp.length; i++){
            sp[i] = new JSpinner();
            //this is important, i will be like and id of 
            //each spinner
            sp[i].setName(String.valueOf(i));
            sp[i].addChangeListener(this);
            add(sp[i]);
        }

        this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setLocationRelativeTo(null);


    }

    public void stateChanged(ChangeEvent e) {
        JSpinner temp = (JSpinner)e.getSource();
        int i = Integer.parseInt(temp.getName());//remmember? Name was like and ID
        System.out.println("Spinner "+i+" was clicked");
        //do whatever you want 
    }

    public static void main(String[]argS){
        new MultiSpinner();
    }
}
Azad
  • 5,047
  • 20
  • 38