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.

Similar Messages

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

  • JFrame which does not allow resizing (maximizing, minimizng)

    I want to develop a login frame which does not allow resizing (maximizing, minimizing as this does not make sense) and with 2 fields, JTextField and JPasswordField.
    The frame is developed but has the usual resizing handles.
    How to do?
    Many tks for any information.
    John Pashley

    Don't use a JFrame. Also, don't expect code like this again; I did it for fun.
    It requires your modification.
    * Title:        Login Screen<p>
    * Description:  Login Screen<p>
    * Class:        Login ScreenLoginScreen<p>
    * Copyright:    who cares<p>
    * Company:      who cares<p>
    * @author who cares
    * @version who cares
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.util.Vector;
    import java.io.File;
    import javax.swing.*;
    public class LoginScreen extends JDialog implements ActionListener, FocusListener
       private JTextField      name;
       private JPasswordField  password;
       private JButton         loginButton;
       private JButton         cancelButton;
       private JDialog         thisDialog = this;
       private ImageIcon       splashImage;
       private String          appTitle;
       private int             logCounter;
       public LoginScreen()
          super();
          this.toFront();
          setTitle("Login");
          addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent e)
                    System.exit(0);
          getContentPane().setLayout(new BorderLayout());
          splashImage = new ImageIcon( getClass().getResource("images" + File.separator + "image.jpg")) );
          getContentPane().add(new JLabel(splashImage), "North");
          getContentPane().add(makeLoginPanel(), "Center");
          getContentPane().add(makeButtonPanel(), "South");
          pack();
          setResizable(false);
          setLocationRelativeTo(null);
          setVisible(true);
        * make login panel
       private JPanel makeLoginPanel()
          JPanel loginPanel = new JPanel();
          JLabel label;
          loginPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
          GridBagLayout gbl = new GridBagLayout();
          GridBagConstraints gbc = new GridBagConstraints();
          loginPanel.setLayout(gbl);
          gbc.weightx = 1.0;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.insets = new Insets(0, 5, 10, 5);
          gbc.gridx = 0;
          gbc.gridy = 0;
          label = new JLabel("Login Name:", SwingConstants.LEFT);
          gbl.setConstraints(label, gbc);
          loginPanel.add(label);
          gbc.gridx = 1;
          name = new JTextField("insider", 10);
          name.addFocusListener(this);
          gbl.setConstraints(name, gbc);
          loginPanel.add(name);
          gbc.gridx = 0;
          gbc.gridy = 1;
          label = new JLabel("Password:", SwingConstants.LEFT);
          gbl.setConstraints(label, gbc);
          loginPanel.add(label);
          gbc.gridx = 1;
          password = new JPasswordField("insider",10);
          password.addFocusListener(this);
          gbl.setConstraints(password, gbc);
          loginPanel.add(password);
          return loginPanel;
        * make button panel
       private JPanel makeButtonPanel()
          JPanel buttonPanel = new JPanel();
          buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
          //make LogIn button
          loginButton = new JButton("Login");
          loginButton.setActionCommand("Login");
          buttonPanel.add(loginButton);
          rootPane.setDefaultButton(loginButton);
          loginButton.addActionListener(this);
          this.getRootPane().setDefaultButton(loginButton);
          //make Cancel button
          cancelButton = new JButton("Cancel");
          cancelButton.setActionCommand("Cancel");
          buttonPanel.add(cancelButton);
          cancelButton.addActionListener(this);
          this.addKeyListener(new KeyAdapter()
             public void keyReleased(KeyEvent e)
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
                   cancelButton.doClick();
             return buttonPanel;
        * Action handler for login and cancel buttons
       public void actionPerformed(ActionEvent e)
          JButton btn = (JButton) e.getSource();
          if (btn.getActionCommand().equals("Login"))
             // Because login() process happens before swing process (above),
             // force it to happen "later"
             SwingUtilities.invokeLater(new Runnable()
                public void run()
                   login(); //create this method, okay?!
          else if (btn.getActionCommand().equals("Cancel"))
             System.exit(0);
        * Focus gained handler for username and password buttons
       public void focusGained(FocusEvent e)
          JTextField tf = (JTextField) e.getSource();
          tf.selectAll();
        * Focus lost handler for username and password buttons
       public void focusLost(FocusEvent e) {}
       private void showErrorMessage(String message, String header)
          JOptionPane.showMessageDialog(getContentPane(),
                                        message, header,
                                        JOptionPane.ERROR_MESSAGE);
        * This method controls the cursor for login window. If isWait is set to
        * true, dialog's cursor is set to Cursor.WAIT_CURSOR. If isWait is set
        * to false, the cursor is set ta Deafult.
        * While the window is in WAIT mode, this method will also disable Login
        * and Cancel buttons to ensure the user does not accidently request
        * a cancel while loging in or launching a second login.
       private void setWaitCursor(boolean isWait)
          /* In order to disable login and cancel buttons while logging in to the
             application, this method will temporarely change action commands and
             reset them when login process failed to give user another chance.
             Note: Disabling the buttons by calling setEnabled(false) did not work
             since login() method is called from an action event handler and the
             process will not be released to AWT until login method is complete.
          if (isWait)
             this.getGlassPane().setCursor(new Cursor(Cursor.WAIT_CURSOR));
             this.getGlassPane().setVisible(true);
             loginButton.setActionCommand("none");
             cancelButton.setActionCommand("none");
          else
             this.getGlassPane().setCursor(Cursor.getDefaultCursor());
             this.getGlassPane().setVisible(false);
             loginButton.setActionCommand("Login");
             cancelButton.setActionCommand("Cancel");
    } //end loginscreen

  • Weird behavior after revalidate()

    hi everyone...
    what im basically trying to do is when a text field looses focus another text field will be added to a panel....and i also have a button that will remove the buttons one after the other.....i am using the revalidate method for proper displaying of the scroll pane.
    what is happening is when i press the remove button, text fields are added instead of getting removed...when i remove the revalidate method things runs smoothly except for the scroll pane....
    what i think is happening is that when i press the button to remove a text field this removed field is loosing focus thus adding a new text field....this is only what i think is happening, it might not be true but either way i haven't been able to fix that....
    this is the relevent part of the code :
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.util.ArrayList;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    * @author fouad
    public class test extends JFrame implements ActionListener{
        private JButton rem;
        private JPanel mainPanel,nPanel,cPanel,sPanel;
        private ArrayList<TestPanel> panels = new ArrayList<TestPanel>();
        private JScrollPane sp;
        private int count = 0;
        public test(){
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(1000, 600);
            mainPanel = new JPanel();
            nPanel= new JPanel();
            cPanel= new JPanel();
            sPanel= new JPanel();
            mainPanel.setLayout(new BorderLayout(5, 5));
            nPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            sPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            cPanel.setLayout(new BoxLayout(cPanel, BoxLayout.Y_AXIS));
            panels.add(new TestPanel(this));
            cPanel.add(panels.get(count));
            count++;
            sp = new JScrollPane(cPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            rem = new JButton("remove");
            rem.setActionCommand("remove");
            rem.addActionListener(this);
            nPanel.add(rem);
            sPanel.setBackground(Color.yellow);
            sPanel.setPreferredSize(new Dimension(1000, 30));
            mainPanel.add(nPanel,BorderLayout.NORTH);
            mainPanel.add(sp,BorderLayout.CENTER);
            mainPanel.add(sPanel,BorderLayout.SOUTH);
            getContentPane().add(mainPanel);
        public void addItem(){
            panels.add(new TestPanel(this));
            cPanel.add(panels.get(count));
            panels.get(count).getField().requestFocus();
            count++;
            cPanel.revalidate();
        public static void main(String[] args){
            test t = new test();
            t.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equalsIgnoreCase("remove")){
                if(count > 1){
                    count--;
                    cPanel.remove(panels.get(count -1));
                    panels.remove(count-1);
                    cPanel.revalidate();
    class TestPanel extends JPanel implements FocusListener{
        private JTextField text = new JTextField(10);
        test t;
        public TestPanel(test t){
            this.t = t;
            setSize(900, 50);
            add(text);
            text.addFocusListener(this);
        public JTextField getField(){
            return text;
        public void focusGained(FocusEvent e) {
        public void focusLost(FocusEvent e) {
            t.addItem();
    }please help
    thanks in advance

    thanks a lot....that was very helpful but the thing is,in this particular example, when you set the button to setFocusable(false) the button does not fire events anymore because when the text field looses focus the button does not get focus so it wont fires....but in my example i have more text fields so when i set the button to non focusable it kept on firing events because when the first text field lost focus the second one gained focus so the solution you provided solved my problem in my case....
    thanks a lot

  • Tabbing through subform

    I have a table that has repeatable rows, each row has an add and delete button at the end of each row,  to remove that specific row if necessary and the initial count is 4. The issue I am having is when I enter data into the text fields in the first row and tab pass the add and delete buttons the cursor goes to the next subform in my document instead of the next row of the current subform.
    Any assistance would be greatly appreciated.
    Thanks
    Parre

    Try using a FocusListener:
            final JTextField text = new JTextField();
            text.addFocusListener(new FocusAdapter() {
                public void focusGained(FocusEvent e) {
                    text.selectAll();
            });

  • Tabbing through TextFields

    Is there a way so that tabbing through TextFields will leave the current contents highlighted by default?
    For example:
    X [ 12 ]
    Y [ 34 ]
    Where X and Y are labels and []'s are textfields. Say I tab to the field in front of X, I would like to have 12 completely highlighted so that I just type something to overwrite the contents.
    Right now I have to type Ctrl-A to make the contents highlighted, then I can type something to overwrite the field, I just want to make so that the content is highlighted by default when I tab to that particular field.
    Thanks,
    -frankie

    Try using a FocusListener:
            final JTextField text = new JTextField();
            text.addFocusListener(new FocusAdapter() {
                public void focusGained(FocusEvent e) {
                    text.selectAll();
            });

  • How can a JTextField in a Dialog gain focus while mainframe is clicked

    Hi
    I have been trying to develop a 3d application. I have some shapes on a Canvas3D laid on a JFrame.
    I open a new shape dialog after pressing the appropriate button.
    Once the dialog is open I need to select two shapes on canvas for reference hence there are two text fields to show the name of each.
    when I select the first shape the corresponding textfield is being updated.
    Now the Problem
    I place the cursor in the second tex field and click on second shape on canvas.
    I lose focus from text field to canvas.
    Now I am unsure if the second textfield has the focus or is the focus with the first text field. Based on this focus info I can update the text fields.
    I understand that only one field can have focus at a time.
    My doubt is How can the JTextField retain its focus while the components on main window are being clicked.
    The following code is enclosed in a listener that responds to picked shapes.
    if(gooi.getSketchDialog() != null && gooi.getSketchDialog().isShowing()){
                gooi.getPick1().getCanvas().setFocusable(false);
                if(gooi.getSketchDialog().getSelectedPlaneTextField().isFocusOwner()){
                        if( pickResult != null)
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText(pickResult.getNode(PickResult.SHAPE3D).getUserData().toString());
                        else if (pickResult == null){
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText("");
            }Any help is appreciated.
    Thanks in Advance
    Venkat
    Edited by: pushinglimits on Oct 31, 2008 6:52 AM

    Michael
    The text field still loses focus when its containing window is no longer focused.import java.awt.FlowLayout;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class NoFocusTransfer implements FocusListener {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new NoFocusTransfer().makeUI();
       public void makeUI() {
          JTextField one = new JTextField(20);
          one.addFocusListener(this);
          JTextField two = new JTextField(20);
          two.addFocusListener(this);
          JFrame frameOne = new JFrame("");
          frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frameOne.setSize(400, 400);
          frameOne.setLocationRelativeTo(null);
          frameOne.setLayout(new FlowLayout());
          frameOne.add(one);
          frameOne.add(two);
          JButton button = new JButton("Click");
          button.setFocusable(false);
          JFrame frameTwo = new JFrame();
          frameTwo.add(button);
          frameTwo.pack();
          frameTwo.setFocusable(false);
          frameOne.setVisible(true);
          frameTwo.setVisible(true);
       public void focusGained(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getOppositeComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getComponent().getClass().getName());
          } catch (NullPointerException npe) {
       public void focusLost(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getOppositeComponent().getClass().getName());
          } catch (NullPointerException npe) {
    }db

  • How to highlight text in JTextField?

    Hi all, I know this is a very simple question but I just couldn't find its solution and I'm rushing for my project.
    My question is: how to highlight all the text in JTextField when it gets focus?
    Thanks a lot in advance!
    Janet

    You have to add a FocusListener in the JTextField and override the focusGained() method to select all the text with JTextField.selectAll().
    class MyFrame {
      JTextField text = new JTextField();
      // when creating the frame
      text.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
          doSelectAllText(); 
      void doSelectAllText() {
        text.selectAll();
    }Hope this help.

  • Problem With Fade Effect For JTextField

    Hello Friends !
    I am putting a 'bounty' of 10 Duke dollars
    for the clever clogs who can help me out !
    I want to create a 'fade in' effect when a
    textfield has the focus and a 'fade out'
    effect when it looses focus.
    The code for what I have done so far is
    listed below, but it leaves nasty 'artifacts'
    behind when painting.
    regards, Asad.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RunProgramAgain{
    public static void main(String[] args){
    JFrame frame = new MyFrame();
    class MyField extends JTextField{
    public MyField(){
    setPreferredSize(new Dimension(100, 30));
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    if(hasFocus())
    fadeIn();
    else
    fadeOut();
    private synchronized void fadeIn(){
    for(alpha = MIN; alpha <= MAX; ++alpha)
    setBackground(new Color(RED, GREEN, BLUE, alpha));
    private synchronized void fadeOut(){
    for(alpha = MAX; alpha >= MIN; --alpha)
    setBackground(new Color(RED, GREEN, BLUE, alpha));
    private int alpha = MIN;
    private static final int MIN = 0;
    private static final int MAX = 10;
    private static final int RED = 0;
    private static final int GREEN = 255;
    private static final int BLUE = 0;
    class MyButton extends JButton{
    public MyButton(){
    super("Start");
    class MyFrame extends JFrame{
    public MyFrame(){
    setSize(new Dimension(300,250));
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(new MyButton());
    getContentPane().add(new MyField());
    show();
    }

    Played some more and came up with a class that will allow you to fade the background color of any JComponent:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Hashtable;
    import java.util.Vector;
    import javax.swing.*;
    public class Fader
         private static final int MIN = 0;
         private static final int MAX = 10;
         private Color fadeFrom;
         private Color fadeTo;
         private Hashtable backgroundColors = new Hashtable();
         **  The background of any Component added to this Fader
         **  will be set/reset to the fadeFrom color.
         public Fader(Color fadeTo, Color fadeFrom)
              this(fadeTo);
              this.fadeFrom = fadeFrom;
         **  The original background of any Component added to this Fader
         **  will be preserved.
         public Fader(Color fadeTo)
              this.fadeTo = fadeTo;
         **  Fading will be applied to this component on gained/lost focus
         public Fader add(JComponent component)
              //  Set background of all components to the fadeFrom color
              if (fadeFrom != null)
                   component.setBackground( fadeFrom );
              //  Get colors to be used for fading
              Vector colors = getColors( component.getBackground() );
              //     FaderTimer will apply colors to the component
              new FaderTimer( colors, component );
              return this;
         **  Get the colors used to fade this background
         private Vector getColors(Color background)
              //  Check if the color Vector already exists
              Object o = backgroundColors.get( background );
              if (o != null)
                   return (Vector)o;
              //  Doesn't exist, create fader colors for this background
              int rIncrement = ( background.getRed() - fadeTo.getRed() ) / MAX;
              int gIncrement = ( background.getGreen() - fadeTo.getGreen() ) / MAX;
              int bIncrement = ( background.getBlue() - fadeTo.getBlue() ) / MAX;
              Vector colors = new Vector( MAX + 1 );
              colors.addElement( background );
              for (int i = 1; i <= MAX; i++)
                   int rValue = background.getRed() - (i * rIncrement);
                   int gValue = background.getGreen() - (i * gIncrement);
                   int bValue = background.getBlue() - (i * bIncrement);
                   colors.addElement( new Color(rValue, gValue, bValue) );
              backgroundColors.put(background, colors);
              return colors;
         class FaderTimer implements FocusListener, ActionListener
              private Vector colors;
              private JComponent component;
              private Timer timer;
              private int alpha;
              private int increment;
              FaderTimer(Vector colors, JComponent component)
                   this.colors = colors;
                   this.component = component;
                   component.addFocusListener( this );
                   timer = new Timer(5, this);
              public void focusGained(FocusEvent e)
                   alpha = MIN;
                   increment = 1;
                   timer.start();
              public void focusLost(FocusEvent e)
                   alpha = MAX;
                   increment = -1;
                   timer.start();
              public void actionPerformed(ActionEvent e)
                   alpha += increment;
                   component.setBackground( (Color)colors.elementAt(alpha) );
                   if (alpha == MAX || alpha == MIN)
                        timer.stop();
         public static void main(String[] args)
              // Create test components
              JComponent textField1 = new JTextField(10);
              JComponent textField3 = new JTextField(10);
              JComponent textField4 = new JTextField(10);
              JComponent button = new JButton("Start");
              JComponent checkBox = new JCheckBox("Check Box");
              JFrame frame = new JFrame("Fading Background");
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add(textField1, BorderLayout.NORTH );
              frame.getContentPane().add(button, BorderLayout.SOUTH );
              frame.getContentPane().add(textField3, BorderLayout.EAST );
              frame.getContentPane().add(textField4, BorderLayout.WEST );
              frame.getContentPane().add(checkBox);
              //  Fader preserving component background
              Fader fader = new Fader( new Color(155, 255, 155) );
              fader.add( textField1 );
              fader.add( button );
              fader.add( checkBox );
              //  Fader resetting component background
              fader = new Fader( new Color(155, 255, 155), Color.yellow );
              fader.add( textField3 );
              fader.add( textField4 );
              frame.pack();
              frame.setVisible( 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

  • 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

  • Help - Focuslost is trigered too many time during jtextfield validation.

    Hi all,
    I am designing a form containing multiple fields with field validations.
    The program supposes bring the focus back to that particular field after the error message is displayed. However; the
    error/warning message is displayed infinitely between the two focusLost events of the two Jtextfields when the focus is switched between the two jtextfields. I tried to google it, but there was no success.
    Can anyone tell me why?
    Thanks a lot.
    core code
        private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {                                     
            // TODO add your handling code here:evt.getSource();
            JTextField roomTag=(JTextField) evt.getSource();
             String text = roomTag.getText();
             if (text.length() >= 3) {
                try {
                        Integer.parseInt(text);
                } catch(NumberFormatException nfe) {
                 //    Toolkit.getDefaultToolkit().beep();
    //SwingUtilities.invokeLater(new FocusGrabber(this.jTextField1));
                   JOptionPane.showMessageDialog(null, "It must be a numeric value");
                   //roomTag.requestFocus();
                   jTextField1.requestFocus();
                   //return;
             } else {
                   JOptionPane.showMessageDialog(null, "It must be 3 chars at least");
                   //roomTag.requestFocus();
                    jTextField1.requestFocus();
                    //return;
        private void txtPhoneFocusLost(java.awt.event.FocusEvent evt) {                                  
            // TODO add your handling code here:
            JTextField roomTag=(JTextField) evt.getSource();
             String text = roomTag.getText();
             if (text.length() <= 12) {
                try {
                    Long a=Long.parseLong(text);
                } catch(NumberFormatException nfe) {
                   JOptionPane.showMessageDialog(null, "The phone number must be a numeric value");
                   txtPhone.requestFocus();
                   //roomTag.requestFocus();
                   //jTextField1.requestFocus();
                   //return;
             } else {
                   JOptionPane.showMessageDialog(null, "The phone number must be 12 chars at most");
                    txtPhone.requestFocus();
                   //roomTag.requestFocus();
                    //jTextField1.requestFocus();
                    //return;
                                         Edited by: ehope on Nov 1, 2009 5:14 PM
    Edited by: ehope on Nov 1, 2009 5:18 PM
    Edited by: ehope on Nov 1, 2009 5:21 PM

    A search of the forum on two terms -- focusLost multiple -- came up with some interesting hits: [forum search|http://search.sun.com/main/index.jsp?all=focuslost+multiple&exact=&oneof=&without=&nh=10&rf=0&since=&dedupe=true&doctype=&reslang=en&type=advanced&optstat=true&col=main-all]
    including a bug report and a work-around by camickr.
    Another possible work around is to remove the focuslistener, then re-add it at the end of the focuslistener but via a Swing Timer to delay its re-addition.

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

  • Validation in JTextField

    Hi ,
    I have a JTextField, a JComboBox , a JButton , a JList and a JTable in my Frame. I enter a value in JTextField which has to be validated with a constant. Where do u write the validation ?
    i have written the validation in focus lost of JTextField.
    This causes problem when i click on the jtable or jcombobox. When i click on the combobox after entering a wrong value in the textfield, cursor remains in the jtextfield but i am able selected a value from the jcombobox as well.
    Following is the sample code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2001
    * Company:
    * @author
    * @version 1.0
    public class EnabledTest extends JFrame implements FocusListener
    JTextField jTextField1 = new JTextField();
    JTextField jTextField2 = new JTextField();
    JComboBox jComboBox1 = new JComboBox();
    JList jList1 = new JList();
    JButton jButton1 = new JButton();
    JTable jTable1 = new JTable();
    public EnabledTest()
    try
    jbInit();
    addListeners();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args)
    EnabledTest enabledTest1 = new EnabledTest();
    enabledTest1.setVisible(true);
    enabledTest1.setBounds(0,0,400,400);
    public void addListeners()
    jTextField1.addFocusListener(this);
    jTextField2.addFocusListener(this);
    jComboBox1.addFocusListener(this);
    jList1.addFocusListener(this);
    jButton1.addFocusListener(this);
    public void focusGained(FocusEvent e)
    public void focusLost(FocusEvent e)
    if(e.getSource() == jTextField1)
    jTextField1_validationPerformed(e);
    private void jbInit() throws Exception
    jTextField1.setText("jTextField1");
    jTextField1.setBounds(new Rectangle(49, 39, 144, 38));
    this.getContentPane().setLayout(null);
    jTextField2.setBounds(new Rectangle(227, 40, 144, 38));
    jTextField2.setText("jTextField1");
    jComboBox1.setBounds(new Rectangle(52, 115, 141, 34));
    jComboBox1.addItem("one");
    jComboBox1.addItem("two");
    jList1.setBounds(new Rectangle(239, 110, 135, 120));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(56, 187, 127, 29));
    jTable1.setBounds(new Rectangle(55, 251, 330, 117));
    jTable1.setModel(new DefaultTableModel(3,3));
    this.getContentPane().add(jTextField1, null);
    this.getContentPane().add(jTextField2, null);
    this.getContentPane().add(jComboBox1, null);
    this.getContentPane().add(jList1, null);
    this.getContentPane().add(jButton1, null);
    this.getContentPane().add(jTable1, null);
    private void jTextField1_validationPerformed(FocusEvent e)
    jTextField1.removeFocusListener(this);
    int intValue = new Integer(jTextField1.getText()).intValue();
    if (intValue > 100)
    JOptionPane.showMessageDialog(this, "Should be < 100");
    jTextField1.requestFocus();
    jTextField1.addFocusListener(this);
    }

    It is fairly easy to validate for a range. I added this kind of validation (attached (*)). At any time you may want to set the validity range of your NumericJTextField. I did it as follows:
    this.numericTextField.setValidityRange(-999, +999);
    I tested and it does work nicely - couldn't fool it.
    (*) Is there any holy way to post files without having to cut and paste them as a whole in this doubly holy tab-eater JTextArea :-(
    package textfieldvalidator;
    * Title: NumericJTextField
    * Description: An example JTextFiled that accepts only digits
    * Copyright: nobody - use it at will
    * Company:
    * @author Antonio Bigazzi - [email protected]
    * @version 1.0 First and last
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class ValidatorExample extends JPanel {
    NumericJTextField numericTextField; // accepts only digit
    JTable table;
    public ValidatorExample() {
    this.setLayout(new BorderLayout());
    this.numericTextField = new NumericJTextField("1234X5");
    this.numericTextField.setBackground(Color.black);
    this.numericTextField.setForeground(Color.yellow);
    this.numericTextField.setCaretColor(Color.white);
    this.numericTextField.setFont(new Font("Monospaced", Font.BOLD, 16));
    this.numericTextField.setValidityRange(-999, +999);
    this.table = new JTable(
    new String[][] { {"a1a", "b2b", "c3c"}, {"456", "777", "234"}},
    new String[] {"Col 1", "Col 2", "Col 3"}
    this.add(this.numericTextField, BorderLayout.NORTH);
    this.add(this.table, BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(new ValidatorExample());
    f.setLocation(300, 75);
    f.pack();
    f.setVisible(true);
    // ===================== the meat ============================
    // the specialized JTextField that uses a restrictive doc model
    class NumericJTextField extends JTextField {
    NumericJTextField() {this("", 0);}
    NumericJTextField(String text) {this(text, 0);}
    NumericJTextField(int columns) {this("", columns);}
    NumericJTextField(String text, int columns) {
    super(new NumericDocument(), text, columns);
    public void setValidityRange(int min, int max) {
    ((NumericDocument)this.getDocument()).setValidityRange(min, max);
    // check what may have been there already (via constructor)
    this.setText(this.getText());
    // the restricted doc model - non-numbers make it beep
    class NumericDocument extends PlainDocument {
    protected int minValue = Integer.MIN_VALUE;
    protected int maxValue = Integer.MAX_VALUE;
    public void setValidityRange(int minValue, int maxValue) {
    this.minValue = minValue;
    this.maxValue = maxValue;
    public void insertString(int offset, String text, AttributeSet a)
    throws BadLocationException {
    // digits only please (or bring your own restriction/validation)
    StringBuffer buf = new StringBuffer(text.length());
    for (int i = 0; i < text.length(); i++) {
         if (Character.isDigit(text.charAt(i))) {
         buf.append(text.charAt(i));
         } else {
         java.awt.Toolkit.getDefaultToolkit().beep();
    super.insertString(offset, buf.toString(), a);
    // get the whole "document" back for range validation
    while(true) {
    String num = this.getText(0, this.getLength());
         if (num.length() == 0) break;
         int value = Integer.parseInt(num);
         if (value >= this.minValue && value <= this.maxValue) {
         break;
         } else {
         // beeep and chop (or whatever reaction for out of range)
         java.awt.Toolkit.getDefaultToolkit().beep();
         this.remove(this.getLength() - 1, 1);
    // Note: in insertString, length is 1 when typing, but it can be anything
    // when the text comes from the constructor, when it is pasted, etc.
    }

  • JTextField on change behaviour

    Hello All
    I needed help with the JTextfield, I need to be able to add a change event listener to it, based on the value entered in JTextfield, I need to repaint other components on the panel. Im not very keen on using the FocusListener like in my code snippet below.Can anyone suggest me with some "On Value change" kind of listener that I can use.
    JTextField jt = new JTextField();
    jt.setPreferredSize(new Dimension(75,25));
    jt.addFocusListener(new FocusListener(){
    public void focusLost(FocusEvent ez)
    System.out.println("focus lost");
    public void focusGained(FocusEvent ex)
    System.out.println("focus gained");
    Regards
    N.

    Hello Anton,
    Your right about the remove/insert listeners.. for every alphabet added or removed the event gets triggered
    I have the focus listeners implementation at the moment.. but am not too keen on it, becoz every time it gains focus it will trigger the event, as I am really doing some jdbc calls to process and populate the other components.. I wanted to use a change listener.. so that it triggers event only on value changes and not keep making these calls when it gains /loses focus
    Regards
    N.

Maybe you are looking for

  • IPhone iCal bug- appointments suddenly 1 hour off

    After 2 days of searching and 1 hour on tech support, I've concluded Apple has a bug with iCal on iPhone that still needs to be addressed. I realized 2 days ago after missing a scheduled conference call that my iCal appointments on my iPhone (3GS) we

  • Cannot post a reply

    For whatever reason, although I am logged-in to Adobe Forums, I cannot post a reply to a message that was posted in reply to my original message (which began the discussion).  A blank white space, barely discernible, is displayed below the two lines

  • Can i still send my iphone in for a repair after 10 days?

    Hi Guys Sorry if this is in the wrong section. Does anyone know if i can still send my iphone in for a repair more than 10 days after receiving my packaging from apple as i noticed on the confirmation email it says if you dont send the phone back wit

  • Import movie from iPhone gives "An unknown error has occurred while reading the video file. Connecting to Dynamic Link server failed. (1)

    Tried previous suggestions about purging the Camera Raw Cache and I raised it to 20.0 GB. Still lightroom fails to read most of the videos that I create on my iPhone 6 plus. Aperture, iMovie, and Image Capture have no problem with these files. Respec

  • Movies will not sync with new 1.1.2 version

    Has anyone had this trouble? I installed the latest update 2 days ago and now none of the movies I have converted will sync. It will start to sync the movie, then i get a Windows error message asking if I want to report the error. When I click yes or