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.

Similar Messages

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

  • Problem with JComboBox in aTable Cell

    I try to put JComboBox in JTableCell,
    what i want to do is something like this...
    Question | Answer |
    1. what is your favourite | a. Pizza |
    food? | b. Hot Dog |
    2. what is your favourite | a. red |
    color? | b. blue |
    Object[][] data = {
    {"1.What is your favourite food?", new AnswerChoices(new String[]{"a.Pizza","b.Hot Dog"})},
    {"2.What is your favourite color?", new AnswerChoices(new String[]{"a.red","b.blue"})}
    here my code;
    //class AnswerChoicesCellEditor
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    import de.falcom.table.*;
    public class AnswerChoicesCellEditor extends AbstractCellEditor implements TableCellEditor{
         protected JComboBox mComboBox;
    public AnswerChoicesCellEditor(){
         mComboBox = new JComboBox();
         mComboBox.addActionListener(this);
         mComboBox.setEditable(false);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){
         if(value instanceof AnswerChoices){
              AnswerChoices a = (AnswerChoices)value;
              String[] c = a.getChoices();
              mComboBox.removeAllItems();
              for(int i=0; i < c.length; i++)
                   mComboBox.addItem(c);
                   mComboBox.setSelectedIndex(a.getAnswer());
         return mComboBox;
    public Object getCellEditorValue(){
         int nchoices = mComboBox.getItemCount();
         String[] c = new String[nchoices];
         for(int i = 0; i<nchoices; i++){
              c[i] = mComboBox.getItemAt(i).toString();
         return new AnswerChoices(c,mComboBox.getSelectedIndex());
         //return mComboBox.getSelectedItem(); //here i get but after selection there is no comboBox in tableCell
    //the Renderer class
    import javax.swing.table.TableCellRenderer;
    import javax.swing.*;
    import java.awt.Component;
    public class AnswerChoicesCellRenderer extends JComboBox implements TableCellRenderer {
         private Object curValue;
    /** Creates new AnswerChoiceCellRenderer */
    public AnswerChoicesCellRenderer() {
    setEditable(false);
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
    if (value instanceof AnswerChoices) {
    AnswerChoices nl = (AnswerChoices)value;
    String[] tList = nl.getChoices();
    if (tList != null) {
    removeAllItems();
    for (int i=0; i<tList.length; i++)
    addItem(tList[i]);
         setSelectedIndex(AnswerChoices.getAnswer());
         //this.setSelectedItem();
    //return this;
    //this.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (table != null)
    if (table.isCellEditable(row, column))
    setForeground(CellRendererConstants.EDITABLE_COLOR);
    else
    setForeground(CellRendererConstants.UNEDITABLE_COLOR);
              setBackground(table.getBackground());
    return this;
    public class AnswerChoices {
         static int ans = 0;
         String[] choices ;
    public AnswerChoices(String[]c,int a){
              choices = c;
              ans          = a;
    public AnswerChoices(String[] c){
              this(c,0);
    public String[] getChoices(){
         return choices;
    public void setAnswer(int a){
         ans = a;
    public static int getAnswer(){
         return ans;
    //the TableModel i used in my app
    import java.awt.Color;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    import javax.swing.*;
    public class FAL_Table extends JTable {
    /** Creates new FAL_Table */
    public FAL_Table(DefaultTableModel dtm) {
    super(dtm);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setBackground(java.awt.Color.white);
    setDefaultCellEditorRenderer();
    private void setDefaultCellEditorRenderer(Class forClass, TableCellEditor editor, TableCellRenderer renderer) {
         setDefaultEditor(forClass, editor);
         setDefaultRenderer(forClass, renderer);
         private void setDefaultCellEditorRenderer() {
              // Setting default editor&renderer of Boolean
              setDefaultCellEditorRenderer(Boolean.class, new BooleanCellEditor(), new BooleanCellRenderer());
              //Setting default editor&renderer of ComboBox
              setDefaultCellEditorRenderer(JComboBox.class, new ComboBoxCellEditor( ),new ComboBoxRenderer());
              // Number class
              // Setting default editor&renderer of java.math.BigDecimal
              setDefaultCellEditorRenderer(java.math.BigDecimal.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.math.BigInteger
              setDefaultCellEditorRenderer(java.math.BigInteger.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.lang.Byte
              setDefaultCellEditorRenderer(Byte.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Double
              setDefaultCellEditorRenderer(Double.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Float
              setDefaultCellEditorRenderer(Float.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Integer
              setDefaultCellEditorRenderer(Integer.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Long
              setDefaultCellEditorRenderer(Long.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Short
              setDefaultCellEditorRenderer(Short.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of String
              setDefaultCellEditorRenderer(String.class,new StringCellEditor(), new StringCellRenderer());
              // Setting default editor&renderer of FileName
              setDefaultCellEditorRenderer(FileName.class,new FileNameCellEditor(), new FileNameCellRenderer());
              // Setting default editor&renderer of Color
              setDefaultCellEditorRenderer(Color.class,new ColorCellEditor(), new ColorCellRenderer());
              setDefaultCellEditorRenderer(AnswerChoices.class, new AnswerChoicesCellEditor(), new AnswerChoicesCellRenderer());
              setDefaultCellEditorRenderer(JSpinner.class, new SpinnerCellEditor(), new SpinnerRenderer());
    public Class getCellClass(int row,int col) {
    TableModel model = getModel();
    if (model instanceof FAL_TableModel) {
    FAL_TableModel ptm = (FAL_TableModel)model;
    return ptm.getCellClass(row,convertColumnIndexToModel(col));
    return model.getColumnClass(convertColumnIndexToModel(col));
    public TableCellRenderer getCellRenderer(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellRenderer renderer = tableColumn.getCellRenderer();
    if (renderer == null) {
    renderer = getDefaultRenderer(getCellClass(row,column));
    return renderer;
    public TableCellEditor getCellEditor(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellEditor editor = tableColumn.getCellEditor();
    if (editor == null) {
    editor = getDefaultEditor(getCellClass(row,column));
    return editor;
    import javax.swing.table.*;
    import java.util.Vector;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    public class FAL_TableModel extends DefaultTableModel implements TableModel {
    public FAL_TableModel() {
    this((Vector)null, 0);
    public FAL_TableModel(int numRows, int numColumns) {
    super(numRows,numColumns);
    public FAL_TableModel(Vector columnNames, int numRows) {
    super(columnNames,numRows);
    public FAL_TableModel(Object[] columnNames, int numRows) {
    super(convertToVector(columnNames), numRows);
    public FAL_TableModel(Vector data, Vector columnNames) {
    setDataVector(data, columnNames);
    public FAL_TableModel(Object[][] data, Object[] columnNames) {
    setDataVector(data, columnNames);
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    Object obj = getValueAt(row,col);
    if (col != 1){
    return false;
         }else{
              return true;
    public Class getCellClass(int row,int col) {
    Object obj = getValueAt(row,col);
    if (obj != null)
         return obj.getClass();
         else
         return Object.class;
    public Object getCellValue(int row,int col) {
    Object obj = getValueAt(row,col);
              return obj;      
    my problem is, when i select an item from one of the comboBox in the table the value of the other cells changes too and i have the same problem with JSpinner.
    please help i am stuck
    Gebi

    and when i try to get the current value oa a cell it returns the Component class like this
    AnswerChoices@bf1f20 ...

  • Help needed for jspinner

    Its the third time i am posting the same qusetion with out any sucess. Some one may knew the answer . Please help me
    I got a jspinner , a text box and a button in my frame. i valdiate the values entered in the text field and if an invalid value is entered an error dialog is show . Now if I enter an invalid value in the text field and click the buttons along with the jspinner, the error dialog is displayed and focus is returned back to the textbox,but the problem is that the spinner button remains in a pressed condition as a result the number keeps of increasing / decreasing in jspinner (if you click both the buttons , it will increase and decrease at the same time). I am including the code also.
    I have searched through the forums and couldnt find a solution. Is it a problem with jspinner or my code?
    thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class focus extends JFrame implements FocusListener {
    JPanel pan1=new JPanel();
    JButton btn1=new JButton("OK");
    JButton btn2=new JButton("Cancel");
    JTextField txt1=new JTextField(10);
    SpinnerCircularNumberModel model=new SpinnerCircularNumberModel(50);
    JSpinner spin=new JSpinner(model);
    focus() {
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(txt1);
    getContentPane().add(btn1);
    getContentPane().add(btn2);
    getContentPane().add(spin);
    txt1.addFocusListener(this);
    setSize(200,200);
    setVisible(true);
    pack();
    public void focusGained(FocusEvent fe) {
    public void focusLost(FocusEvent fe) {
    try {
    Integer.parseInt(txt1.getText());
    } catch ( NumberFormatException nfe) {
    JOptionPane.showMessageDialog(this, "Invalid value","ERROR", JOptionPane.ERROR_MESSAGE);
    txt1.requestFocus();
    public static void main(String arg[]) {
    focus f=new focus();
    class SpinnerCircularNumberModel extends SpinnerNumberModel {
    public SpinnerCircularNumberModel(int init) {
    super(init,0,99,1);
    public Object getNextValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==99)
    return (new Integer(0));
    else
    return (new Integer(++val));
    public Object getPreviousValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==0)
    return (new Integer(99));
    else
    return (new Integer(--val));

    i found out the answer . It was a bug with the jspinner.
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4840869

  • Funny behaviour of JSpinner

    please help me solving this peculiar problem with jspinner . I got a jspinner , a text box and a button of my frame.i have written code to valdiate the value entered in text field. If an invalid value is entered an error dialog is show. and focus is returned to the textbox.. Now if I enter an invalid value in the text field and click the small buttons in jspinner, the error dialog is displayed and focus is returned back to the textbox but the problem is that the spinner button remains in a pressed condition as a result the number keeps of increasing / decreasing in jspinner (if you click both the buttons , it will increase and decrease at the same time). I am including the code also.
    I have searched through the forums and find that its a problemm with the look and feel. Can any one suggest a simple method to rectify it ??
    thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class focus extends JFrame implements FocusListener {
    JPanel pan1=new JPanel();
    JButton btn1=new JButton("OK");
    JButton btn2=new JButton("Cancel");
    JTextField txt1=new JTextField(10);
    SpinnerCircularNumberModel model=new SpinnerCircularNumberModel(50);
    JSpinner spin=new JSpinner(model);
    focus() {
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(txt1);
    getContentPane().add(btn1);
    getContentPane().add(btn2);
    getContentPane().add(spin);
    txt1.addFocusListener(this);
    setSize(200,200);
    setVisible(true);
    pack();
    public void focusGained(FocusEvent fe) {
    public void focusLost(FocusEvent fe) {
         try {
              Integer.parseInt(txt1.getText());
         } catch ( NumberFormatException nfe) {
              JOptionPane.showMessageDialog(this, "Invalid value","ERROR", JOptionPane.ERROR_MESSAGE);               
    txt1.requestFocus();
    public static void main(String arg[]) {
    focus f=new focus();
    class SpinnerCircularNumberModel extends SpinnerNumberModel {
    public SpinnerCircularNumberModel(int init) {
    super(init,0,99,1);
    public Object getNextValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==99)
    return (new Integer(0));
    else
    return (new Integer(++val));
    public Object getPreviousValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==0)
    return (new Integer(99));
    else
    return (new Integer(--val));

    I used it in the following way:
    class OptEmSpinner extends EmSpinner{
    public OptEmSpinner() {
    public interface RevertListener extends EventListener
         * The value has been Reverted to a the old valid value.
         * @param source is this bean.
         public void valueReverted(Component source);
    public static class OptNumberEditor extends NumberEditor {
         public OptNumberEditor(JSpinner spinner) {
         super(spinner);
         public void propertyChange(PropertyChangeEvent e)
              OptEmSpinner spinner = (OptEmSpinner)getSpinner();
              if (spinner == null) return; // Indicates we aren't installed anywhere.
              Object source = e.getSource();
              String name = e.getPropertyName();
              if ((source instanceof JFormattedTextField) && "value".equals(name))
                   Object lastValue = spinner.getValue();
                   // Try to set the new value
                   try
                        spinner.setValue(getTextField().getValue());
                   catch (IllegalArgumentException iae)
                        // Spinner didn't like new value, reset
                        try
                             ((JFormattedTextField)source).setValue(lastValue);
                        catch (IllegalArgumentException iae2)
                             spinner.fireValueReverted(e);
                             // Still bogus, nothing else we can do, the
                             // SpinnerModel and JFormattedTextField are now out
                             // of sync.
              else
                   spinner.fireValueReverted(e);
    protected JComponent createEditor(SpinnerModel model) {
         if (model instanceof SpinnerNumberModel) return new OptNumberEditor((JSpinner)this);
         return super.createEditor(model);
    private void fireValueReverted(PropertyChangeEvent e)
         Object source = e.getSource();
         String name = e.getPropertyName();
    // JFormattedTextField jft = ((DefaultEditor) getEditor()).getTextField();
         JComponent jft = ((DefaultEditor)getEditor()).getTextField();
         if ((source instanceof JFormattedTextField) && "editValid".equals(name))
              if (!jft.hasFocus()) // ensure lost focus
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = listeners.length - 2; i >= 0; i -= 2)
                        if (listeners[i] == RevertListener.class)
                             ((RevertListener)listeners[i + 1]).valueReverted(jft);
    public void addRevertListener(RevertListener revListener)
         listenerList.add(OptEmSpinner.RevertListener.class, revListener);
    public void removeRevertListener(RevertListener revListener)
         listenerList.remove(OptEmSpinner.RevertListener.class, revListener);
    USED in class:
    public class MyPanel extends JPanel implements OptEmSpinner.RevertListener
    LISTENER IMPLEMENTATION:
    public void valueReverted(Component source)
              Runnable runnable =
                        new Runnable()
                             public void run()
                                  EmOptionPane.showSemiModalMessageDialog(
                                       parent,
                                       sRes.getString("Invalid Value: Old value will be retained."),
                                       sRes.getString("Invalid Input"),
                                       JOptionPane.WARNING_MESSAGE
    //                              dialogShown = false;
                   SwingUtilities.invokeLater(runnable);
    You can modify or pick from this......
    Regards
    Mohit

  • JSpinner generates multiple change events

    Having problem with JSpinner generating two change events when using double values in the model. It looks like the number editor formatter is causing an event to be generated before it rounds and after it rounds.
              final JSpinner s = new JSpinner(
                   new SpinnerNumberModel(20.0, 0.0, 100.0, 0.0025));
              s.setEditor(new JSpinner.NumberEditor(s, "###0.000"));
              // When value is changed, need to process certain events.
              s.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent event) {
                        System.out.println("New Value:" + s.getValue());
              JFrame f = new JFrame("Test Spinner");
              f.getContentPane().setLayout(new java.awt.BorderLayout());
              f.getContentPane().add(s, java.awt.BorderLayout.CENTER);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(331, 254);
              f.setVisible(true);If you modify the editor to use the following format, you can see that the two events are not generated because the formatter does not need to round:
    "###0.000##############"I have to actually modify the model to round the incremented or decremented value to a precision where the formatter will not round the value, which is a pretty messy solution.
    Are there any other workarounds (or solutions) that are a little more elegant?
    Thanks.

    Thanks for the reply.
    This workaround reduces the amount of duplicate events, but I still see double change events that make it through the filter.
    You have to filter events to get the relevant one.
    See :
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=476
    5246
    import java.awt.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class SpinnerEvents{
    JSpinner s;
    JSpinner.NumberEditor jne;
    DecimalFormat dfmt;
    public SpinnerEvents() {
    s = new JSpinner(new SpinnerNumberModel(20.0,
    0.0, 0.0, 100.0, 0.0025));
    jne = new JSpinner.NumberEditor(s, "###0.000");
    dfmt = jne.getFormat();
    s.setEditor(jne);
    // When value is changed, need to process only
    only *relevant event*.
    s.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent event) {
    double val =
    le val = ((Double)s.getValue()).doubleValue();
    // ignore format event
    if
    if
    if
    if
    (!(String.valueOf(val).equals(dfmt.format(val)))){
    myImportantTask();
    JFrame f = new JFrame("Test Spinner");
    f.getContentPane().setLayout(new
    (new java.awt.BorderLayout());
    f.getContentPane().add(s,
    d(s, java.awt.BorderLayout.NORTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 300);
    f.setVisible(true);
    void myImportantTask(){
    System.out.println("New Value:" +
    :" + dfmt.format(s.getValue()));
    public static void main(String[] args){
    new SpinnerEvents();

  • Jspinner keeps counting

    I am having a problem with Jspinner. I have implemented a circular spinner SpinnerCircularNumberModel by extending SpinnerNumberModel . I also have 2 text boxes . i have to validate these textboxes .I put the validation codes in the focus lost event of these text boxes .If an invalid value is entered, then an error message is displayed and focus is returned to that textbox..Its working fine but the problem occurs when after entering an invalid value and changing the focus to the spinner (click the spinner buttons) ,error message is displayed and control returns back to the textbox but the spinner button remains in the pressed state as a result the number keeps on auto incrementing .
    how can i solve this problem .please help me.

    I have encountered the same problem. Did you solve it meanwhile?
    Here is a little program that shows the behaviour.
    Perhaps it is a bug? Did anyone submit it as a bug in the
    BugParade?
    --------------- Code ---------------------------------------------
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class SpinnerFrame extends JFrame implements ChangeListener {
    private JSpinner spinner;
    private boolean changing;
    private SpinnerFrame() {
    super();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().add(getSpinner());
    setSize(80,60);
    setLocation(200, 300);
    setVisible(true);
    changing = false;
    private JSpinner getSpinner() {
    if (spinner == null) {
    spinner = new JSpinner();
    spinner.setModel(new SpinnerNumberModel(10, 1, 50, 1));
    spinner.addChangeListener(this);
    return spinner;
    public void stateChanged(ChangeEvent e) {
    JSpinner spinner = (JSpinner) e.getSource();
    int value = ((Integer) spinner.getValue()).intValue();
    System.out.println("Changed to " + value);
    if (changing) {
    return;
    changing = true;
    if (value > 20) {
    JOptionPane.showMessageDialog(this, "20 exceeded");
    changing = false;
    public static void main(String[] args) {
    new SpinnerFrame();

  • Problem with SpinnerDateModel

    Hello,
    I got a problem using JSpinner. I remember I got the same problem years ago but forgot how to solve it.
    The following code I use to create a JSpinner for date/time
    JSpinner notBevoreSpin, notAfterlSpin;
    // later
    Calendar cal = Calendar.getInstance();
            java.util.Date initDate = cal.getTime();
            cal.add( Calendar.YEAR, 10 );
            java.util.Date latestDate = cal.getTime();
            SpinnerDateModel sdm = new SpinnerDateModel( initDate,
                    initDate,
                    latestDate,
                    Calendar.MINUTE );
            notBevoreSpin = new JSpinner( sdm );
            notBevoreSpin.setEditor( new JSpinner.DateEditor( notBevoreSpin,
                    "dd.MM.yyyy HH:mm" ) );
            notAfterlSpin = new JSpinner( sdm );
            notAfterlSpin.setEditor( new JSpinner.DateEditor( notAfterlSpin,
                    "dd.MM.yyyy HH:mm" ) );Later I can't spin. It only rings the warning sound from windows...
    Any Ideas?
    I guess it depends on the 4th parameter of the SpinnerDateModel.
    Regards,
    Olek

    it is the start/end parameters that need to be null
    SpinnerDateModel sdm = new SpinnerDateModel( initDate,
            null,//initDate,
            null,//latestDate,
            Calendar.MINUTE );and you'll need a lot more code to get the MINUTE field highlighted, so it will 'spin' by default

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

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

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

Maybe you are looking for

  • My Windows 7 64Bit Computer doesn't recognize my iPhone4S

    Just as the title states my computer here does not see or recognize my iPhone 4S. No matter what I have tried and done to get it to see and recognize my phone via my wireless network doesn't see it at all. I have forget this network, turned wifi off

  • Display resolution and Mac OS X 10.5.7

    I am now using my Mac mini (early 2009) as my primary computer (new aluminum keyboard and an LG 23" LCD HDTV) and have sent the iMac Core Duo to "the boys" room for them to use. But they have called my attention to the display resolution a few times

  • PSE 9.0.3 update can't install. Error message is "patch cannot be applied."

    PSE 9.0.3 does not install. Error message "patch cannot be applied."

  • Enterprise portals Questions

    Hi Can some body post me the usual interview questons in EP ...! Including Content Development, Implemention,Installation, Migration ,KM etc..... Also to have general understanding, What are all the versions of EP came so far? Major difference betwee

  • Remotely connecting to oracle linux on vmware from putty

    Hi, I have installed Oracle Linux on Vmware workstation. The Host is Windows 8. From the Host, I am able to connect via putty. But from another laptop, I am unable to connect via putty. Both, the laptop and the Host PC are on the same wifi. Can anyon