JSpinner stateChanged Problem!!!!

Hello,
I have an Application where i am using one Jspinner and Jlist. From Jlist i am changing maximum value for the Jspinner. Here occures problem, When any Value changed in Jspinner it's call the method stateChanged().
But in method stateChanged i am doing another things, which doesnot gives me correct result.
Is there any way to prevent from the problem.Just want to know is ther any way that, when i change the maximum value from The jlist, it does not invoke method stateChange().
thank'x in Advance.

I use the setEnabled(boolean) method to achive this. Assume we have a JSpinner js, I need three lines of code js.setEnabled(false);  //switch off firing of events
js.getModel().setValue(new Integer(whatever));
js.setEnabled(true);  //switch on firing of eventsThis works for most classes that extend JComponent (JSlider, etc).

Similar Messages

  • JSpinner model problem

    Hello,
    I have an application which let you insert data of a music album. All this data goes into a database. One of the possible fields is the length of the album.
    I thought about using a JSpinner and using a SpinnerDateModel but this gives me some problems.
    To make it easy for the user i would like to enter the time in following format: mm:ss. But the problem here is that the minutes only goes to 59. But it should not be limited to 59, to make it the same as the time indicated on your music player. For example: 75minutes:24seconds.
    Is this possible with a SpinnerDateModel? Or should I use something else?
    Thx

    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • JSpinner & FocusListener Problem

    Hey all....
    Im trying to add a focusListener to a JSpinner so that when the spinner looses focus it saves its value in a database...
    But i cant seem to get it to work, i tried to add the listener on the spinner, on the editor and on the textfield from the editor and none of them work....
    what am i missing or can this be done????
    thanks

    ok heres the code
    public class CaddyTimeField extends JSpinner implements CaddyWidget
    private DataBean bean;
    private boolean isDirty = false;
    private CaddyPanel parent;
    private int dataType;
    private String propertyName;
    public CaddyTimeField()
    super();
    init();
    public CaddyTimeField(String propertyName)
    super();
    init();
    this.propertyName = propertyName;
    private void init()
    Calendar cal = new GregorianCalendar(0, 0, 0, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    SpinnerDateModel sdm = new SpinnerDateModel(cal.getTime(), null, null, Calendar.MINUTE);
    sdm.setCalendarField(Calendar.MINUTE);
    this.setModel(sdm);
    try
    this.commitEdit();
    catch (Exception e)
    Trace.traceError(e);
    JSpinner.DateEditor editor = new JSpinner.DateEditor(this, "HH:mm");
    this.addChangeListener(new javax.swing.event.ChangeListener()
    public void stateChanged(javax.swing.event.ChangeEvent e)
    setDirty(true);
    this.addFocusListener(new FocusListener()
    public void focusGained(FocusEvent e){}
    public void focusLost(FocusEvent e)
    if(isDirty)
    setBeanValues();
    this.setEditor(editor);
    private void getBeanValue()
    try
    Class c = bean.getClass();
    Method meth = c.getMethod("get" + propertyName, null);
    Object obj = meth.invoke(bean, null);
    if(obj != null)
    this.setValue(obj);
    catch(NoSuchMethodException mex){Trace.traceError(mex);}
    catch(IllegalAccessException aex){Trace.traceError(aex);}
    catch(InvocationTargetException itex){Trace.traceError(itex);}
    catch(Exception ex){Trace.traceError(ex);}
    public void setBeanValues()
    try
    Time time = new Time(((Date)this.getValue()).getTime());
    Class c = bean.getClass();
    java.lang.reflect.Method meth = null;
    Class[] args = { Class.forName("java.sql.Time") };
    meth = c.getMethod("set" + propertyName, args);
    Object[] args2 = { time };
    Object obj = meth.invoke(bean, args2);
    catch(ClassNotFoundException cex){Trace.traceError(cex);}
    catch(NoSuchMethodException mex){Trace.traceError(mex);}
    catch(IllegalAccessException aex){Trace.traceError(aex);}
    catch(java.lang.reflect.InvocationTargetException itex) {Trace.traceError(itex);}
    catch(Exception ex){Trace.traceError(ex);}
    public void setBean(DataBean bean)
    this.bean = bean;
    if(bean != null)
    getBeanValue();
    public void setParent(CaddyPanel parent)
    this.parent = parent;
    public void setDirty(boolean isDirty)
    this.isDirty = isDirty;
    if(parent != null)
    parent.setDirty(true);
    }

  • JSpinner Using Problem

    Hey guys, I'm new to the JAVA programming world and i have a little problem...
    I read the API of the JSpinnerNumberModel but i don't know, using NetBeans, how to set the "only positivie values range" for the JSpinner...
    I know is a noob question but i hope someone will help me...Thanks!!

    According to this posting the OP has the answer:
    http://forum.java.sun.com/thread.jspa?threadID=5200948

  • Jspinner weird problem

    Hi all,
    I have this weird problem with Jspinners when I try to run this code. When I run it, the second spinner shows the date (while the first one only shows the time) and they are both larger than they are supposed to be (try resizing after it shows up)
    Any help would be greatly appreciated.
    // CODE STARTS HERE ////////////////////////////////
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    public class Test {
         public static void main(String args[]) {
              TimeSpinner spin1 = new TimeSpinner();
              TimeSpinner spin2 = new TimeSpinner();
              JFrame frame = new JFrame();
                   frame.getContentPane().setLayout(new FlowLayout());
                   frame.getContentPane().add(spin1);
                   frame.getContentPane().add(spin2);
                   frame.setSize(300,300);
                   frame.show();
    class TimeSpinner extends JSpinner {
         public TimeSpinner() {
              super();
              // spinner date model
              SpinnerDateModel sdm = new SpinnerDateModel();
              sdm.setCalendarField(Calendar.MINUTE);
              this.setModel(sdm);
              try {
                   this.commitEdit();
              } catch (Exception e) {
                   e.printStackTrace();
              JSpinner.DateEditor de = (JSpinner.DateEditor)this.getEditor();
              de.getFormat().applyPattern("hh:mm a");
         public void setFixedSize(int width, int height) {
              Dimension fixedDimension = new Dimension(width, height);
              this.setMinimumSize(fixedDimension);
              this.setMaximumSize(fixedDimension);
              this.setPreferredSize(fixedDimension);

    The problem is in the format. The format supplied by the standard API does exactly what you described. The alternative is to create your own format or (better) your own formatter.
    I ended up creating my own DateSpinner which is not too difficult.
    Cheers,
    Didier

  • JSpinner DateEditor problem

    Hi,
    I have a problem with the JSpinner. When I set a SpinnerDateModel into it, and not define the "full"(eg. MM/dd/yyyy HH: mm a) date format string, then the JSpinner or DateEditor reset the undefined part of time.
    eg.
    -If I not define in the date format string the date part "MM/dd/yyyy" then the JSpinner or the DateEditor is reset the date value of JSpinner to 1970,1,1
    -If I not define in the date format string the time part "HH: mm a" then the JSpinner or the DateEditor is reset the time value of JSpinner to 12:00 AM
    What can I do for not reset the not defined/showed/ part of the time?
    thx.

    The problem is in the format. The format supplied by the standard API does exactly what you described. The alternative is to create your own format or (better) your own formatter.
    I ended up creating my own DateSpinner which is not too difficult.
    Cheers,
    Didier

  • JSpinner format problem

    Hi guys,
    I am trying to create a JSpinner with the following format HH:MM but it is not working. The spinner keeps displaying both the date and the time. Can somebody tell me what's wrong with my code? I would really appreciate it ...
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class Test {
    public static void main(String[] args) {
              Frame f = new Frame();
              f.setLayout(new BorderLayout());
              f.add(new TimeSpinner(), BorderLayout.WEST);
              f.add(new TimeSpinner(), BorderLayout.EAST);
    f.setVisible(true);
              f.pack();
    class TimeSpinner extends JSpinner {
         public TimeSpinner() {
              super();
              // spinner date model
              SpinnerDateModel sdm = new SpinnerDateModel();
              sdm.setCalendarField(Calendar.MINUTE);
              this.setModel(sdm);
              try {
                   this.commitEdit();
              } catch (Exception e) {
                   e.printStackTrace();
              JSpinner.DateEditor de = (JSpinner.DateEditor)this.getEditor();
              de.getFormat().applyPattern("hh:mm a");

    Hey you were close, try this:
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class Test{
         public static void main(String[] args) {
              Frame f = new Frame();
              f.setLayout(new BorderLayout());
              f.add(new TimeSpinner(), BorderLayout.WEST);
              f.add(new TimeSpinner(), BorderLayout.EAST);
              f.setVisible(true);
              f.pack();
    class TimeSpinner extends JSpinner {
         public TimeSpinner() {
              super();
              // spinner date model
              SpinnerDateModel sdm = new SpinnerDateModel();
              sdm.setCalendarField(Calendar.MINUTE);
              this.setModel(sdm);
              try {
                   this.commitEdit();
              } catch (Exception e) {
                   e.printStackTrace();
              JSpinner.DateEditor editor = new JSpinner.DateEditor(
    this, "hh:mm a");
    this.setEditor(editor);
    }

  • JSpinner problem

    I've searched google and looked everywhere in the API and tutorial before posting here. I don't see what the problem is. I added a JSpinner to my interface, when I add the changelistener it doesn't update. Like the numbers in the spinner don't change when i click the arrows. They work fine without the changelistener, but with it they don't work. The weird thing is that in the stateChanged function I put some debug code, and the values are changing, but not visibly in the spinner.
    here is my declaration:
             CurrentRecopy = new JSpinner(new SpinnerNumberModel(0, 0, 9, 1));          
          CurrentRecopy.addChangeListener(this);here is my stateChanged code:
           public void stateChanged(ChangeEvent e) {
             SaveItems();
           public void SaveItems(){
             int NumRecopy = CurrentRecopy.getNumber().intValue();
             if(debug) display.append(NumRecopy + " ");
             int NumTime = current_time.getNumber().intValue();
             int NumOfEffects = no_of_times.getNumber().intValue();
             if(debug) display.append(NumTime + " ");
               //CurrentRecopy.setValue(NumTime);
             data[NumRecopy].NumberOfEffects = NumOfEffects;
             data[NumRecopy].TimeMultipliersMain[((NumTime*2)-2)] = Integer.parseInt(Time_a_input.getText());
             data[NumRecopy].TimeMultipliersMain[((NumTime*2)-1)] = Integer.parseInt(Time_b_input.getText());
             data[NumRecopy].TimeAccMain[(NumTime-1)] = Integer.parseInt(MainAcc.getText());
             data[NumRecopy].TimedEffectMain[(NumTime-1)] = EnterMainEffect.getText();
             data[NumRecopy].AlternateEffects = Alt_active_box.isSelected();
             data[NumRecopy].NumberOfAlternateEffects = total_alt_time.getNumber().intValue();
             data[NumRecopy].TimeMultipliersAlt[((NumTime*2)-2)] = Integer.parseInt(Alt_a_input.getText());
             data[NumRecopy].TimeMultipliersAlt[((NumTime*2)-1)] = Integer.parseInt(Alt_b_input.getText());
             data[NumRecopy].TimeAccAlt[(NumTime-1)] = Integer.parseInt(AltAcc.getText());
             data[NumRecopy].TimedEffectAlt[(NumTime-1)] = EnterAltEffect.getText();
             data[NumRecopy].Trailing = TrailingBox.isSelected();
             data[NumRecopy].TrailingTime = Integer.parseInt(TrailingTime.getText());
             data[NumRecopy].TrailingAcc = Integer.parseInt(TrailingAcc.getText());
             data[NumRecopy].TrailingEffect = TrailingEffect.getText();
             data[NumRecopy].Leading = LeadBox.isSelected();
             data[NumRecopy].LeadingTime = Integer.parseInt(LeadTime.getText());
             data[NumRecopy].LeadingAcc = Integer.parseInt(LeadAcc.getText());
             data[NumRecopy].LeadingEffect = LeadEffect.getText();
          }If you think it'd help I could post the entire program here. I'm using JDK 5. I'm not sure if that effects it or not.
    Thanks.

    public void SaveItems()
      if(checkFields())
             int NumRecopy = CurrentRecopy.getNumber().intValue();
             if(debug) display.append(NumRecopy + " ");
             int NumTime = current_time.getNumber().intValue();
             int NumOfEffects = no_of_times.getNumber().intValue();
             if(debug) display.append(NumTime + " ");
              ...all of saveItems() code wrapped up in the if()
      else //error message, incomplete data
    public boolean checkFields()
      if(textField1.getText().equals("")) return false;
      if(textField2.getText().equals("")) return false;
      ...all the way to
      if(textField10.getText().equals("")) return false;
      return true;
    }but this will only check for empty fields - you are doing Integer.parseInt(), so will
    probably have the same problem if non-parseable characters are entered.
    it might be easier to use JFormattedTextFields, with a default value already inserted

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • JSpinner problem when extending AbstractSpinnerModel

    Hi,
    I have a problem with a class that extends AbstractSpinnerModel.
    My class is
      class MaxSpinnerModel extends AbstractSpinnerModel {
        Double value;
        public Object getNextValue() {
          // deltaSP is a JSpinner from wich I want to get the value (see rules below)
          value = new Double(value.doubleValue() + ((Double)deltaSP.getValue()).doubleValue());
          return value;
        public Object getPreviousValue() {
          // deltaSP is a JSpinner from wich I want to get the value (see rules below)
          value = new Double(value.doubleValue() - ((Double)deltaSP.getValue()).doubleValue());
          return value;
        public Object getValue() {
          if (value == null) {
            value = new Double(MAX_INI);
          return value;
        public void setValue(Object value) {
          if ((value == null) || !(value instanceof Double)) {
            throw new IllegalArgumentException("illegal value");
          if (!value.equals(this.value)) {
            this.value = (Double)value;
            fireStateChanged();
      }I have two problems:
    -1 the editor is not editable ( when trying to put an Editor like a JFormattedTextField,
    values are not visible)
    -2 the most important so far, pressing the up or down button of the JSpinner do not
    change the value on the screen while the method getNext or PreviousValue are
    called.
    What should I do to fix these two bugs?
    I need to implement my spinner model because I would like to
    bind dynamically the increment and decrement of the different spinner.
    I must have the following rules for next and previous values:
    -1 min
    increment/decrement of min is delta and incrmenting min, should mofiy
    middle (middle = min+max/2), and delta (delta = max -min), mas does not
    change
    -2 max same as min
    -3 delta quit complicated let's say, increment/decrement is *2.0 and *0.5,
    middle does not change, min and max change with the rules
    min = middle - delta/2, max = middle + delta/2
    -4 middle increment/decrement is delta, min and max are simply shited of delta

    Hello,
    I managed to solve the second question on my own.
    I created another InfoSource and another Update rule to the InfoObject with flexible updating. It doesn’t erase the old data anymore.
    Although I still have problems with the time characteristics.
    Thank you,
    Best regards

  • JSpinner problems with alignment of text

    I experience problems with the alignment of the text within the spinner. I read a few topics on this forum. Many answers point to the solution of grabbing the JFormattedTextField from the spinner and call the setHorizontalAlignment(int) method. Seems hat doesn't work for me.
    Here is the code I wrote:
    SpinnerDateModel dateModel = new SpinnerDateModel();
    JSpinner dateSpinner = new JSpinner(dateModel);
    JSpinner.DateEditor dateEditor = (JSpinner.DateEditor)dateSpinner.getEditor();
    JFormattedTextField tf = dateEditor.getTextField();
    tf.setHorizontalAlignment(JFormattedTextField.RIGHT);
    maybe I am missing something. Please help!
    Thank You in advance.

    I'm not sure if this is the solution, but the getTextField() Method should be called on a JSpinner, rather than a SpinnerDateModel. I took this Method from the Swing Tutorial and made it static, so i could use it anywhere:
    public static JFormattedTextField getTextField(JSpinner spinner) {
              JComponent editor = spinner.getEditor();
              if (editor instanceof JSpinner.DefaultEditor) {
                   return ((JSpinner.DefaultEditor)editor).getTextField();
              } else {
                   System.err.println("Unexpected editor type: "
                                          + spinner.getEditor().getClass()
                                          + " isn't a descendant of DefaultEditor");
                   return null;
         }Besides, setting an Editor for this JSpinner is not neccesary, because it is chosen automaticaly. You only need to do so if you have implemented a custom SpinnerModel.
    Hope this was any help...

  • Problems in JSpinner

    Hi,
    I am trying to create timefield using JSpinner similar to TimeField in
    Date/Time Properties dialog in Microsoft Windows. Here is the code i have
    written
    import javax.swing.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class MySpinner {
    JFormattedTextField tf;
    public MySpinner(){
    JFrame frame = new JFrame("Spinner");
    frame.setDefaultCloseOperation(3);
    final SpinnerDateModel model = new SpinnerDateModel();
    JSpinner spinner = new JSpinner(model);
    JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner,"HH:ss:mm");
    spinner.setEditor(editor);
    tf =((JSpinner.DateEditor)spinner.getEditor()).getTextField();
    tf.setEditable(true);
    tf.setBackground(Color.white);
    tf.setSelectionColor(Color.blue);
    tf.setSelectedTextColor(Color.white);
    DefaultFormatterFactory factory
    =(DefaultFormatterFactory)tf.getFormatterFactory();
    DateFormatter formatter = (DateFormatter)factory.getDefaultFormatter();
    formatter.setAllowsInvalid(false);
    frame.getContentPane().add(spinner, BorderLayout.SOUTH);
    frame.pack();
    frame.show();
    public static void main (String args[]) throws Exception {
    new MySpinner();
    It works just fine when i use up/down keys or spinner at the right to change
    the time. But when i try to
    modify the time by editing the TimeField it is not behaving as expected.
    I want it such that Timefield should allow user to change the time using
    Spinner as well as by editing the
    timefield. But it should not allow the user to enter invalid time.
    Please give me your suggestions. Am I missing something here?
    Thanks in advance.
    Abhijeet

    Hi J�rg,
    Thanks for your reply.
    I wrote a standalone version simulating the problem I have and -- guess what -- it worked fine.
    The only feasible difference between the two programs is that for the demo program I coded the layout and placement of the components myself, whereas with the problem code, I used IntelliJ's GUI builder, which uses its own layout manager. This must have something to do with the problem.
    However, I have managed to botch a fix -- first I set the JSpinners' values to 0, THEN set them to the random numbers. Weird, but works.
    Thanks again, though.
    Regards.

  • Please help with JSpinner problem

    The only way that I know of to get access to the fireStateChanged()
    method is to extend JSpinner because it's a protected method in
    the JSpinner class. However, when I do that and invoke a
    fireStateChanged I get a stack overflow with no other information.
    java.lang.StackOverflowError
    is all I get? Any ideas on what I'm doing wrong and how to fix
    it?
    I don't understand what can go wrong because it just a simple
    extends class as follows:
    setup code:
              Integer value = new Integer(period);
              Integer min = new Integer(3);
              Integer max = new Integer(99);
              Integer step = new Integer(1);
              model = new SpinnerNumberModel(value, min, max, step);
              period = model.getNumber().intValue();
              periodSpinner = new PeriodSpinner(model);
              periodSpinner.addChangeListener(this);class code (inner class):
         private class PeriodSpinner extends JSpinner {
              public PeriodSpinner(SpinnerModel model) {
                   super(model);
              protected void fireStateChanged() {
                   super.fireStateChanged();
         }ChangeListener:
         public void stateChanged(ChangeEvent changeEvent) {
              Object changeEvtSrc = changeEvent.getSource();
              if(changeEvtSrc == (Object)periodSpinner) {
                   period = model.getNumber().intValue();
                   // o next statement cause a stack over flow
                   periodSpinner.fireStateChanged();

    The only way that I know of to get access to the fireStateChanged()
    method is to extend JSpinner because it's a protected method in
    the JSpinner class. However, when I do that and invoke a
    fireStateChanged I get a stack overflow with no other information.
    java.lang.StackOverflowError
    is all I get? Any ideas on what I'm doing wrong and how to fix
    it?
    I don't understand what can go wrong because it just a simple
    extends class as follows:
    setup code:
              Integer value = new Integer(period);
              Integer min = new Integer(3);
              Integer max = new Integer(99);
              Integer step = new Integer(1);
              model = new SpinnerNumberModel(value, min, max, step);
              period = model.getNumber().intValue();
              periodSpinner = new PeriodSpinner(model);
              periodSpinner.addChangeListener(this);class code (inner class):
         private class PeriodSpinner extends JSpinner {
              public PeriodSpinner(SpinnerModel model) {
                   super(model);
              protected void fireStateChanged() {
                   super.fireStateChanged();
         }ChangeListener:
         public void stateChanged(ChangeEvent changeEvent) {
              Object changeEvtSrc = changeEvent.getSource();
              if(changeEvtSrc == (Object)periodSpinner) {
                   period = model.getNumber().intValue();
                   // o next statement cause a stack over flow
                   periodSpinner.fireStateChanged();

  • When that occurs a stateChanged event on a jspinner?

    Hi,
    I am using a stateChanged in a jspinner.
    I expect that every time jspinner.setvalue occurs, then stateChanged in the jspinners occurs to. But debugging the code, it seems that those two things are not so linked...
    Can some one provide me more info about that?

    This works fine for me:
    import javax.swing.*;
    import javax.swing.event.*;
    public class JSpinnerTest {
         public JSpinnerTest(){
              JFrame frame = new JFrame("Spinner Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JSpinner spinner = new JSpinner();
              spinner.addChangeListener(new ChangeListener(){
                   @Override
                   public void stateChanged(ChangeEvent e) {
                        System.out.println("Change Event!");
              frame.add(spinner);
              frame.setSize(100, 100);
              frame.setVisible(true);
              System.out.println("Setting value...");
              spinner.setValue(50);
              System.out.println("...Done setting value.");
         public static void main(String [] args){
              new JSpinnerTest();
    }

  • Problems calling JSlider.setValue() from ChangeListener.stateChanged()

    G'day,
    I want to restrict the value a JSlider can take on according to the value of another JSlider, for example I have two sliders, min and max and I want to ensure that min.getValue() <= max.getValue().
    Fairly straightforward, here's the code to do it:
    public class SliderProblem
            extends JFrame
        public SliderProblem()
            // Set-up sliders.
            final JSlider min = new JSlider(0, 1000, 0);
            final JSlider max = new JSlider(0, 1000, 1000);
            min.setMajorTickSpacing(200);
            max.setMajorTickSpacing(200);
            min.setMinorTickSpacing(50);
            max.setMinorTickSpacing(50);
            min.setPaintLabels(true);
            min.setPaintTicks(true);
            max.setPaintLabels(true);
            max.setPaintTicks(true);
            /* This fixes the problem.
           min.setSnapToTicks(true);
           max.setSnapToTicks(true); */
            // Layout frame.
            final Container pane = getContentPane();
            pane.setLayout(new GridLayout(0, 1));
            pane.add(min);
            pane.add(max);
            // Create listener.
            final ChangeListener listener = new ChangeListener()
                public void stateChanged(final ChangeEvent e)
                    final Object source = e.getSource();
                    if (min.equals(source))
                        // Ensure min <= max.
                        final int limit = max.getValue();
                        if (min.getValue() > limit)
                            min.setValue(limit);
                    else if (max.equals(source))
                        // Ensure max >= min.
                        final int limit = min.getValue();
                        if (max.getValue() < limit)
                            max.setValue(limit);
            // Listen up.
            min.addChangeListener(listener);
            max.addChangeListener(listener);
        public static void main(String args[])
            final SliderProblem frame = new SliderProblem();
            frame.pack();
            frame.setVisible(true);
    }The problem is that even though the ChangeListener calls JSlider.setValue(limit) the thumb of the JSlider is not repositioned to the limit value.
    If I resize the JFrame holding the sliders then the thumbs are correctly repainted.
    I've tried calling repaint() explicitly (including within SwingUtilities.invokeLater()), and working directly with the BoundedRangeModel underlying the JSliders but all to no avail.
    The only thing that does work is to call setSnapToTicks(true). However, for the specific application I'm working on I need setSnapToTicks(false).
    All suggestions appreciated.
    Thanks,
    Chris.

    Ok, I didn't understand what you exactly want.
    So change your listener like this:
    public void stateChanged(final ChangeEvent e)
         final Object source = e.getSource();
         if (min == source)
              if (min.getValueIsAdjusting())
                   return;
              // Ensure min <= max.
              final int limit = max.getValue();
              if (min.getValue() > limit)
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             min.setValue(limit);
         else if (max == source)
              if (max.getValueIsAdjusting())
                   return;
              // Ensure max >= min.
              final int limit = min.getValue();
              if (max.getValue() < limit)
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             max.setValue(limit);                                        
    }

Maybe you are looking for

  • My mini's fan murdered its host - help!

    Okay, so I guess this is a 2005 Mac Mini, using...Tiger, I believe? Anyways, it had been running pretty badly for a while (very slow, fan always going) but didn't seem in terrible danger as it was. I was backing up my files, irony of ironies, when al

  • Unable to see option interactive

    hello all, i am unable to see the option interactive, in web intelligence options for select view format and also the select a report panel is missing in the web intelligence document preferences. i am using BO XI r2. thanks

  • How could insert a Watermark or Copy Right logo in Aperture 2?

    Hello, Would it be possible to insert a copy right logo or watermark in a version modified & edited in Aperture 2? Or that is not available in Aperture 2? Regards

  • Oracle Tutor Help Needed

    Hi We need help creating desktop manuals and workflows with Oracle Tutor. Does anyone know any consultants who might also be technical writers who can help out in our New York office? Much Appreciated, Lynn Redgrad PFI Pharamaceuticals

  • Flex Library Project(SWC) with css and image assets

    HI, I want to create a flex library project with images and css. I shall use that swc with other flex applications. I wand to use those css and images from the swc. Is it possible? Can you please explain in detail. Thanks Nirmal