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

Similar Messages

  • FocusListener problem with JComboBox

    Hi,
    I am facing a problem with JComboBox. When I make it as Editable it is not Listening to the FocucListener Event....
    Please tell me if there is any way to overcome this..
    Regards,
    Chandan Sharma

    I searched the forum using "jcombobox focuslistener editable" and quess what, the first posting I read had the solution.
    Search the forum before posting questions.

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

  • FocusListener problem

    Hello,
    I have a focus listener that detects errors in my user interface. When the user enters a non Integer parsable entry, an exception is thrown and the focus is set back to the entry with the error.
    However, it seems as if two focus lost function calls are happening when this occurs. What is causing this. My code is below:
    //import the necessary java packages
    import java.awt.*;                  //for the awt widgets
    import javax.swing.*;               //for the swing widgets
    import java.awt.event.*;            //for the event handler interfaces
    //no import is needed for the DisplayCanvas class
    //if in the same directory as the DemoShape class
    public class DemoShape extends JApplet
        //declare private data members of the DemoShape class
        //declare the entry and display panel containers
        private Container entire;           //houses entryPanel and displayCanvas
        private JPanel entryPanel;          //accepts the user entries into widgets
        private DisplayCanvas drawCanvas;   //displays the response of entries
        //required control buttons for the entryPanel
        private JTextField widthShapeText, heightShapeText, messageText, fontSizeText;
        private ButtonGroup shapeRadio;
        private JRadioButton rect, oval, roundRect;
        private JComboBox shapeColorDrop, fontTypeDrop, fontColorDrop;
        //arrays of strings to be used later in combo boxes
        String displayFonts[] = {"Dialog", "Dialog Input", "Monospaced",
                                 "Serif", "Sans Serif"};          
        String javaFonts[] = {"Dialog", "DialogInput", "Monospaced",
                               "Serif", "SansSerif"};                   
        String shapes[] = {"Rectangle", "Round Rectangle", "Oval"};   
        String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
                           "Gray", "Green", "Light Gray", "Magenta", "Orange",
                           "Pink", "Red", "White", "Yellow"};
        Color javaColors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                               Color.gray, Color.green, Color.lightGray,
                               Color.magenta, Color.orange, Color.pink, Color.red,
                               Color.white, Color.yellow };
        //declare public data members of the DemoShape class
        //init method to initialize the applet objects
        public void init()
            //declare variables to assist with the layout
            //these are the left and right justified x coordinates
            int ljX = 10; int rjX = 150;
            //this is the y coordinates for the rows
            int yRow1 = 10;     //the shape rows
            int yRow2 = 40;
            int yRow3 = 60;
            int yRow4 = 130;
            int yRow5 = 150;
            int yRow6 = 210;    //the message rows
            int yRow7 = 240;
            int yRow8 = 260;
            int yRow9 = 300;
            int yRow10 = 320;
            int yRow11 = 360;
            int yRow12 = 380;
            //these are the widths for the text boxes, drop downs
            //message entry,  big message entry and radio buttons
            int tWidth = 30; int dWidth = 110;
            int mWidth = 250; int bmWidth = 250;
            int rWidth = 125;
            //the height is universal, even for the messages!
            int height = 25;
            //set a content pane for the entire applet
            //set the size of the entire window and show the entire applet
            entire = this.getContentPane();
            entire.setLayout(new GridLayout(1, 2));
            //create the entry panel and add it to the entire pane
            entryPanel = new JPanel();
            entryPanel.setLayout(null);
            entire.add(entryPanel);
            //create the display canvas and add it to the entire pane
            //this will display the output
            drawCanvas = new DisplayCanvas();
            drawCanvas.setBackground(Color.white);
            entire.add(drawCanvas);       
            //entry panel code
            //add the form elements in the form of rows
            //the first row (label)
            JLabel entryLabel = new JLabel("Enter Shape Parameters:");
            entryPanel.add(entryLabel);
            entryLabel.setBounds(ljX, yRow1, bmWidth, height);
            //second row (labels)
            JLabel shapeTypeLabel = new JLabel("Select Shape:");
            shapeTypeLabel.setBounds(ljX, yRow2, mWidth, height);
            entryPanel.add(shapeTypeLabel);
            JLabel shapeColorLabel = new JLabel("Select Shape Color:");
            shapeColorLabel.setBounds(rjX, yRow2, mWidth, height);
            entryPanel.add(shapeColorLabel);
            //third row (entry)        
            rect = new JRadioButton("Rectangle", true);
            oval = new JRadioButton("Oval", false);
            roundRect = new JRadioButton("Round Rectangle", false);
            rect.setBounds(ljX, yRow3, rWidth, height);
            oval.setBounds(ljX, yRow3 + 20, rWidth, height);
            roundRect.setBounds(ljX, yRow3 + 40, rWidth, height);
            rect.addItemListener(new changeListen());
            oval.addItemListener(new changeListen());
            roundRect.addItemListener(new changeListen());
            shapeRadio = new ButtonGroup();
            shapeRadio.add(rect);
            shapeRadio.add(oval);
            shapeRadio.add(roundRect);
            entryPanel.add(rect);
            entryPanel.add(oval);
            entryPanel.add(roundRect);       
            shapeColorDrop = new JComboBox(colors);
            shapeColorDrop.setBounds(rjX, yRow3, dWidth, height);
            shapeColorDrop.addItemListener(new changeListen());
            entryPanel.add(shapeColorDrop);
            //the fourth row (labels)
            JLabel widthShapeLabel = new JLabel("Enter Width:");
            widthShapeLabel.setBounds(ljX, yRow4, mWidth, height);
            entryPanel.add(widthShapeLabel);
            JLabel heightShapeLabel = new JLabel("Enter Height:");
            heightShapeLabel.setBounds(rjX, yRow4, mWidth, height);
            entryPanel.add(heightShapeLabel);
            //the fifth row (entry)
            widthShapeText = new JTextField("200", 3);
            widthShapeText.setBounds(ljX, yRow5, tWidth, height);
            widthShapeText.addFocusListener(new focusListen());
            entryPanel.add(widthShapeText);        
            heightShapeText = new JTextField("200", 3);
            heightShapeText.setBounds(rjX, yRow5, tWidth, height);
            heightShapeText.addFocusListener(new focusListen());
            entryPanel.add(heightShapeText);
            //the sixth row (label)
            JLabel messageLabel = new JLabel("Enter Message Parameters:");
            messageLabel.setBounds(ljX, yRow6, bmWidth, height);
            entryPanel.add(messageLabel);
            //the seventh row (labels)   
            JLabel messageEntryLabel= new JLabel("Enter Message:");
            messageEntryLabel.setBounds(ljX, yRow7, mWidth, height);
            entryPanel.add(messageEntryLabel);
            //the eighth row (entry)
            messageText = new JTextField("Enter your message.");
            messageText.setBounds(ljX, yRow8, mWidth, height);
            messageText.addFocusListener(new focusListen());
            entryPanel.add(messageText);
            //the ninth row (label)
            JLabel fontTypeLabel = new JLabel("Select Font:");
            fontTypeLabel.setBounds(ljX, yRow9, mWidth, height);
            entryPanel.add(fontTypeLabel);
            JLabel fontColorLabel = new JLabel("Select Font Color:");
            fontColorLabel.setBounds(rjX, yRow9, mWidth, height);
            entryPanel.add(fontColorLabel);
            //the tenth row (entry)
            fontTypeDrop = new JComboBox(displayFonts);
            fontTypeDrop.setBounds(ljX, yRow10, dWidth, height);
            fontTypeDrop.addItemListener(new changeListen());
            entryPanel.add(fontTypeDrop);       
            fontColorDrop = new JComboBox(colors);
            fontColorDrop.setBounds(rjX, yRow10, dWidth, height);
            fontColorDrop.addItemListener(new changeListen());
            entryPanel.add(fontColorDrop);
            //the eleventh row (label)
            JLabel fontSizeLabel = new JLabel("Select Font Size:");
            fontSizeLabel.setBounds(ljX, yRow11, mWidth, height);
            entryPanel.add(fontSizeLabel);
            //the final row (entry)
            fontSizeText = new JTextField("12", 2);
            fontSizeText.setBounds(ljX, yRow12, tWidth, height);
            fontSizeText.addFocusListener(new focusListen());
            entryPanel.add(fontSizeText);
            //set the applet to visible
            //set to visible and display
            entire.setSize(800, 600);
            entire.setVisible(true);
        }   //end the init method
        //paint method
        public void paint(Graphics g)
            //call the demoShape's superclass constructor
            super.paint(g);
            //repaint the canvas
            drawCanvas.repaint();
        }   //end paint method
        //begin the DisplayCanvas
        private class DisplayCanvas extends Canvas
            //declare private data members to house the width and height of the canvas
            private int canWidth;
            private int canHeight;
            //declare private data members for the shape and message
            private String message;
            private String shape;
            private Color sColor;
            private int sWidth;
            private int sHeight;
            private String font;
            private Color ftColor;
            private int ftSize; 
            //declare public data members
            //constructor of DisplayCanvas
            public DisplayCanvas()
                 //set all data members to defaults
                canWidth = 0;
                canHeight = 0;
                message = "Enter your message.";
                shape = "rect";
                sColor = Color.black;
                sWidth = 200;
                sHeight = 200;
                font = "Serif";
                ftColor = Color.black;
                ftSize = 12;
           } //end the constructor
           //begin the setMessage function
           public void setMessage(String m) { message = m; }
           //begin the setShape function
           public void setShape(String s) { shape = s; }
           //begin the setSColor function
           public void setSColor(Color sC) { sColor = sC; }
           //begin the setSWidth function
           public void setSWidth(int w) { sWidth = w; }
           //begint the setSHeight
           public void setSHeight(int h) { sHeight = h; }
           //begin the setFont method
           public void setFont(String f) { font = f; }
           //begin the setFtColor method
           public void setFtColor(Color ftC) { ftColor = ftC; }
           //begin the setFtSize
           public void setFtSize(int ftS) { ftSize = ftS; } 
           //begin the public paint function of ShowShape
           public void paint(Graphics g)
                //set and output the shape according to the arguments
                 //set the width and height
                //this must be done in the paint method (not init())
                canWidth = this.getWidth();
                canHeight = this.getHeight();
                //determine the x and y of the shape
                int x = (canWidth - sWidth) / 2;
                int y = (canHeight - sHeight) / 2;
                //set the color for the graphic object
                g.setColor(sColor);
                //output the shape
                //if the shape is a rectangle
                if(shape.equals("rect"))
                { g.drawRect(x, y, sWidth, sHeight); }
                //else if it is a oval
                else if(shape.equals("oval"))
                { g.drawOval(x, y, sWidth, sHeight); }
                //else it is a round rectangle
                else
                { g.drawRoundRect(x, y, sWidth, sHeight, 25, 25); }
                //set and output the message according to the arguments
                //set the color and the font for the graphic object
                g.setColor(ftColor);
                g.setFont(new Font(font, Font.PLAIN, ftSize));
                //determine the centering of the message
                 //get the width and height of the message
                FontMetrics metrics = g.getFontMetrics();
                int mW = metrics.stringWidth(message);
                int mH = metrics.getHeight();
                //if the message is too wide for the shape
                if(mW > sWidth)
                { JOptionPane.showMessageDialog(null, "Message is too wide for the shape."); }
                //else if the message is too tall for the shape
                else if(mH > sHeight)
                { JOptionPane.showMessageDialog(null, "Message is too tall for the shape."); }
                //else print the message
                else
                { g.drawString(message, (canWidth - mW) / 2, (canHeight - mH) / 2); } 
            } //end the paint function of ShowShape class
        } //end the DisplayCanvas class
        //declare an inner class to handle events
        private class focusListen implements FocusListener
            //supply the implementation of the actionPerformed method
            //pass an event variable as the argument
            public void focusLost(FocusEvent e)
                //check the entries with possibilities for errors
                //if widthShapeText lost focus
                if(e.getSource() == widthShapeText)
                    int widthShapeInt = 0;  //integer to house wrapper conversion
                    //test for integer parsing
                    try
                        //try parsing the int and send the width
                        widthShapeInt = Integer.parseInt(widthShapeText.getText());
                        //test the width of the shape within the canvas
                        if(widthShapeInt > drawCanvas.getWidth()) { throw new Exception(); }
                        //set the canvas parameter
                        drawCanvas.setSWidth(widthShapeInt);
                    //catch and process the exception
                    catch(Exception swException)
                        JOptionPane.showMessageDialog(null, "Error, width must be numeric and less than " + drawCanvas.getWidth() + ".");
                        widthShapeText.requestFocus();
                    //check if width it too wide
                }   //end if focus left widthShapeText
                //if heightShapeText lost focus
                else if(e.getSource() == heightShapeText) 
                    int heightShapeInt = 0;  //integer to house wrapper conversion
                    //test for integer parsing
                    try
                        //test entry for integer parsing
                        heightShapeInt = Integer.parseInt(heightShapeText.getText());
                        //test the width of the shape within the canvas
                        if(heightShapeInt > drawCanvas.getHeight()) { throw new Exception(); }
                        //set the canvas parameter
                        drawCanvas.setSHeight(heightShapeInt);                   
                    //catch and process the exception
                    catch(Exception shException)
                        JOptionPane.showMessageDialog(null, "Error, height must be numeric and less than " + drawCanvas.getHeight() + ".");
                        heightShapeText.requestFocus();
                    //check if height it too high              
                }   //end else if heightShapeText lost focus                      
                //if messageText
                else if(e.getSource() == messageText)
                    //send the message to the canvas
                    drawCanvas.setMessage(messageText.getText());
                }   //end else if messageText lost focus
                //if fontSizeText lost focus
                else if(e.getSource() == fontSizeText)
                    int fontSizeInt = 0;  //integer to house wrapper conversion
                    //test for integer parsing
                    try
                        //test entry for integer parsing
                        fontSizeInt = Integer.parseInt(fontSizeText.getText());
                        //set the canvas parameter
                        drawCanvas.setFtSize(fontSizeInt);
                    //catch and process the exception
                    catch(Exception fsException)
                        JOptionPane.showMessageDialog(null, "Error, font size must be numeric.");
                        fontSizeText.requestFocus();
                }   //end else fontSizeText has focus           
                //repaint the canvas after any focus lost above
                drawCanvas.repaint();
            }  //end focusLost method
            //implement an empty focus gained function
            public void focusGained(FocusEvent e) {}      
        }   //end testListen class
        //declare an inner class to handle events
        private class changeListen implements ItemListener
            //begin the itemStateChanged method
            public void itemStateChanged(ItemEvent e)
                //if shapeColorDrop was changed
                if(e.getSource() == shapeColorDrop)
                { drawCanvas.setSColor(javaColors[shapeColorDrop.getSelectedIndex()]); }  
                //if fontTypeDrop was changed
                else if(e.getSource() == fontTypeDrop)
                { drawCanvas.setFont(javaFonts[fontTypeDrop.getSelectedIndex()]); }  
                //if fontColorDrop was changed
                else if(e.getSource() == fontColorDrop)
                { drawCanvas.setFtColor(javaColors[fontColorDrop.getSelectedIndex()]); }  
                //check the radio buttons
                //if fontColorDrop was changed
                else if(e.getSource() == rect)
                { drawCanvas.setShape("rect"); }  
                //if fontColorDrop was changed
                else if(e.getSource() == roundRect)
                { drawCanvas.setShape("roundRect"); }  
                //if fontColorDrop was changed
                else if(e.getSource() == oval)
                { drawCanvas.setShape("oval"); }  
                //repaint the canvas after any change above
                drawCanvas.repaint();
            }   //end itemStateChanged method
        }   //end changeListen class
    }   //end DemoShape class

    Just my first impression, but it might be that when one of your components is losing focus another one is gaining focus. Right up to the point where JOptionPane gets focus. Then then other one loses focus and generates an event.

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

  • Problem with focusListener

    Hi All,
    I have created 2 text fields and added the focus listener to check user data.
    EX: Whenever user leaves the text field blank progrm will alert not to leave the text field blank. Whenever I press tab to go to next text field I receive alert for both the text fields. Following is my code.
    public void focusLost(FocusEvent fe1)
              Component c = fe1.getComponent();
              if(c instanceof JTextField)
                   JTextField f = (JTextField) c;
                   if (f.getName().equals("First Name"))
                        String s = f.getText();
                        if(s.equals(""))
              createDialog("First Name value can not be null!!",c);
                        else if(f.getName.equals("Last Name"))
                             createDialog("First Name value can not be null!!",c);
    public void createDialog(String s,Component cc)
                   JDialog dialog = new JDialog();
                   dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(),BoxLayout.Y_AXIS));
                   dialog.setSize(210,100);
                   JLabel message = new JLabel(s);
                   JButton b = new JButton("Ok");
                   dialog.getContentPane().add(message);
                   dialog.getContentPane().add(b);
                   dialog.setVisible(true);
                   dialog.setLocationRelativeTo(cc);
                   dialog.show();
    Please help!!
    Thanks

    Hello again,
    using now a flag to prevent focus problem:import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Test extends JFrame implements FocusListener
         public static void main(String[] args)
              new Test();
         private JTextField t1 = null;
         private JTextField t2 = null;
         boolean eventChecked = false;
         public Test()
              super();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initPanel();
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         private void initPanel()
              t1 = new JTextField(10);
              t1.setName("FirstName");
              t2 = new JTextField(10);
              t2.setName("LastName");
              t1.addFocusListener(this);
              t2.addFocusListener(this);
              getContentPane().add(t1, BorderLayout.NORTH);
              getContentPane().add(t2, BorderLayout.SOUTH);
         public void focusLost(FocusEvent fe1)
              if (eventChecked)
                   return;
              Component c = fe1.getComponent();
              if (c instanceof JTextField)
                   JTextField f = (JTextField) c;
                   String s = f.getText();
                   if (f.getName().equals("FirstName") && s.equals(""))
                        createDialog("First Name value can not be null!!", c);
                        eventChecked = true;
                        f.requestFocusInWindow();
                   else if (f.getName().equals("LastName") && s.equals(""))
                        createDialog("Last Name value can not be null!!", c);
                        eventChecked = true;
                        f.requestFocusInWindow();
         public void focusGained(FocusEvent e)
         public void createDialog(String s, Component cc)
              final JDialog dialog = new JDialog();
              dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
              dialog.setSize(210, 100);
              JLabel message = new JLabel(s);
              JButton b = new JButton("Ok");
              dialog.getContentPane().add(message);
              dialog.getContentPane().add(b);
              dialog.setLocationRelativeTo(cc);
              dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
              dialog.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        eventChecked = false;
                        dialog.hide();
              dialog.setVisible(true);
    }regards,
    Tim

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

  • FocusListener and other listener problem

    I don't know why i can't catch Deactivated and LostFocus and other relevant event.
    I try to make a simplepanel as Popup because Jpopupmenu have some problem.
    please take a look.
    regards thanks
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JWindow;
    * Created on Jun 1, 2006
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author varamthanapon
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    public class SampleMain extends JApplet implements ActionListener,
              WindowFocusListener, ComponentListener, WindowListener {
         private JButton m_objJButton = null;
         private PopupPanel m_objPopupPanel = null;
         public SampleMain() {
              this.getContentPane().setLayout(new BorderLayout());
              JPanel mainPanel = new JPanel();
              mainPanel.setSize(500, 500);
              mainPanel.setLocation(500, 500);
              mainPanel.add(new JLabel("XXX"), BorderLayout.NORTH);
              this.getContentPane().add(mainPanel);
              JButton xbutton = new JButton("xxx");
              this.getContentPane().add(xbutton, BorderLayout.WEST);
              xbutton.addActionListener(this);
              m_objPopupPanel = new PopupPanel(this);
              this.addFocusListener(m_objPopupPanel);
              this.show();
         public class PopupPanel extends JWindow implements FocusListener {
              public PopupPanel(SampleMain obj) {
                   this.addWindowFocusListener(obj);
                   this.addComponentListener(obj);
                   this.addWindowListener(obj);
              * (non-Javadoc)
              * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
              public void focusGained(FocusEvent e) {
                   // TODO Auto-generated method stub
                   JOptionPane.showMessageDialog(new JPanel(), "XXX");
              * (non-Javadoc)
              * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
              public void focusLost(FocusEvent e) {
                   // TODO Auto-generated method stub
                   JOptionPane.showMessageDialog(new JPanel(), "XXX");
         * (non-Javadoc)
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         public void actionPerformed(ActionEvent e) {
              // TODO Auto-generated method stub
              m_objPopupPanel.setSize(200, 50);
              m_objPopupPanel.setLocation(200, 50);
              m_objPopupPanel.show();
         * (non-Javadoc)
         * @see java.awt.event.WindowFocusListener#windowGainedFocus(java.awt.event.WindowEvent)
         public void windowGainedFocus(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowGainedFocus");
         * (non-Javadoc)
         * @see java.awt.event.WindowFocusListener#windowLostFocus(java.awt.event.WindowEvent)
         public void windowLostFocus(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowLostFocus");
         * (non-Javadoc)
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
         public void componentResized(ComponentEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "componentResized");
         * (non-Javadoc)
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
         public void componentMoved(ComponentEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "componentMoved");
         * (non-Javadoc)
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
         public void componentShown(ComponentEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "componentShown");
         * (non-Javadoc)
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
         public void componentHidden(ComponentEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "componentHidden");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowOpened(java.awt.event.WindowEvent)
         public void windowOpened(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowOpened");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowClosing(java.awt.event.WindowEvent)
         public void windowClosing(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowClosing");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowClosed(java.awt.event.WindowEvent)
         public void windowClosed(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowClosed");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowIconified(java.awt.event.WindowEvent)
         public void windowIconified(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowIconified");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowDeiconified(java.awt.event.WindowEvent)
         public void windowDeiconified(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowDeiconified");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowActivated(java.awt.event.WindowEvent)
         public void windowActivated(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowActivated");
         * (non-Javadoc)
         * @see java.awt.event.WindowListener#windowDeactivated(java.awt.event.WindowEvent)
         public void windowDeactivated(WindowEvent e) {
              // TODO Auto-generated method stub
              JOptionPane.showMessageDialog(new JPanel(), "windowDeactivated");
    }

    I believe it's because Windows which don't have a visible parent frame are, by default, not focusable. Therefore they're never activated or focused.
    For the window to become focusable it needs a visible parent. Have a look at Window.isFocusableWindow method's Javadoc for information about how this works.
    There's also no point trying to force the window to be focusable using setFocusableWindowState - it still won't work without the visible parent frame.
    What's the problem with JPopupMenu? It seems unlikely that you'll write something better than that.
    Alternatively, you could try using an undecorated JDialog. Personally, I'd try resolving your differences with JPopupMenu!
    Hope this helps.

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

Maybe you are looking for