FocusListener

Hi,
My prob is I got two JTextFields, only one editable. The text supposed to be entered, should only contain positive numbers (which I realize by the use of a Document). Ok so far.
When I tab from that editable JTextField to some other field or, say, put the focus on another widget, the input should be checked (value to big, whatever..) or written to the other JTextField (ineditable). I tried this with an ActionListener, but now it only works on ENTER. How to get that done when I already move the focus away from that field by a TAB?
(I thought about using a FocusListener, well - I'm not setting the focus to somewhere, but removing it from somewhere..???)
public class DlgCustomizeSelection03 extends javax.swing.JDialog {
     private JTextField tfGroupsStart;
     private JTextField tfStartCol;
// init and setting up GUI..
// init ActionListener
          tfGroupsStart.addActionListener( new ActionListener(){
               public void actionPerformed( ActionEvent ae){
                    // check the input and do the following if input is ok
                    tfStartCol.setText( String.valueOf(iVal));
(...)

should only contain positive numbers (which I realize by the use of a Document)...
put the focus on another widget, the input should be checked (value to big, whatever..)perhaps extending the function of the document you mention, to include
checking/disallowing when "value to big, whatever..", might be a better approach

Similar Messages

  • Possible to tell input type in a FocusListener?

    I'm using a rather simple FocusListener to select the text in text boxes when they gain focus.
    public class SelectOnFocus extends FocusAdapter {
         @Override
         public void focusGained(FocusEvent ev) {
              if (ev.getComponent() instanceof JTextComponent) {
                   JTextComponent tc = (JTextComponent) ev.getComponent();
                   tc.selectAll();
    }However, while this makes sense for when the user focuses the box with tab or a mnemonic, it doesn't make as much sense for when the user clicks in the text box. Is there any way to tell what kind of event caused the component to gain focus?

    if you want to remove the mouse from the ways to trigger a focusGained event,
    one way would be to add a mouseListener, in mousePressed remove the focusListener,
    and in mouseReleased add it back.
    I don't know that there's any guarantees the event order won't change, but for java1.6,
    mousePressed fires before focusGained

  • FocusListener not working for abstract button

    hi,
    FocusListener is not working for abstract button...
    Is there any other method which work similar to focusGained()...
    I think isFocusable() do that... Iam not sure about it.. Could anyone explain about it.
    It is needed very urgently.
    thanks in advance,
    regards,
    Deepa Raghuraman

    for all JComponent you have the hasFocus() method....

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

  • 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

  • Default background color and Focuslistener disapair on table?

    When I imp. TableCellRenderer on my table the default background color and Focuslistener disapair. What can I do to get it back and still keep TableCellRenderer on my table? This is how my TableCellRenderer looks:
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
            JFormattedTextField beloeb = new JFormattedTextField();
            beloeb.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter()));
            beloeb.setBorder(null);
            beloeb.setHorizontalAlignment(JTextField.RIGHT);
            if (value != null) {
                if (value instanceof Double) {
                    Double val = (Double) value;
                    beloeb.setValue(val);
                    if (val.doubleValue() < 0) {
                        beloeb.setForeground(Color.RED);
            beloeb.setFont(new Font("Verdana",Font.PLAIN, 11));
            beloeb.setOpaque(true);
            return beloeb;
        }

    I'm sorry to say this is a terrible example of a renderer. The point of using a renderer is to reuse the same object over and over. You don't keep creating Objects every time a cell is renderered. In your example your are creating:
    a) JFormattedTextField
    b) NumberFormatter
    c) DefaultFormatterFactory
    d) Font.
    So you start by extending the DefaultTableCellRenderer. A JLabel is used to display the text. There is no need to use a JFormattedTextField. All you want to do is format the data. So in your constructor for the class you would create a NumberFormatter that can be reused to format your data. Then your code in the renderer would look something like:
    if (value instanceof Double)
        Double val = (Double)value;
        setText( formatter.format(val) );
        if (negative)
          setForeground(Color.RED)
        else
            setForeground(table.getForeground());
    }Here is a really simple [url http://forum.java.sun.com/thread.jsp?forum=57&thread=419688]example to get you started

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

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

  • FocusListener not working

    hello everybody,
    class MyPanel extends JPanel implements FocusListener
       public MyPanel(String str)
          // some gui code of this class (ignored for brevity)
          dialog = new JDialog();
          dialog.getContentPane().add(this);
          dialog.setSize(450, 380);
          dialog.setResizable(false);
          dialog.addFocusListener(this);
          dialog.setVisible(true);
       public void focusGained(FocusEvent event)
          System.out.println("---> focusGained");
       public void focusLost(FocusEvent event)
          System.out.println("--- ccc ---> focusLost");
    // test code
    new MyPanel("FocusListener Test");

    Swing related questions should be posted in the Swing forum.
    The dialog itself doesn't gain focus. Some component on the dialog gains focus.
    Instead you should use a WindowListener listener and handle the windowActivated, windowDeactivated events.

  • FocusListener and FocusEvent.getSource() issue

    I have a composite JComponent that contains many other JComponents inside of it (like JButtons and JComboBoxes). Whenever these internal components lose focus, I need to know that the focus owner was the enclosing component, and not its inner JButtons and the like.
    The problem is that I have to add a FocusListener to each of the internal components, and whenever the focusLost() method gets called, the FocusEvent.getSource() method returns the internal component as the source, when I needed it to be the enclosing component instead.
    Any ideas on how I can make this work, or if it's even possible?

    Great idea, it works perfectly. I created an internal listener that invokes the outer component's processFocusEvent() and everything works as I wanted.
    Thanks.

  • FocusListener on JTextField

    Hi,
    I have a JFrame with 10 JTextFields in it. I have a Barcode scanner machine that scans number on a bill. As soon as the number is scanned, the number gets printed in the first text field.
    The problem is that I have added FocusListener to the JTextField so that as soon as the barcode number (length is 11) is filled in the text field, it shoud move to next text field.
    I am having problems here. As soon as my programme stars working, the focus is on to the first text field and the focus listener gets fired, but I wanted to do some action in the focusGained() only when the text field is filled with 11 digits of number and then move to next textfield.
    any idea on how to do this. A sample code snippet would be helpful.
    Thanks
    Mathew

    Hello Mathew
    I am too using barcode in My APP.
    any way what I think is you should add javax.swing.event.CaretListener
    to textfield
    text.addCaretListener(this);
    public void caretUpdate(javax.swing.event.CaretEvent e)
    if(e.getDot()==11|| txtBarcode.getText().length()==11)
    txtNext.requestFocus();
    }

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

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

  • FocusListener in JTextField

    I have a JTextField with a focusListener
    on it that is supposed to fire when the
    focus is lost. The JTextField is actually
    a field in a table. When I click into the
    field and then leave it fires but when
    I click enter on the field above it and
    it brings me to this field the focusLost
    never fires. Did anyone experience this
    or know what can be done?

    Problem solved.

  • FocusListener on JFrames not working...

    Hi. I have ab application with multiple JFrames. I want to find out when one gains focus. So I made a FocusListener and added it to each JFrame. However, my focusGained and focusLost methods aren't being called....
    am I going about this the wrong way?
    thanks for any assistance.

    Hi. I have ab application with multiple JFrames. I want to find out when one gains focus. So I made a FocusListener and added it to each JFrame. However, my focusGained and focusLost methods aren't being called....
    am I going about this the wrong way?
    thanks for any assistance.

Maybe you are looking for

  • IPad WiFi Greyed Out After Update To IOS 8.1!!!

    So I finally bit the bullet and upgraded my iPad from 7.1 to 8.1, but now I find that my wifi won't work!   So I've tried all the common things to try to get my wifi working again (resetting network settings; rebooting,  turning wifi networking off i

  • Perform Client import/export SCC8 with different release component between server

    Dear All Isn't possible to perform Client import/export SCC8 with different release component between server.? Currently the condition of between two system as follows Source Server     : SAP ECC6.0, Component SAP_APPL, release 602 level 16 Target Se

  • How to pass a SELECT-OPTION to a FUNCTION-MODULE

    Hi forum:           How can i pass a selection-option like an input parameter of a function-module?. Put one example in the answer, please.           After pass this value i want to put this into an IN select condition.    But for i only need know ho

  • SQL Developer: infuriatingly unstable

    How many times should a person need to force-quit an application each day due to bugs? The connection handling in SQL Developer is atrocious. If a session drops out due to inactivity or a network issue, it's not uncommon to get stuck in a "Do you wan

  • OEM Console - uanble to see interconnect components

    I have installed OEM and Interconnect10g(9.0.4) in separate homes. I have not installed the 9iAS server. I have followed the post installation instructions for the Oracle management infrastructure. But I still am unable to see the interconnect compon