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

Similar Messages

  • 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...

  • 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(...);

  • 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();

  • 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.

  • 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.

  • 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 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).

  • 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

  • Problems with JSpinner in Linux

    Hi,
    I'm using six JSpinners in an application I am developing but I am experiencing some problems with them. I have a JButton which, when pressed, changes the values in each of the JSpinners to a random integer.
    JButton button;
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            resetSpinners();
    private static void resetSpinners(){
        spinner1.setValue(<some random int>);
        spinner2...
    }Unfortunately, a lot of the time, the random numbers I have generated will not be applied to the spinners.
    I know that the numbers are randomly generated correctly, as I have checked this, so the number being passed to setValue(Object value) is definitely a new value.
    However, I have also tried retrieving that value again at the bottom of the setSpinners() method, and it hasn't changed. So even though a new number is definitely being passed to the method, it's not setting it all the time.
    Weirder is that sometimes it will set the value fine, others it won't. Usually, out of the six, three or four will NOT change their values.
    I don't know if the fact I am on Linux affects things, and I haven't tried this on a Windows machine yet.
    Can anyone help?
    Regards.

    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.

  • 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 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);
    }

  • Design problem with Swing

    Hi all. I've run into some design problems when trying to create a Swing app.
    I've got a non-graphical class that emulates a power supply unit. Let's call it PSUnit. I have to create a GUI for PSUnit.
    Every class designed to build a full GUI app uses PSUnit in some way (changes its voltage, displays voltage, turns it on, turns it off, etc.)
    Here's the catch. Suppose I've got a class:
    public class BuildingBlock extends JPanel {
         // code includes a JTextBox displaying
         // the current PSUnit voltage.
    }another class is created for setting the voltage:
    public class AnotherBlock extends JPanel {
         // this class contains a JSpinner and
         // a button that retrieves the JSpinner value
         // and sets it as the current voltage of
         // PSUnit
    }When the button in AnotherBlock is clicked, I must notify the BuildingBlock class that a PSUnit has changed its state so it can update it's values and display the correct data.
    I've tried to do this a few times but failed miserably, so I'm hoping you guys could help me out.
    Please note that both of the above classes have some additional code and it's not very pleasant to make one class an inner class of another. I should be able to create a "standalone" classes which, combined together, form a GUI for PSUnit.
    Thanks.

    Yes this is a common problem that many of us have when building UIs
    Here's the question: In this instance, are these two classes really independant? Could they stand alone? Often when building a GUI, it's not even that easy to answer that question, but these leads to the two ways you can solve this
    #1. Make them independent, and use listeners either using Observable / Observer or creating your own custom listeners. The advantage of this is smaller classes and more independence. The disadvantage is it's generally more complicated, especially at the design stage
    #2 (what I'd probably recommend). Make 1 GUI class "MyPSFrame", then declare your panel classes as inner classes within that class. This way, everything goes into one spot, and everything is shareable. This also makes sense if you can't have 1 of the panels without the other.

Maybe you are looking for

  • How can I manually change the height of the "Type ...

    Hi all Just got automatically installed the latest 6.22 version of skype few minutes ago and I got a few questions.  First and foremost, how can I MANUALLY change the height of the textbox, where I type the messages. I would like to make it larger, l

  • I cannot transfer music from my external hard drive to my new machine. Help!

    I backed up all of my iTunes from my old computer to my external hard drive. When I went to transfer them to my new computer, they did not show up. They can only be accessed if the hard drive is connected.  I downloaded the iTunes version for Windows

  • Re: Verizon Email Correspondence

    My uncle lives at {edited for privacy} and recently subscribed to your service. His name is {edited for privacy} and he is disabled. I look after him including getting his mail for him. He has your FIOS triple play and had been waiting for his 1st mo

  • I can't buy apps in the app catalog

    I can only see free apps in my app cataglog...I don't see any apps I can buy. My husband has the same phone and he shows free apps and apps he can buy in his app catalog. I have v1.0 Beta and he has v1.0.0 How can I get my app catalog to show both th

  • Impossible to display KF unit

    Hi, I want to display unit when i use the formulas. I have two different formulas with one of them it's impossible to display the unit. my first formula is: - (XXX) %A (YYY) No doubt for the unit Second formula: - (XXX < YYY)* XXX %A YYY+ (XXX > YYY)