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.

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

  • 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

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

  • Strange Problem about KeyListener, and FocusListener

    Hi,Please help me with this problem.
    I create a JTable and setCellEditor by using my customerized TextField
    The problem is: when I edit JTable Cell, the value can not be changed and I can not get Key Event and Focus Event.
    here is my source:
    //create normal JTable instance,and then initlize it
    private void initTable(Vector folders)
    TableColumn tempcol = getColumnModel().getColumn(0);
    tempcol.setCellEditor(new DefaultCellEditor(new MyTextField()));
    for(int i=0;i<folders.size();i++)
    mddDataSource ds=(mddDataSource) folders.get(i);
    String name = ds.getDataSourceName();
    layers.add(name);
    for(int i=0;i<layers.size();i++){
    Vector temp = new Vector();
    temp.add(layers.get(i));
    temp.add(layers.get(i));
    dtm.addRow(temp);
    // My Text Field cell
    class MyTextField extends JTextField implements FocusListener, KeyListener
    MyTextField()
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    MyTextField(String text)
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    public void focusGained(FocusEvent e) {
    System.out.println("get Focus");
    public void focusLost(FocusEvent e) {
    instance.setValue(getText());
    public void keyTyped(KeyEvent e){
    instance.setValue(getText());
    public void keyPressed(KeyEvent e){
    System.out.println("get Key ");
    public void keyReleased(KeyEvent e){
    instance.setValue(getText());
    If there are some good sample, please tell me the link or give me some suggestion.
    Thanks in advanced

    Thanks for your help.
    The problem still exist. It does not commit the value that I input.
    Maybe I should say it clearly.
    I have create JPanel include three JPanel:
    Left Panel and right upper-panel and right borrom panel.
    The JTable instance is on right-upper Panel.
    If I edit one of row at JTable and then click JTable other row,the value can be commited. if I edit one of row and then push one Button on
    the right-bottom button to see the editting cell value.It does not commit value.
    when I use debug style, and set breakpoint the
    foucsGained or KeyTyped,
    It never stopes at there,So I assume that the Editing cell never get focus.
    Is there a bug at Java if we move focus on other Panel, that JTable can not detect the Focus lost or focus gained event?
    Thanks

  • Problem with Listeners/ requestFocus()

    Hello,
    I am new to Java (started learning two months back), There is a problem with the requestFocus() in the focusListener. The program does not return the focus to the object indicated in the requestFocus but it shows multiple cusors!!
    The faculity at the institute where I am learning could not rectify the error.
    Is the error because of the myMethod() which I am using. I had made this method to prove to my professor that we can reduce the code drastically while using the gridbaglayout.
    The code which I had written is as under:
    // file name ShopperApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShopperApplet extends JApplet implements ActionListener, FocusListener,Runnable
         //static JPanel sP;
         //static JPanel oP;
         JTabbedPane tabbedPane = new JTabbedPane();
         JPanel sP;
         JPanel oP;
         JPanel pwd = new JPanel();
         // Layout Decleration of oP
         GridBagLayout ordL = new GridBagLayout();
         GridBagConstraints ordC = new GridBagConstraints();
         // Layout Decleration of sP
         FlowLayout flow = new FlowLayout();
         // Variables of sP
              JTextField textShopperId;
              JPasswordField textPassword;
              JTextField textFirstName ;
              JTextField textLastName ;
              JTextField textEmailId ;
              JTextField textAddress ;
              JComboBox comboCity ;
              JTextField textState ;
              JTextField textCountryId ;
              JTextField textZipCode ;
              JTextField textPhone ;
              JTextField textCreditCardNo ;
              JRadioButton rbVisa;
              JRadioButton rbMaster;
              JRadioButton rbAmEx;
              ButtonGroup BGccType;
              //JComboBox comboCreditCardType;
              //JTextField textExperyDate;
              JComboBox cmbDt;
              JComboBox cmbMth;
              JComboBox cmbYear;
              JButton btnSubmit;
              JButton btnReset;          
         // Variables of oP
              // Variable Decleration od oP
              JTextField txtOrderNo;
              JTextField txtToyId;
              JTextField txtQty;
              JRadioButton rbYes;     
              JRadioButton rbNo;
              ButtonGroup bgGiftWrap;
              JComboBox cmbWrapperId;
              JTextField txtMsg;
              JTextField txtToyCost;
              JButton btnOSubmit;
              JButton btnOReset;     
         // Variables of pwd
              JTextField txtShopperId;
              JPasswordField txtPassword;
              JButton btnPSubmit;
              JButton btnPReset;     
              JButton btnPNew;
              JButton btnPLogoff;
              JLabel lblN, lblN1;     
              Thread t,t1;
         Font TNR = new Font("Times New Roman",1,15);
         Font arial = new Font("Arial",2,15);
         public void sPDet()
              //Variable Decleration of sP
              textShopperId = new JTextField(6);
              textPassword = new JPasswordField(4);
              textPassword.addFocusListener(this);
              //textPassword = new JTextField(4);
              textPassword.setEchoChar('*');
              textFirstName = new JTextField(20);
              textLastName = new JTextField(20);
              textEmailId = new JTextField(25);
              textAddress = new JTextField(20);
              String cityList[] = {"New Delhi", "Mumbai", "Calcutta", "Hyderabad"};
              comboCity = new JComboBox(cityList);
              comboCity.setEditable(true);
              textState = new JTextField(30);
              textCountryId = new JTextField(25);
              textZipCode = new JTextField(6);
              textPhone = new JTextField(25);
              textCreditCardNo = new JTextField(25);
              String cardTypes[] = {"Visa", "Master Card", "American Express"};
              //comboCreditCardType = new JComboBox(cardTypes);
              rbVisa = new JRadioButton("Visa");
              rbMaster = new JRadioButton("Master Card");
              rbAmEx = new JRadioButton("American Express");
              BGccType = new ButtonGroup();
              BGccType.add(rbVisa);
              BGccType.add(rbMaster);
              BGccType.add(rbAmEx);
              String stDt[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
              String stMth[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
              String stYear[] = {"2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"};
              cmbDt = new JComboBox(stDt);
              cmbMth = new JComboBox(stMth);
              cmbYear = new JComboBox(stYear);
              //textExperyDate = new JTextField(10);
              btnSubmit = new JButton("Submit");
              btnReset = new JButton("Reset");
              // Adding Layout Controls
              sP.setLayout(ordL);
              sP.setBackground(Color.green);
              myLayout(textShopperId,3,1,sP,"FM","Shopper Id");
              myLayout(textPassword,3,2,sP,"FM","Password");
              myLayout(textFirstName,3,3,sP,"FM","First Name") ;
              myLayout(textLastName,3,4,sP,"FM","Last Name") ;
              myLayout(textEmailId,3,5,sP,"FM","E-Mail Id") ;
              myLayout(textAddress,3,6,sP,"FM", "Address") ;
              myLayout(comboCity,3,7,sP,"FM","City") ;
              myLayout(textState,3,8,sP,"FM","State") ;
              myLayout(textCountryId,3,9,sP,"FM","Country") ;
              myLayout(textZipCode,3,10,sP,"FM","Zip Code") ;
              myLayout(textPhone,3,11,sP,"FM","Phone") ;
              myLayout(textCreditCardNo,3,12,sP,"FM","Credit Card No.") ;
              //myLayout(rbVisa,3,13,sP);
              JPanel newPanel = new JPanel();
              newPanel.add(rbVisa);
              newPanel.add(rbMaster);
              newPanel.add(rbAmEx);
              myLayout(newPanel,3,13,sP,"FM","Credit Card Type");
              //myLayout(rbMaster,4,13);
              //myLayout(rbAmEx,5,13);
              JPanel newPanel1 = new JPanel();
              newPanel1.add(cmbDt);
              newPanel1.add(cmbMth);
              newPanel1.add(cmbYear);
              myLayout(newPanel1,3,14,sP,"FM","Expiry Date");
              //myLayout(textExperyDate,3,14,sP,"FM");
              myLayout(btnSubmit,1,17,sP,"AL","Submit");
              myLayout(btnReset,3,17,sP,"AL","Reset");          
         public void oPDet()
              txtOrderNo = new JTextField(10);
              txtToyId = new JTextField(10);
              txtQty = new JTextField(10);
              rbYes = new JRadioButton("Yes");
              rbNo = new JRadioButton("No");
              bgGiftWrap = new ButtonGroup();
              bgGiftWrap.add(rbYes);
              bgGiftWrap.add(rbNo);
              String wrapperTypes[] = {"Blue Stripes", "Red Checks", "Green Crosses","Yellow Circles", "Red & Purple Stripes"};
              cmbWrapperId = new JComboBox(wrapperTypes);
              txtMsg = new JTextField(10);
              txtToyCost = new JTextField(10);
              btnOSubmit = new JButton("Submit");
              btnOReset = new JButton("Reset");
              // Adding Controls to oP
              oP.setLayout(ordL);
              oP.setBackground(Color.yellow);
              myLayout(txtOrderNo,3,1,oP,"FM","Order No.");
              myLayout(txtToyId,3,2,oP,"FM","Toy Id");
              myLayout(txtQty,3,3,oP,"FM","Quantity");
              myLayout(rbYes,3,4,oP,"M");
              myLayout(rbNo,4,4,oP,"M");
              myLayout(cmbWrapperId,3,5,oP,"M","Wrapper Id");
              myLayout(txtMsg,3,6,oP,"FM","Message");
              myLayout(txtToyCost,3,7,oP,"FM","Toy Cost");
              myLayout(btnOSubmit,1,8,oP,"AL","Submit");
              myLayout(btnOReset,3,8,oP,"AL","Reset");          
         public void pwdDet()
              pwd.setLayout(ordL);
              pwd.setBackground(Color.green);
              t = new Thread(this);
              t.start();
              t1 = new Thread(this);
              t1.start();
              lblN = new JLabel("");
              lblN1 = new JLabel("");
              txtShopperId = new JTextField(10);
              txtPassword = new JPasswordField(10);
              btnPSubmit = new JButton("Submit") ;
              btnPReset = new JButton("Reset");     
              btnPNew = new JButton("New Member");
              btnPLogoff = new JButton("Log Off");
              pwd.setLayout(ordL);
              pwd.setBackground(Color.yellow);
              myLayout(lblN,3,7,pwd);
              myLayout(lblN1,3,8,pwd);
              myLayout(txtShopperId,3,1,pwd,"FM","Shopper Id.");
              myLayout(txtPassword,3,2,pwd,"FM","Password");
              myLayout(btnPSubmit,2,4,pwd,"AL","Submit");
              myLayout(btnPReset,3,4,pwd,"AL","Reset");          
              myLayout(btnPNew,2,5,pwd,"AL","New");
              myLayout(btnPLogoff,3,5,pwd,"AL","Log Off");
         public void run()
              int ctr =0;
              String ili[] = {"India","is","a","Great","Country"};
              int ctr1 = 0;
              String iib[] = {"India","is","the","Best"};
              Thread myThread = Thread.currentThread();
              if (myThread == t)
                   while (t != null)
                        lblN.setText(ili[ctr]);
                        ctr++;
                        if (ctr >=5) ctr=0;
                        try
                             t.sleep(500);
                        catch(InterruptedException e)
                             showStatus("India is a great Country has been interrupter");
              else
                   while (t1 != null)
                        lblN1.setText(iib[ctr1]);
                        ctr1++;
                        if (ctr1 >=4) ctr1=0;
                        try
                             t1.sleep(1000);
                        catch(InterruptedException e)
                             showStatus("India is the best has been interrupter");
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JButton aObj, int x, int y, JPanel aPanel,String aListener, String toolTip)
              aObj.setToolTipText(toolTip);
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JTextField aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              //aObj = new JTextField(10);
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
              //     aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JLabel aObj, int x, int y, JPanel aPanel)
              ordC.anchor=GridBagConstraints.SOUTH;
              aObj.setForeground(Color.blue);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void init()
              getContentPane().add(tabbedPane);
              sP = new JPanel();
              sPDet();
              oP = new JPanel();
              oPDet();
              pwdDet();
              tabbedPane.addTab("Login",null,pwd,"Login");
              tabbedPane.addTab("Shopper",null,sP,"Shopper Details");
              tabbedPane.addTab("Order",null,oP,"Order Details");
              tabbedPane.setEnabledAt(2, false);
              tabbedPane.setEnabledAt(1, false);
         public void actionPerformed(ActionEvent e)
              Object obj = e.getSource();
              if (obj == btnSubmit)
                   if (validShopperId() == false) return;
                   if (validPassword() == false) return;
                   if (validFirstName() == false) return ;
                   if (validLastName() == false) return ;
                   if (validEmailId() == false) return;
                   if (validAddress() == false) return;
                   if (validState() == false) return;
                   if (validCountryId() == false) return;
                   if (validZipCode() == false) return;
                   if (validCreditCardNo() == false) return ;
                   resetShopper();
                   tabbedPane.setEnabledAt(1,false);
                   tabbedPane.setEnabledAt(2,false);
                   tabbedPane.setSelectedIndex(0);
                   // also can be written as tabbedPane.setSelectedComponent(pwd);
                   //tabbedPane.remove(sP);
              if (obj == btnReset)
                   resetShopper();
                   tabbedPane.setEnabledAt(2,false);
                   //textExperyDate.setText("");
              if (obj == btnOSubmit)
                   if (validOrderNo() == false) return;
                   if (validToyId() == false) return;
                   if (chkNullEntry(txtQty, "Quantity")) return ;
                   if (chkNullEntry(txtToyCost, "Toy Cost")) return ;
              if (obj == btnOReset)
                   resetOrder();
              if (obj == btnPSubmit)
                   if (validPShopperId() && validPPassword())
                        tabbedPane.setEnabledAt(2, true);
                        tabbedPane.setEnabledAt(1, false);
                        txtShopperId.setText("");
                        txtPassword.setText("");
                        resetPassword();
                        //tabbedPane.addTab("Order",null,oP,"Order Details");
              if (obj == btnPReset)
                   resetPassword();
                   tabbedPane.setEnabledAt(1, false);
                   tabbedPane.setEnabledAt(2, false);
              if (obj == btnPNew)
                   tabbedPane.setEnabledAt(1, true);
                   tabbedPane.setEnabledAt(2, false);
                   resetPassword();
                   tabbedPane.setSelectedComponent(sP);
                   //tabbedPane.addTab("Shopper",null,sP,"Shopper Details");          
              if (obj == btnPLogoff)
                   tabbedPane.setEnabledAt(2, false);
                   tabbedPane.setEnabledAt(1, false);
                   resetPassword();
         public void focusGained(FocusEvent fe)
              //Object aObj = fe.getSource();
              //showStatus("Current Object is "+aObj);
         public void resetPassword()
              txtShopperId.setText("");
              txtPassword.setText("");
         public void resetShopper()
                   textShopperId.setText("");
                   textPassword.setText("");
                   textFirstName.setText("") ;
                   textLastName.setText("") ;
                   textEmailId.setText("") ;
                   textAddress.setText("") ;
                   textState.setText("") ;
                   textCountryId.setText("") ;
                   textZipCode.setText("") ;
                   textPhone.setText("") ;
                   textCreditCardNo.setText("") ;
         public void resetOrder()
              txtOrderNo.setText("");
              txtToyId.setText("");
              txtQty.setText("") ;
              txtToyCost.setText("") ;
              txtMsg.setText("") ;
         public void focusLost(FocusEvent fe)
              try{
                   Object obj = fe.getSource();
                   if (obj == textShopperId &&     validShopperId() == false)
                        //textShopperId.requestFocus();
                        return;
                   if (obj == textPassword && validPassword() == false)
                        //textPassword.requestFocus();
                        return;
                   if (obj == textFirstName && validFirstName() == false)
                        //textFirstName.requestFocus();
                        return;
                   if (obj == textEmailId && validEmailId() == false)
                        //textEmailId.requestFocus();
                        return;
                   if (obj == txtOrderNo && validOrderNo() == false)
                        //txtOrderNo.requestFocus();
                        return;
                   if (obj == txtToyId && validToyId() == false);
                        //txtToyId.requestFocus();
                        return;
              catch(Exception e)
                   showStatus("error in LostFocus() Method");
         public boolean validShopperId()
              if (chkNullEntry(textShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPassword()
              if (chkNullEntry(textPassword,"Password")) return false;
              return true;
         public boolean validFirstName()
              if (chkNullEntry(textFirstName,"First Name")) return false;
              return true;
         public boolean validLastName()
              if (chkNullEntry(textLastName,"Last Name")) return false;
              return true;
         public boolean validAddress()
              if (chkNullEntry(textAddress,"Address")) return false;
              return true;
         public boolean validState()
              if (chkNullEntry(textState,"State")) return false;
              return true;
         public boolean validCountryId()
              if (chkNullEntry(textCountryId,"Country")) return false;
              return true;
         public boolean validZipCode()
              if (chkNullEntry(textZipCode,"Postal Code")) return false;
              return true;
         public boolean validCreditCardNo()
              if (chkNullEntry(textCreditCardNo,"Credit Card No.")) return false;
              return true;
         public boolean validEmailId()
              if (chkNullEntry(textEmailId,"Email Address")) return false;
              String s1 = textEmailId.getText();
              int abc = s1.indexOf("@");
              if (abc == -1 || abc == 0 || abc == (s1.length()-1))
                   JOptionPane.showMessageDialog(sP,"Invalid Email Address","Error Message",JOptionPane.ERROR_MESSAGE);
                   //textEmailId.requestFocus();
                   return false;
              return true;
         public boolean validOrderNo()
              if (chkNullEntry(txtOrderNo,"Order No.")) return false;
              return true;
         public boolean validToyId()
              if (chkNullEntry(txtToyId,"Toy Id")) return false;
              return true;
         public boolean chkNullEntry(JTextField aObj,String sDef)
              String s1 = aObj.getText();
              if (s1.length() ==0)
                   try
                        JOptionPane.showMessageDialog(sP,sDef+" cannot be left blank","Error Message",JOptionPane.ERROR_MESSAGE);
                        //showStatus(sDef+" cannot be left blank");
                        // nbvvvv vcz     z111111eeeefgggggggggg aObj.requestFocus();
                   catch(Exception e)
                        showStatus("Error in chkNullEntry() method");
                   return true ;
              else
                   return false;
         public boolean validPShopperId()
              if (chkNullEntry(txtShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPPassword()
              if (chkNullEntry(txtPassword,"Password")) return false;
              return true;
    // end of code.

    Would it not be acceptable to check that each field has a value when Submit is pressed. If a field is found with no data then display the error message and return the focus to the empty field. This would solve the multiple cursors problem as you would not need any focusLost handler code.
    If this is entirely out of the question then you will have to override some of the FocusManager methods to prevent the JVM from handling focus for you :
    FocusManager.setCurrentManager(new DefaultFocusManager() {
      // Override FocusManager methods here.
    });Ronny.

  • Problem with JTextArea

    Hi all,
    I am having a class which extends JTextArea. I press backspace and I check for some condition in KeyReleased event. If the condition is true I am setting the JTextArea with the old text(retainText). What happens here is that first the backspace entered by me is reflecting on the screen and then only the new text (retainText) is set. This causes a flickering on the text area. My requirement is that this should not happen.
    Is there any way to avoid this .
    or else Is there any way to cancel this event ( say i enter backspace and if the condition becomes true in the KeyReleased event, I should stop this event. Can any body please help me ASAP. Thanks!!!
    I ve attached the code also
    package com.bankofny.iic.client.component;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    import com.bankofny.iic.client.instruction.viewer.TradeDetailForm;
    import com.bankofny.iic.common.util.StringFormatter;
    public class IicTextAreaSwift extends JTextArea implements FocusListener, KeyListener
        // IicTextAreaSwift Method
         private int DescCharWidth = 0;
        private int DescCharHeight =0;
         private String retainText; //retain always the latest text
         private int KeyCode;
         private String KeyText="";
        public IicTextAreaSwift(int _rows, int _columns, boolean scrollPane)
            super(_rows, _columns + 1);
            setDisabledTextColor(Color.gray);
                rows            = _rows;
            columns         = _columns;
            setRows(_rows);
            maxTextAllowed  = _rows * _columns;
            setBorder(new BevelBorder(BevelBorder.LOWERED));
            setLineWrap(true);
            setWrapStyleWord(true);
            Font fixedFont = new Font("Courier", Font.PLAIN, 12);
            setFont(fixedFont);
            FontMetrics fm = getFontMetrics(fixedFont);
            DescCharWidth = fm.charWidth('W') * (_columns + 1);
          //  DescCharHeight = fm.getHeight() * 4 ;
               DescCharHeight =  DEFAULT_LABEL_HEIGHT * 3;
            setPreferredSize(new Dimension(DescCharWidth, DescCharHeight));
            // setSize(new Dimension(DescCharWidth, DescCharHeight));
            addKeyListener(this);
            addFocusListener(this);
            fixTAB();
        public IicTextAreaSwift(int _rows, int _columns)
              super(_rows, _columns);
              // HA this constructor is for this field not in a scroll pane
              setDisabledTextColor(Color.gray);
              rows            = _rows;
              columns         = _columns;
              setRows(_rows);
              maxTextAllowed  = _rows * _columns;
              setBorder(new BevelBorder(BevelBorder.LOWERED));
              setLineWrap(true);
              setWrapStyleWord(true);
              Font fixedFont = new Font("Courier", Font.PLAIN, 12);
              setFont(fixedFont);
              FontMetrics fm = getFontMetrics(fixedFont);
              DescCharWidth = fm.charWidth('W') * (_columns + 1);
             //  DescCharHeight = fm.getHeight() * 4 ;
              DescCharHeight =  DEFAULT_LABEL_HEIGHT * 3;
              setPreferredSize(new Dimension(DescCharWidth, DescCharHeight));
              // setSize(new Dimension(DescCharWidth, DescCharHeight));
              addKeyListener(this);
              addFocusListener(this);
              fixTAB();
        public Dimension getDimen()
              return new Dimension(     DescCharWidth, DescCharHeight);
         public void showKeys(JComponent component)
              // List keystrokes in the WHEN_FOCUSED input map of the component
              InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
              printInputMap(map,"WHEN_FOCUSED");
              // List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component
              map = component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              printInputMap(map,"WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
              //list(map, map.keys());
              // List keystrokes in all related input maps
              //list(map, map.allKeys());
              // List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component
              map = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
              printInputMap(map,"WHEN_IN_FOCUSED_WINDOW");
              printActionMap( getActionMap() , "JTextArea");
              //list(map, map.keys());
              // List keystrokes in all related input maps
            // list(map, map.allKeys());
         public void fixTAB()
              Set newForwardKeys = new HashSet ();
              newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false));
              this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
              Set newBackwardKeys = new HashSet ();
              newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK, false));
              this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, newBackwardKeys);
              Set forwardKeys = this.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
    //          System.out.println ("Desktop forward focus traversal keys: " + forwardKeys);
              Set backwardKeys = this.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
    //          System.out.println ("Desktop backward focus traversal keys: " + backwardKeys);
             this.setFocusTraversalKeysEnabled(true);
         public static void printActionMap(ActionMap actionMap, String who)
         {     //     System.out.println("Action map for " + who + ":");
              Object[] keys = actionMap.allKeys();
              if (keys != null)
                   for (int i = 0; i < keys.length; i++)
                        Object key = keys;
                        Action targetAction = actionMap.get(key);
                   //     System.out.println("\tName: <" + key + ">, action: " + targetAction.getClass().getName());
         public static void printInputMap(InputMap inputMap, String heading)
              //System.out.println("\n" + heading + ":");
              KeyStroke[] keys = inputMap.allKeys();
              if (keys != null)
                   for (int i = 0; i < keys.length; i++)
                        KeyStroke key = keys[i];
                        Object actionName = inputMap.get(key);
                   //     System.out.println("\tKey: <" + key + ">, action name: " + actionName);
    public void paste()
    public void focusGained(java.awt.event.FocusEvent event)
              //System.out.println("Hman " + event.paramString());
         if(event.getOppositeComponent() != null)
              if(event.getOppositeComponent().getParent() != null)
                   if (findRoot(event.getOppositeComponent()) != null && findRoot(this) != null)
                        if ( isEnabled() && findRoot(event.getOppositeComponent()) == findRoot(this))
                        selectAll();
         public Component findRoot(Component _cc)
              while (_cc.getParent() != null)
                   cc = cc.getParent();
                   //System.out.println("Parent:" + _cc);
                   if (_cc instanceof TradeDetailForm)
                   return _cc;
              return null;
    public void focusLost(java.awt.event.FocusEvent event)
         Begin Nirmal 1: Requirements 3.1 issues.
         To fix: getValue() method never returns more than the rows.
         New method added to ensure user entered text never goes beyond Rows
    * Method to ensure the getValue() never returns more than the rows.
    * will return -1 if the rows are out of range
    * @param KeyEvent
    * @return int
    public int ensureNotBeyondRows(KeyEvent e)
              String[] s = getValue();
              if (s==null)
                   return 0;
              if (s.length>rows)
                   setText(retainText);
                   return -1;
              String str=getText();
              insert(e.getKeyChar()+"", getCaretPosition());
              s = getValue();
              setText(str);
              if (s.length>rows)
                   setText(retainText);
                   return -1;
              return 0;
         End Nirmal 1:
    // main Method
    // processComponentKeyEvent Method
    public void keyTyped(KeyEvent e)
         /* Naga */
              System.out.println("inside keyTyped");
              System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
         /*try
                   java.lang.Thread.sleep(2000);
              catch(InterruptedException ie)
         try {
    int curPos2 = getCaretPosition();
    int curLine2 = getLineOfOffset(curPos2);
    //System.out.println( "curline:" + curLine2 + " of " + rows);
    char[] tmp = {e.getKeyChar()};
    int curPos1 = getCaretPosition();
    int line1 = getLineOfOffset(curPos1) ;
    int startOfLine = getLineStartOffset(line1) ;
    if( curPos1 == startOfLine && line1 > 0)
    if ((tmp[0] == ':') || (tmp[0] == '-' )){
    // System.out.println("hman3");
    e.consume();
    return;
                   Begin Nirmal 2: Requirements 3.1 issues.
                   To fix: getValue() method never returns more than the rows.
                   New method added to ensure user entered text never goes beyond Rows
                   if (!isArrowKey(e) &&
                        (e.paramString().indexOf("Enter") == -1 ) &&
                        !isBackspaceKey(e)) {
                             int maxLimitFlg=ensureNotBeyondRows(e);
                             setCaretPosition(curPos2);
                             if (maxLimitFlg == -1)
                                  e.consume();
                                  return;
                   End Nirmal 2:
    // System.out.println("e.paramString()" + e.paramString());
    // System.out.println("place 2 " + e.paramString());
    if (!(StringFormatter.isValidSwift(tmp[0])) && !(functionKey(e)) && notMoveForward(e))
    // System.out.println("hman2 isaction" + e.isActionKey());
    // System.out.println("KeyTyped" + e.getKeyChar()+ e.getKeyText(e.getKeyCode()) + "/keycode" + e.getKeyCode() + "/modifiers" + e.getModifiers() );
    e.consume();
    return;
    int curPosInLine = -1;
    int firstPos = -1;
    if (getText().length() < maxTextAllowed ||
    (KeyCode == KeyEvent.VK_UP || KeyCode == KeyEvent.VK_BACK_SPACE))
    int curPos = getCaretPosition();
    if (!(functionKey(e)))
    e.setKeyChar( (new String( tmp ).toUpperCase()).toCharArray()[0]);
    curPos2 = getCaretPosition();
    curLine2 = getLineOfOffset(curPos2);
    //System.out.println( "curline:" + curLine2 + " of " + rows);
    if (curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) )
    // System.out.println("hman1");
    e.consume();
    return;
    else {
    String oldText = getText();
    // super.processKeyEvent(e);
    if (getNumberOfLines(getLineCount()) == -1 && !(functionKey(e)))
    setText(oldText);
    invalidate();
    setCaretPosition(curPos);
    } } catch (javax.swing.text.BadLocationException evt) {
    System.out.println("Bad Location Exception in processKeyEvent");
    public void keyPressed(KeyEvent e){
              //System.out.println("keyPressed" + e.getKeyCode()+ e.getKeyText(e.getKeyCode()));
                   retainText = getText();//retain always the latest text
                   /* Naga */
                   //System.out.println("retainText " + retainText);
                   System.out.println("inside keyPressed");
                   System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
                   /*try
                        java.lang.Thread.sleep(2000);
                   catch(InterruptedException ie)
    public void keyReleased(KeyEvent e){
              //System.out.println( "keyReleased" + e.getKeyCode()+ e.getKeyText(e.getKeyCode()));
         String []s = getValue();
         /* Naga */
         System.out.println(" inside keyReleased");
         System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
         /*try
              java.lang.Thread.sleep(2000);
         catch(InterruptedException ie)
              /*try
                   System.out.println("s " + s[0]);
                   System.out.println("s " + s[1]);
                   System.out.println("s " + s[2]);
                   System.out.println("s " + s[3]);
              catch(Exception e1)
              //System.out.println("s.length " + s.length);
              //System.out.println("rows " + rows);
              if (s!=null && s.length>rows)
                   System.out.println("setting text");
                   //setText(retainText);
                   invalidate();
         public boolean isTab(KeyEvent e)
              if (e.paramString().indexOf("keyChar=Tab") == -1)
              return false;
              } else
                   return true;
         public boolean keepProcessing(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("keyChar=Backspace") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Left") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Down") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Up") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Delete") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Right") != -1 ) { return true; }
              return false;
         public boolean isArrowKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Left") != -1 ||
                   e.paramString().indexOf("Down") != -1 ||
                   e.paramString().indexOf("Up") != -1 ||
                   e.paramString().indexOf("Right") != -1 )
                   return true;
              return false;
         public boolean isBackspaceKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Backspace") != -1)
                   return true;
              return false;
         public boolean isDeleteKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Delete") != -1)
                   return true;
              return false;
    public boolean notMoveForward(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Backspace") == -1 &&
              e.paramString().indexOf("Left") == -1 &&
              // e.paramString().indexOf("keyText=Down") == -1 &&
              e.paramString().indexOf("Up") == -1 &&
              e.paramString().indexOf("Delete") == -1 ) { return true; }
              return false;
    // processKeyEvent Method
    public void processKeyEvent(java.awt.event.KeyEvent e)
    //     System.out.println( "processKeyEvent");
         /* Naga */
         System.out.println(" inside processKeyEvent");
         System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
                   if (e.paramString().indexOf("KEY_PRESSED") != -1) {
                        KeyText=e.paramString();
                   } else {
                        KeyText="";
                   KeyCode=e.getKeyCode();
    int filledRows = (getText().length()-1)/columns + 1;
    if (KeyCode == KeyEvent.VK_ENTER && filledRows >= rows)
    return;
    try {
                   if (isArrowKey(e) || isBackspaceKey(e) || isDeleteKey(e)) {
                        super.processKeyEvent(e);
                        return;
    int curPos2 = getCaretPosition();
    int curLine2 = getLineOfOffset(curPos2);
    // System.out.println( "curline:" + curLine2 + " of " + rows);
    if (curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) )
                             //System.out.println("hman5");
    e.consume();
    return;
    int curPosInLine = -1;
    int firstPos = -1;
    if (getText().length() < maxTextAllowed)
    int curPos = getCaretPosition();
    curPos2 = getCaretPosition();
    curLine2 = getLineOfOffset(curPos2);
    int curlinepos = getLineStartOffset(curLine2) ;
                   if ( (curLine2 + 1 == rows) && (curPos2 - curlinepos >= getColumns() - 1) && notMoveForward(e))
                        e.consume();
    return;
    if ((curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) ))
    // System.out.println("hman6");
    e.consume();
    return;
    } else {
    String oldText = getText();
    // System.out.println("hman7");
    super.processKeyEvent(e);
    if (getNumberOfLines(getLineCount()) == -1 && !(functionKey(e)))
    // System.out.println("hman8");
    setText(oldText);
    invalidate();
    setCaretPosition(curPos);
    } } catch (javax.swing.text.BadLocationException evt) {
    System.out.println("Bad Location Exception in processKeyEvent");
    // processFunctionalKeys Method
    public boolean processFunctionalKeys(java.awt.event.KeyEvent e)
    // System.out.println( "processFunctionalKeys");
    if (KeyCode == KeyEvent.VK_BACK_SPACE ||
    KeyCode == KeyEvent.VK_ESCAPE ||
    KeyCode == KeyEvent.VK_PAGE_UP ||
    KeyCode == KeyEvent.VK_PAGE_DOWN ||
    KeyCode == KeyEvent.VK_END ||
    KeyCode == KeyEvent.VK_HOME ||
    KeyCode == KeyEvent.VK_LEFT ||
    KeyCode == KeyEvent.VK_UP ||
    KeyCode == KeyEvent.VK_RIGHT ||
    KeyCode == KeyEvent.VK_DOWN ||
    KeyCode == KeyEvent.VK_DELETE
    //System.out.println("Process the KEY getkey:" + e.getKeyChar() + "/getcode:" + e.getKeyCode());
    super.processKeyEvent(e);
    return true;
    else
    return false;
    public boolean functionKey(java.awt.event.KeyEvent e)
    // System.out.println( "functionKey");
    if (KeyCode == KeyEvent.VK_BACK_SPACE ||
    KeyCode == KeyEvent.VK_ESCAPE ||
    KeyCode == KeyEvent.VK_PAGE_UP ||
    KeyCode == KeyEvent.VK_PAGE_DOWN ||
    KeyCode == KeyEvent.VK_END ||
    KeyCode == KeyEvent.VK_HOME ||
    KeyCode == KeyEvent.VK_LEFT ||
    KeyCode == KeyEvent.VK_UP ||
    KeyCode == KeyEvent.VK_RIGHT ||
    KeyCode == KeyEvent.VK_DOWN ||
    KeyCode == KeyEvent.VK_DELETE
    //System.out.println("Process the KEY getkey:" + e.getKeyChar() + "/getcode:" + e.getKeyCode());
    //super.processKeyEvent(e);
    return true;
    else
    return false;
    // getLineCount Method - Returns -1 if number of lines is not between 1 to 4.
    /* This method return -1 if number of lines is not between 1 to 4.
    Pass in getLineCount() to get number of lines for all elements.
    JTextArea separates elements by new line character.
    BnyTextArea treats each row as a line.
    public int getNumberOfLines(int elementCount)
    int lineCount = 0;
    int startPos = 0;
    int endPos = 0;
    for (int i = 0; i <= elementCount - 1; i++) {
    lineCount = lineCount + getLineCountOfElement(i);
    if (lineCount == -1 || lineCount > rows) {
    lineCount = -1;
    break;
    return lineCount;
    // getSpacePos Method - this method finds the first position of space found.
    public int getSpacePos(int pos)
              Begin Nirmal 3: Requirements 3.1 issues.
              Modified the end limit from 0 to pos-columns,
              so that to avoid the return index value from previous lines
              int endLimit=pos-columns;
              if (endLimit<0) {
                   endLimit=pos;
    for (int i = pos; i > endLimit; i--) {
    if (getText().charAt(i) == ' ' || getText().charAt(i) == '\n') { // 11/14/03 Eaten treat \n as space
                        return i;
    return -1;
              End Nirmal 3:
    // getLineCountOfElement Method - returns -1 if number of lines is not between 1 to 4.
    public int getLineCountOfElement(int line)
    int lineCount = 1;
    try {
    int startPos = getLineStartOffset(line) ;
    int endPos = getLineEndOffset(line) ;
    if (moreThanNumOfColumns(startPos, endPos)) {
    lineCount = 2;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    lineCount = 3;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    lineCount = 4;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    return -1;
    } catch (javax.swing.text.BadLocationException e) {
    System.out.println("Bad Location Exception in getLineCountOfElement");
    return lineCount;
    // moreThanNumOfColumns Method
    public boolean moreThanNumOfColumns(int startPos, int endPos)
    if ((endPos - startPos) > (columns + 1))
    return true;
    else
    return false;
    // getNewLineCount Method
    public int getNewLineCount()
    int count = 0;
    boolean rc = true;
    int pos = getText().indexOf(KeyEvent.VK_ENTER, 0);
    if (pos == -1)
    rc = false;
    else
    count++;
    while (rc) {
    pos = getText().indexOf(KeyEvent.VK_ENTER, pos+1);
    if (pos == -1)
    rc = false;
    else
    count++;
    return count;
    // getValue Method
    public String[] getValue()
    // System.out.println(getText());
    int lines = getLineCount();
    int spacePos = 0;
    String str = new String();
    Vector strings = new Vector();
    boolean newLine=true;
    /*Nirmal : this boolean is to add the empty only in new line.
    To avoid those lines which end with \n
    if (getDocument().getLength() > 0) {
    for (int i = 0; i < lines; i++) {
                        newLine=true;
    try {
    int startPos = getLineStartOffset(i) ;
    int endPos = getLineEndOffset(i) + 1;
    /* Naga */
    //System.out.println("startPos " + startPos);
    //System.out.println("endPos " + endPos);
    //System.out.println(i + "HHMAN startPos = " + getLineStartOffset(i));
    //System.out.println(i + "HHMAN endPos = " + getLineEndOffset(i));
    while (moreThanNumOfColumns(startPos,endPos)) {
                                  newLine=false;
    int tempEndPos = 0;
    tempEndPos = startPos + columns;
    System.out.println("tempEndPos " + tempEndPos + " columns " + columns);
    spacePos = getSpacePos(tempEndPos);
    if (spacePos == -1) {
    if (startPos >= getDocument().getLength())
    break;
    else {
    if (tempEndPos >= getDocument().getLength())
    spacePos = getDocument().getLength();
    else {
    spacePos = startPos + columns;
    str = getText().substring(startPos,spacePos);
    if (!(str.trim().equals(""))) {
                                       strings.addElement(str.trim());
    startPos = spacePos;
                             if (startPos < endPos) {
         str = getText().substring(startPos,endPos - 1).trim();
         if(str!=null) {
              if(str.trim().length()>0) {
                                            strings.addElement(str);
                                            continue;
                                       } else {
                                            if(newLine) {
                                                 strings.addElement(str);
    /*Nirmal commented the below lines to fix existing issue
    of adding even empty lines entered in textbox */
    //if ((str==null) || (str.length()==0)) continue;
    //if (!(str.trim().equals(""))) strings.addElement(str);
    } catch (javax.swing.text.BadLocationException e) {
    System.out.println("Bad Location Exception in getValue");
    String[] strs = new String[strings.size()];
    strings.copyInto(strs);
    return strs;
    } else
    return null;
         public void clear() {
    setText("");
    // invalidate();
    // repaint();
    // fixTAB();
    public int getColumnsX()
    if (columnLimits != null)
    int curPos = getCaretPosition();
    //System.out.println("getCaretPosition()" + curPos);
    if (curPos > 0)
    for (int i = 0;i < columnLimits.length;i++)
    curPos = curPos - columnLimits[i];
    if (curPos < 1)
    //System.out.println("getNumberOfLines(curElem)" + i);
    return columnLimits[i];
    } else
    return columns;
    return 0;
         public void setRowLimitX(int rows,int columns)
    maxTextAllowed = rows * columns;
    setRows(_rows);
    rows = _rows;
    columns = _columns;
    setFont(fixedFont);
    setBorder(new BevelBorder(BevelBorder.LOWERED));
    setLineWrap(true);
    setWrapStyleWord(true);
    Font fixedFont = new Font("Courier", Font.PLAIN, 12);
    FontMetrics fm = getFontMetrics(fixedFont);
    int width = fm.charWidth('W') * (35 + 1);
    int height = DEFAULT_LABEL_HEIGHT * 3 ;
    setPreferredSize(new Dimension(width, height));
    public void setEditable(boolean editable)
    super.setEditable(editable);
    super.setEnabled(editable);
    setFocusable(editable);
    if (editable)
    setForeground(Color.black);
    else
    setForeground(Color.gray);
    fixTAB();
    // add your data members here
    // add your data members here
    private int rows = 0;
    private int columns = 0;
    private int[] columnLimits = null;
    private int maxTextAllowed = 0;
    private Font fixedFont = new Font("Courier", Font.PLAIN, 12);
    public final static int LEFT_LABEL_WIDTH = 100;
         public final static int DEFAULT_LABEL_HEIGHT = 20;

    You posted way too much code. 90% of the code is not related to the "backspace" problem. We want compileable and executable code, but only that code that is relevant to the problem.
    Anyway, instead of handling KeyEvents you should read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings for the recommended approach.
    Also you may want to check out this posting which has some information on the backspace KeyStroke:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=566748

  • Problem in printing to LPT1 through applet?

    Hello everyone,
    I am having problem in printing through Applet in LPT1 of remote client machine using "gridDoubleClicked" method of customized "GridPanel" which is third party component. The class structure is given below:
    public class GridPanel extends Panel implements GridPanelInterface, AdjustmentListener, KeyListener, FocusListener, Serializable
    }I am using above class to populate data in table and perform "double click" action. I am using JDK 1.5 and a self signed jar to access from remote machines through applet.The code, I am using is given below:
    public class testApplet extends Applet {
        printToLPT1 lpanel =new printToLPT1();
        public void init() {
          this.setLayout(new BorderLayout());
          this.add(lpanel, BorderLayout.CENTER);
          this.setSize(380, 250);
    public class printToLPT1 extends Frame{
    GridPanel grid;
    public printToLPT1() throws Exception {
    grid.addGridListener(new GridAdapter() {
                public void gridDoubleClicked(GridEvent ge) {               
                    testPrint();
    public static void testPrint() throws Exception {
            try {
                BufferedOutputStream pos = new BufferedOutputStream(new FileOutputStream("LPT1"));
                String str = "\n\n\n\n\n\n\n\n\n\n\n";
                pos.write(str.getBytes());
                pos.flush();
                pos.close();
            } catch (Exception fnfe) {
                throw new Exception("PRINTER SETUP IS NOT PROPER");
    }For applet, I have used following script in login.html:
    <APPLET
         height="200px"
         archive="testprinter.jar,jbcl.jar,grid.jar,plugin.jar" 
         width="390px"
         align="top"
         code="test.testApplet.class"
         name="Testing"
        ALT="<P>This applet requires Java to be enabled!  Check the browser options or see your SysAdmin." MAYSCRIPT>
        <P>This page requires Java!  Get it free from <A HREF='http://www.java.com/'>www.java.com</A>.</P>
    </APPLET>
    ------------------- If signed jar file of application is run using command line in client machine then "double clicked" of GridPanel method works fine and send signal to printer at LPT1 port but when same application is called using applet and accessed from remote machine with printer in LPT1 port, in that time also "double clicked" of GridPanel method works fine but printer could not be found and Exception is thrown java.lang.Exception:"PRINTER SETUP IS NOT PROPER" . Why is this happening? Can anyone suggest me the solution for this problem?
    Thanks in advance.
    -Ritesh
    Edited by: ritesh163 on Apr 15, 2010 2:56 PM

    The SSCCE for this problem is given below:
    //Applet class
    package test;
    import java.awt.BorderLayout;
    import javax.swing.JApplet;
    public class testApplet extends JApplet {
        testPrint lpanel =new testPrint();
        public void init() {
          this.setLayout(new BorderLayout());
          this.add(lpanel, BorderLayout.CENTER);    
          this.setSize(380, 250);    
    // Printing class...
    package test;
    import com.borland.jbcl.layout.XYConstraints;
    import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import wdn.grid.GridAdapter;
    import wdn.grid.GridData;
    import wdn.grid.GridEvent;
    import wdn.grid.GridPanel;
    public class testPrint extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private javax.swing.JButton btnPrint;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration     
        GridPanel grid;
        GridData gdata;
        String[] gridCols = {
            "Receipt No", "Name"};
        public testPrint() {
            grid = new GridPanel(0, 8);
            gdata = new GridData(0, 8);
            grid.setRowHeaderWidth(0);
            grid.setGridData(gdata);
            grid.setMultipleSelection(false);
            grid.setColWidths("100,60");
            grid.setColHeaders(gridCols);
            setGridProperties(grid);
            grid.setColSelection(false);
            this.setVisible(true);
            grid.addGridListener(new GridAdapter() {
                public void gridDoubleClicked(GridEvent ge) {
                   //This event works fine...
                    System.out.println("Press Re-Print button...");
                    try{
            stringToPrinter("testing by grid \n\n\n\n\n\n\n\n\n\n\n\n\n");
            }catch(Exception ex){
                ex.printStackTrace();
                public void gridCellsClicked(GridEvent ge) {
                    btnPrint.setEnabled(true);
            initComponents();
            jPanel1.add(grid, new XYConstraints(52, 60, 100, 150));
            grid.deleteRows(1, grid.getNumRows());
            grid.insertRow(1);
                        grid.setCellText(1, 1, "12134", false);
                        grid.setCellText(2, 1, "test" + "", false);
                        grid.repaintGrid();
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            btnPrint = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            btnPrint.setText("Print");
            btnPrint.setToolTipText("to Print");
            btnPrint.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnPrintActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(36, 36, 36)
                    .add(btnPrint)
                    .addContainerGap(287, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(198, Short.MAX_VALUE)
                    .add(btnPrint)
                    .add(57, 57, 57))
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {                                        
            try{
            stringToPrinter("testing \n\n\n\n\n\n\n\n\n\n\n\n\n");
            }catch(Exception ex){
                ex.printStackTrace();
        public static void setGridProperties(GridPanel grid) {
            grid.setRowHeaderWidth(0);
            grid.setAutoResizeColumns(true);
            grid.setRowNumbers(true);
            grid.setCellSelection(false);
            grid.setRowSelection(true);
            grid.setHighlightColor(Color.blue);
            grid.setHighlightTextColor(Color.white);
            grid.setAutoResizeRows(true);
            grid.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyChar() == KeyEvent.VK_SPACE) {
                public void keyReleased(KeyEvent e) {
        public static void stringToPrinter(String str) throws Exception {
            try {
                System.out.println("inside stringToPrinter...");
                BufferedOutputStream pos = new BufferedOutputStream(new FileOutputStream("LPT1"));
                System.out.println("inside stringToPrinter...1-pos::"+pos);
                pos.write(str.getBytes());
                pos.flush();
                pos.close();
            } catch (Exception fnfe) {
                throw new Exception("PRINTER SETUP IS NOT PROPER");
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new testPrint().setVisible(true);
    }

  • Jpopupmenu visibility problem with JWindows

    Hello,
    BACKGROUND:
    I am attempting to implement a feature similar to one found in the netbeans IDE for a programming editor I am helping to write. The feature is an autocomplete/function suggestion based on the current word being typed, and an api popup for the selected function.
    Currently a JPopupMenu is used to provide a list of suggested functions based on the current word being typed. EG, when a user types 'array_s' a JPopupMenu pops up with array_search, array_shift, array_slice, etc.
    When the user selects one of these options (using the up/down arrow keys) a JWindow (with a jscrollpane embedded in it) is made visible which displays the api page for that particular function.
    PROBLEM:
    The problem is that when a user scrolls down the JWindow the JPopupmenu disappears so he user cannot select another function.
    I have added a ComponentListener to the JPopupMenu so that when componentHidden is called I can do checks to see if it should be visible and make visible if necessary. However, componentHidden is never called.
    I have added a focuslistener to the JPopupMenu so that when it loses focus I can do the same checks/make visible if necessary. This function is never called.
    I have added a popupMenuListener but this tells me when it is going to make something invisible, not actually when it's done it, so I can't call popup.setVisible(true) from popupMenuWillBecomeInvisible because at that point the menu is still visible.
    Does anyone have any suggestions about how I can scroll through a scrollpane in a JWindow whilst still keeping the focus on a separate JPopupMenu in a separate frame?
    Cheers

    The usual way to do popup windows (such as autocomplete as you're doing) is not to create a JPopupMenu, but rather an undecorated (J)Window. Stick a JList in the popup window for the user to select their choice from. The problem with using a JPopupMenu is just what you're experiencing - they're designed to disappear when they lose focus. Using an undecorated JWindow, you can control when it appears/disappears.
    See this thread for information on how to do this:
    http://forum.java.sun.com/thread.jspa?threadID=5261850&messageID=10090206#10090206
    It refers you to another thread describing how to create the "popup's" JWindow so that it doesn't steal input focus from the underlying text component. Then, further down, it describes how you can forward keyboard actions from the underlying text component to the JWindow's contents. This is needed, for example, so the user can keep typing when the autocomplete window is displayed, or press the up/down arrow keys to select different items in the autocomplete window.
    It sounds complicated, but it really isn't. :)

  • ActionEvent Vs FocusListener

    Hi all,
    and thx in advance.
    My problem look like the Bug ID: 4224932
    Environment Description :
    -     I have some some JtextField.
    -     each JtextField have an difference instance of FocusListener listener.
    -     On focusLost I�m doing a validation (check) of JtextField content.
    -     I have also OK Button.
    Problem Description:
    -     When I click on OK button first I receive the an ActionEvent and at the end we have focusLost Event.
    Consequence:
    -     last JtextField does�t have a validation.
    Restriction:
    - This problem append only on HPUX, on Windows I receive first the focusLost and then the ActionEvent.

    Swing related questions should be posted in the Swing forum.
    Use an InputVerifier, not a FocusListener.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • Problem: do something, if jumping in another textfield through tab-key

    hi,
    please, maybe can anybody help me.....
    I've got some textfields (JTextField) in a swing-application. by jumping in another textfield through pressing the tab-key, something should happen.
    I wrote the following code, but it doesn't works ;-(
    textfieldReleaseOf.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_TAB ) {
    System.out.println("tabspr...................");
    else {
    System.out.println("kein tabspr...................");
    thanks for helping......

    From your problem description it seems that you need to do something not only when the user presses TAB but also if the user switches to some other textfield. Although it could be accomplished using the KeyListener as you have already done, a better way would be to use the FocusListener. You can add a FocusListener to your JComponent (or JTextField) object. It will fire events whenever the user presses tab to move onto the next field and even when the user clicks on the next field using a mouse.

  • More event problems

    Hello again, I have yet another event problem. When I try to use this code I get an error saying Abstract class actionPerformed is not implemented in non- abstract class TableWindow. I'm not quit sure how I'm supposed to implement it.

    Here is what I believe to be the relevant code. addWindowListener works but addFocusListener returns the error.
    // Table window
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableWindow extends Frame implements ActionListener
    public TableWindow ()
    Create Window
    super ("Test Window");
    setBackground (SystemColor.control);
    setLocation (0, 0);
    setLayout (new GridLayout (5, 5));
    addWindowListener (new WindowAdapter ()
    public void windowClosing (WindowEvent e)
    try
    if (Connected == true)
    // Close the Statement
    stmt.close ();
    // Close the connection
    con.close ();
    catch (SQLException sqle)
    dispose ();
    System.exit (0);
    tPane = new JTabbedPane ();
    tPane.addChangeListener (new ChangeListener ()
    public void stateChanged (ChangeEvent c)
    //Status.setText ("Clicked");
    tablePane = new JPanel ();
    recordPane = new JPanel ();
    recordPane.addFocusListener(new FocusListener()
    public void focusGained(FocusEvent e)
    Status.setText ("Clicked");
    queryPane = new JPanel ();
    TName1 = new TextField (25);
    TName2 = new TextField (25);
    TName3 = new TextField (25);
    idField = new TextField (10);
    idField2 = new TextField (10);
    TitleField = new TextField (25);
    TitleField2 = new TextField (25);
    result = new TextArea ("Under Construction", 5, 30);
    NewT = new Button ("New Table");
    NewR = new Button ("New Record");
    NewQ = new Button ("New Query");
    NewT.addActionListener (this);
    NewR.addActionListener (this);
    NewQ.addActionListener (this);
    TNameLabel1 = new Label ("Enter name of table here");
    TNameLabel2 = new Label ("Enter name of table here");
    TNameLabel3 = new Label ("Enter name of table here");
    idLabel = new Label ("Enter movie ID here");
    TitleLabel = new Label ("Enter title of Movie here");
    TitleLabel2 = new Label ("Enter title of Movie here");
    tablePane.add (TNameLabel1);
    tablePane.add (TName1);
    tablePane.add (NewT);
    recordPane.add (TNameLabel2);
    recordPane.add (TName2);
    recordPane.add (idLabel);
    recordPane.add (idField);
    recordPane.add (TitleLabel);
    recordPane.add (TitleField);
    recordPane.add (NewR);
    //recordPane.add (tableChoice);
    queryPane.add (TNameLabel3);
    queryPane.add (TName3);
    queryPane.add (TitleLabel2);
    queryPane.add (TitleField2);
    queryPane.add (NewQ);
    queryPane.add (result);
    Status = new Label ("");
    // make the window and add components to it
    tPane.addTab ("Table", tablePane);
    tPane.addTab ("Record", recordPane);
    tPane.addTab ("Query", queryPane);
    add (tPane, BorderLayout.CENTER);
    add (Status, BorderLayout.SOUTH);
    pack ();
    setVisible (true);
    public static void main (String args [])
    ConnectToDatabase ("vdds");
    TableWindow tw = new TableWindow ();
    }

  • Problem in comparing Two String

    Hi friends
    I have a strange Problem, i am able to find out the Reason for this problem.
    In my Program i use a JTextField with implements the FocusListener. i just get the Text of this JTextField and retrive a record from DataBase which is Equal to the JTextField's Text. yes it retrives the same record. Now i want to compare these two Text. I mean the JTextFied text and the text which i retrived from the Database.
    My code is this
    public void focusLost (FocusEvent fe) {
              Object obj = fe.getSource ();
          if (obj == txtMemberId)
                        memberId = txtMemberId.getText().toString();     
                        int memberDays,memberBooks,memberCat,heldBooks;
                        String mname,memberNo;                              //Use for Comparing the Member's Id.
                        boolean find = false;                         //To Confirm the Member's Id Existance.
                        try
                             //SELECT Query to Retrieved the Record.
                             String q = "SELECT * FROM Members WHERE RollNumber= '"+memberId+"'";
                             ResultSet rs = st.executeQuery (q);     //Executing the Query.
                             rs.next ();                    //Moving towards the Record.
                             memberNo = rs.getString ("RollNumber");
                                                                //Storing the Record.
                             boolean ans=memberNo.equals(memberId);
                             System.out.println("STAUS OF THE COMPARISION:"+ans);
                             if (ans)
                             {               //If Record Found then Display Records.
                             System.out.println("RECORD FOUND DON'T WORRY");
                             find = true;
                             memberCat=rs.getInt("MCat");
                                  heldBooks=rs.getInt("Bcnt");
                                  System.out.println("HELD BOOK COUNT IS::"+heldBooks);
                                  mname=rs.getString ("FirstName");
                                  txtMemberName.setText (""+mname);
                                  gblname=mname;
                                  rs.close();
                                  ResultSet rs1= st.executeQuery("Select * from Mecat where MCat = " + memberCat + "" );
                                  rs1.next();
                                  memberBooks=rs1.getInt("Blmt");
                                  System.out.println("BOOK LIMITED TO::"+memberBooks);
                                  memberDays=rs1.getInt("Dlmt");
                                  if(heldBooks==memberBooks)
                                       txtClear();
                                       JOptionPane.showMessageDialog (this, "Book Limit Reached");
                                       dispose();
                                   GregorianCalendar gcal=new GregorianCalendar();
                                     id1= gcal.get(Calendar.DATE);
                                     im=(int)gcal.get(Calendar.MONTH)+1;
                                     iy=gcal.get(Calendar.YEAR);
                                     vd=id1+memberDays;
                                     vm=im;
                                     vy=iy;
                                     String xx,yy,zz;
                                     if(id1<10) {
                                         xx="0"+id1;
                                     } else {
                                         xx = ""+id1;
                                     if(im<10) {
                                         yy="0"+im;
                                     } else {
                                         yy = ""+im;
                                     idate=xx+"/"+yy+"/"+iy;
                                     //  String vdate=vd+"/"+vm+"/"+vy;
                                     //********************                        to calcutlate return date
                                     //System.out.println("came here1!!!");
                                     while(vd>31) {
                                         if(im==1||im==3||im==5||im==7||im==8||im==10||im==12){
                                             if(vd>31){
                                                 im=im+1;
                                                 vd=vd-31;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;
                                         if(im==4||im==6||im==9||im==11){
                                             if(vd>30){
                                                 im=im+1;
                                                 vd=vd-30;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;}
                                         if(im==2){
                                             if(vd>28){
                                                 im=im+1;
                                                 vd=vd-28;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;
                                    vdate = vd+"/"+im+"/"+iy;
                                 //System.out.println("came here3!!!");
                             //     txtMemberId.setText ("" + memberId);
                                  txtDate1.setText(idate);
                                  txtDate2.setText(vdate);
                             else {
                                  find = false;
                                  if (find == false) {
                                  JOptionPane.showMessageDialog (this, "Really Record not Found.");
                                  System.out.println("DON'T WORRY FIND A WAY");
                        catch (SQLException sqlex) {
                             if (find == false) {
                                  //txtClear ();          //Clearing the TextFields.
                                  JOptionPane.showMessageDialog (this, "Really Record not Found.");
                                  txtDate1.setText("");     
                                  txtDate2.setText("");
                                  txtMemberId.setText("");
                                  txtMemberId.requestFocus ();
                        catch(Exception e)
                             e.printStackTrace();
    when i compare those two Text By using this Line
    boolean ans=memberNo.equals(memberId);[b]It retruns False
    please tell me what would be the Problem here
    Thank you for your service
    Cheers
    Jofin

    Hi
    Thank you very much, it is working for me. i am very greatful to you .
    Thank you for your service
    jofin

  • Highlighting problems

    Hi,
    i have created a specific JTextField that, among other things, only can take in numbers. To do this I have modified the Document of the textfield.
    My problem is that the user can toggle between two different textfields using a combo box. One textfield of this kind and one standard JTextField. When the user toggles the focus should be on the text field, and if there is text in the textfield it should be highlighted. This works fine for the standard JTextField using requestFocus() on the textfield, and a FocusListener that does a selectAll() when the text field recieves focus. But my "enhanced" textfield gets a null pointer exception when the selectAll() occurs. Any ideas?
    The TextFields new Document
    protected Document createDefaultModel() {
    return new FaTkTaxNrDocument();
    protected class FaTkTaxNrDocument extends PlainDocument
    public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException
    char[] source = str.toCharArray();
    int size = source.length;
    char[] result = new char[size];
    int j = 0;
    boolean dashSet = false;
    // Ska endast f� plats 7 tecken
    if(this.getLength() > 7) {
    return;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source)) {
    result[j++] = source[i];
    if (offs+i == 6) {
    dashSet = true;
    else if (offs == 6 && Character.isSpaceChar(source[i])) {
    result[j++] = '-';
    else {
    // System.err.println("insertString: " + source[i]);
    if(dashSet) {
    super.insertString(offs, new String(result, 0, j), a);
    super.insertString(offs, "-", null);
    else
    super.insertString(offs, new String(result, 0, j), a);
    The focus listener
    public class FaTkInputListener implements FocusListener
    public void focusGained(FocusEvent arg0)
         selectAll();
    The null pointer exception
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTextUI.damageRange(Unknown Source)
         at javax.swing.plaf.basic.BasicTextUI.damageRange(Unknown Source)
         at javax.swing.text.DefaultHighlighter.addHighlight(Unknown Source)
         at javax.swing.text.DefaultCaret.moveDot(Unknown Source)
         at javax.swing.text.DefaultCaret.moveDot(Unknown Source)
         at javax.swing.text.JTextComponent.moveCaretPosition(Unknown Source)
         at javax.swing.text.JTextComponent.selectAll(Unknown Source)
         at se.rsv.fa.tk.client.view.FaTkInputField$FaTkInputListener.focusGained(FaTkInputField.java:124)
         at java.awt.AWTEventMulticaster.focusGained(Unknown Source)
         at java.awt.Component.processFocusEvent(Unknown Source)
         at javax.swing.JComponent.processFocusEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.setFocusRequest(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Container.proxyRequestFocus(Unknown Source)
         at java.awt.Component.requestFocus(Unknown Source)
         at javax.swing.JComponent.grabFocus(Unknown Source)
         at javax.swing.JComponent.requestFocus(Unknown Source)
         at se.rsv.fa.tk.client.application.view.FaTkSearchBar.updateData(FaTkSearchBar.java:161)
         at se.rsv.fa.tk.client.control.FaTkModelListener.modelChanged(FaTkModelListener.java:54)
         at se.rsv.fa.tk.client.model.FaTkModel.fireChangedEvent(FaTkModel.java:78)
         at se.rsv.fa.tk.client.model.FaTkModel.setData(FaTkModel.java:110)
         at se.rsv.fa.tk.client.model.FaTkModel.runUpdate(FaTkModel.java:57)
         at se.rsv.fa.tk.client.view.FaTkSelectBox.fireDataEvent(FaTkSelectBox.java:89)
    at se.rsv.fa.tk.client.view.FaTkSelectBox$FaTkSelectionListener.itemStateChanged(FaTkSelectBox.java:109)
         at javax.swing.JComboBox.fireItemStateChanged(Unknown Source)
         at javax.swing.JComboBox.selectedItemChanged(Unknown Source)
         at javax.swing.JComboBox.contentsChanged(Unknown Source)
         at javax.swing.AbstractListModel.fireContentsChanged(Unknown Source)
         at javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source)
         at javax.swing.JComboBox.setSelectedItem(Unknown Source)
         at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
         at javax.swing.plaf.basic.BasicComboBoxUI.selectPreviousPossibleValue(Unknown Source)
    at com.sun.java.swing.plaf.windows.WindowsComboBoxUI.selectPreviousPossibleValue(Unknown Source)
         at com.sun.java.swing.plaf.windows.WindowsComboBoxUI$UpAction.actionPerformed(Unknown Source)
         at javax.swing.SwingUtilities.notifyAction(Unknown Source)
         at javax.swing.JComponent.processKeyBinding(Unknown Source)
         at javax.swing.JComponent.processKeyBindings(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at javax.swing.JComboBox.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processKeyEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

    Hi everyone, I have changed nick from mbr1799 to Mr. Brodd
    Ok guys, here is a program that reproduces the exception.
    Copy, compile and run!
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ClipTest extends JFrame
    implements ActionListener, KeyListener, FocusListener
    JTextField tf = new JTextField(20);
    JTextField tf2 = new JTextField(20);
    JComboBox cb = null;
    JComboBox cb2 = null;
    JButton b = null;
    JLabel l1 = new JLabel("Kommun");
    JLabel l2 = new JLabel("Taxenhet");
    Box toolBox = new Box(BoxLayout.X_AXIS);
    String keys = null;
    public ClipTest() {
    String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    try {
    UIManager.setLookAndFeel(lookAndFeel);
    catch (ClassNotFoundException e) {
    System.out.println("Couldn't find class for specified look and feel:" + lookAndFeel);
    System.out.println("Did you include the L&F library in the class path?");
    System.out.println("Using the default look and feel.");
    catch (UnsupportedLookAndFeelException e) {
    System.out.println("Can't use the specified look and feel ("+ lookAndFeel + ") on this platform.");
    System.out.println("Using the default look and feel.");
    catch (Exception e) {
    System.out.println("Couldn't get specified look and feel ("+ lookAndFeel+ "), for some reason.");
    System.out.println("Using the default look and feel.");
    //e.printStackTrace();
    init();
    public static void main(String[] args) {
    ClipTest ct = new ClipTest();
    public void init() {
    button.setBackground(Color.blue);
    Box topBox = new Box(BoxLayout.Y_AXIS);
    String[] listExamples = {"kommun", "taxenhet"};
    cb2 = new JComboBox(listExamples);
    cb2.addActionListener(this);
    tf.addFocusListener(this);
    tf2.addFocusListener(this);
    fixBox();
    this.getContentPane().add(toolBox);
    this.pack();
    setVisible(true);
    private void fixBox()
    toolBox.add(Box.createHorizontalStrut(5));
    toolBox.add(cb2);
    toolBox.add(Box.createHorizontalStrut(5));
    toolBox.add(l1);
    toolBox.add(tf);
    toolBox.add(Box.createHorizontalStrut(5));
    toolBox.add(l2);
    toolBox.add(tf2);
    l2.setVisible(false);
    tf2.setVisible(false);
    private void fixBoxKommun() {
    l1.setVisible(true);
    tf.setVisible(true);
    l2.setVisible(false);
    tf2.setVisible(false);
    tf.requestFocus();
    private void fixBoxTax() {
    l1.setVisible(false);
    tf.setVisible(false);
    l2.setVisible(true);
    tf2.setVisible(true);
    tf2.requestFocus();
    public void actionPerformed(ActionEvent e) {
    System.out.println("Action " + e.toString());
    String selected = (String)cb2.getSelectedItem();
    if(selected.equals("kommun"))
    fixBoxKommun();
    else if(selected.equals("taxenhet"))
    fixBoxTax();
    else
    System.out.println("Huh??");
    public void keyPressed(KeyEvent ke) {
    public void keyReleased(KeyEvent ke) {
    public void keyTyped(KeyEvent ke) {
    public void lostOwnership(Clipboard cb, Transferable tr)
    public void focusGained(FocusEvent fe) {
    if(tf.isVisible())
    tf.selectAll();
    else if(tf2.isVisible())
    tf2.selectAll();
    public void focusLost(FocusEvent fe) {
    }

Maybe you are looking for

  • No internet in wifi environment?

    I bought lately the new Ipad 3. Everything at home works fine, but when I go elsewhere (where there is Wifi), I get no connection with the internet. What is wrong or what should I change?

  • I need help making a program. It deals with BaseTime.

    Hey. Look im having a lot of trouble with a program. It is actually a program i have to make based on another program that i was given. it is called BaseTimeTest. here is the code of that program: import java.io.PrintStream; public class BaseTimeTest

  • Can we find the auth method used after a user has authenticated ?

    When a user is authenticated to an SAP ABAP system, they can use a userid and password, SNC or an SSO2 ticket. Is there a report, or some other way to get a list of user authentications over a period of time (e.g. during last 7 days) and indicate whe

  • New Role does not appear in home page after assigned to a user

    Hi there! I'm new at SAP Portals. I've created a role and assigned it to an user, but the corresponding tab does not appear in home page. I've already changed permitions to a group that is assigned to the user. I've seen in some posts that the role's

  • HAL policy file to change DPI

    I have Acer Aspire One... X works pretty much out of the box without xorg.conf file. Problem is that HAL doesn't seem to detect the DPI correctly... could someone please post the correct policy file to make fonts smaller?