• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 258
  • Last Modified:

textfield question

Hi experts,

I want the text in a text field to be set to "" when the user first clicks on the text field to enter new text. How do you specify that?

thanks
0
Samooramad
Asked:
Samooramad
  • 8
  • 6
  • 2
  • +1
3 Solutions
 
objectsCommented:
Add a FocusListener to the text field that clears the text when focus gained.
0
 
SamooramadAuthor Commented:
never used one. could you give me a short example?
0
 
objectsCommented:
public class MyFocusListener implements FocusListener
{
   JTextField tf;

   MyFocusListener(JTextField tf)
   {
      this.tf = tf;
      tf.addFocusListener(this);
   }

   public void focusGained(FocusEvent event)
   {
      tf.setText("");
   }

   public void focusLost(FocusEvent event)
   {
   }
}
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
ThummalaRaghuveerCommented:
Here is a part of my trimmed code

import java.awt.Container;
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.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Client extends JFrame

{
      private JTextField textZipcode,textZipcode1;
      private JLabel labelZipcode,labelZipcode1;

      
      
      private boolean firstFocus = false;

      public Client() {
            Container container = getContentPane();
            container.setLayout(new FlowLayout());
            ButtonHandler handler = new ButtonHandler();

            labelZipcode = new JLabel("ZipCode ");
            container.add(labelZipcode);
            textZipcode = new JTextField(15);
            
            textZipcode.addFocusListener(handler);
            container.add(textZipcode);
            textZipcode.setText("Code");
            
            labelZipcode1 = new JLabel("ZipCode ");
            container.add(labelZipcode1);
            textZipcode1 = new JTextField(15);
            container.add(textZipcode1);
            
            
            container.add(textZipcode);

            
            setSize(200, 600);
            setVisible(true);

            

      }
      


      // Button Click Event Handler
      class ButtonHandler implements FocusListener{
            
            

            /* (non-Javadoc)
             * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
             */
            public void focusGained(FocusEvent e) {
                  if(!firstFocus){
                        firstFocus = true;
                        ((JTextField)(e.getComponent())).setText("Focus");
                  }
                  
                  
                  
                  // TODO Auto-generated method stub
                  
            }

            /* (non-Javadoc)
             * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
             */
            public void focusLost(FocusEvent e) {
                  // TODO Auto-generated method stub
                  
            }

      }

      public static void main(String a[]) {
            Client abc = new Client();


      }

}

The first time U do it its changed next time on its not...
0
 
sudhakar_koundinyaCommented:
Although other friends gave the answer, as you are working with dynamic fields here is an idea



import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
 *
 * @author  Sudhakar
 */
public class TextFieldTest extends javax.swing.JFrame implements FocusListener {
   
    /** Creates new form TextFieldTest */
    JTextField textfield[]=new JTextField[10];
    Boolean bFirst[]=new Boolean[10];
    public TextFieldTest() {
        initComponents();
        AddTextField();
        setSize(400,400);
        setVisible(true);        
    }
    protected void AddTextField() {        
        JPanel panel1=new JPanel();        
        panel1.setLayout(new FlowLayout());
        for(int i=0;i<10;i++) {
            bFirst[i]=new Boolean(true);
            JPanel panel=new JPanel();
            panel.setLayout(new BorderLayout());            
            int cols = 20;
            textfield[i] = new JTextField("Initial Text"+i, cols);
            textfield[i].addFocusListener(this);          
            panel.add(textfield[i],BorderLayout.NORTH);
            panel.add(new JLabel(),BorderLayout.CENTER);
            panel1.add(panel);
        }        
        getContentPane().add(panel1);
       
       
    }
   
    private void initComponents() {

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        pack();
    }  
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }    
   
    public static void main(String args[]) {
        new TextFieldTest().show();
    }
   
    public void focusLost(FocusEvent e) {
       
    }
   
    public void focusGained(FocusEvent e) {
        for(int i=0;i<10;i++) {
            if(e.getSource()==textfield[i]) {
                if(bFirst[i].booleanValue()==true) {
                    bFirst[i]=new Boolean(false);
                    textfield[i].setText("");
                    break;
                }
            }
        }        
    }  
}
0
 
SamooramadAuthor Commented:
objects, I got two errors with your code... cannot reslove symbol focuslistner and interface expected
not sure what to do

ThummalaRaghuveer, Im working on yours..thanks :)

will get to yours too sudhakar
0
 
SamooramadAuthor Commented:
oh nevermind.. it was a typo.. I got the same errors with ThummalaRaghuveer's code but now both are working

my problem now is the focus is set to the text field as soon as I run the program so its always empty...how do I change that?
0
 
sudhakar_koundinyaCommented:
// Create frame and three buttons
    JFrame frame = new JFrame();
   JTextField field=new JTextField("Hello");
   
    // Set component with initial focus; must be done before the frame is made visible
    InitialFocusSetter.setInitialFocus(frame, field);
   
    class InitialFocusSetter {
        public static void setInitialFocus(Window w, Component c) {
            w.addWindowListener(new FocusSetter(c));
        }
   
        public static class FocusSetter extends WindowAdapter {
            Component initComp;
            FocusSetter(Component c) {
                initComp = c;
            }
            public void windowOpened(WindowEvent e) {
                initComp.requestFocus();
   
                // Since this listener is no longer needed, remove it
                e.getWindow().removeWindowListener(this);
            }
        }
    }
0
 
sudhakar_koundinyaCommented:
This never sets initial focus to Textfield



 JFrame frame = new JFrame();
   JTextField field=new JTextField("Hello");
   JButton field1=new JButton("Hello");
   
    // Set component with initial focus; must be done before the frame is made visible
    InitialFocusSetter.setInitialFocus(frame, field1);
   
    class InitialFocusSetter {
        public static void setInitialFocus(Window w, Component c) {
            w.addWindowListener(new FocusSetter(c));
        }
   
        public static class FocusSetter extends WindowAdapter {
            Component initComp;
            FocusSetter(Component c) {
                initComp = c;
            }
            public void windowOpened(WindowEvent e) {
                initComp.requestFocus();
   
                // Since this listener is no longer needed, remove it
                e.getWindow().removeWindowListener(this);
            }
        }
    }
0
 
sudhakar_koundinyaCommented:
Here is one more idea to work with dynamic fields

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
 *
 * @author  Sudhakar
 */


class MyActionListener implements ActionListener {
   
    public void actionPerformed(ActionEvent evt) {
        JTextField textfield = (JTextField)evt.getSource();
       
    }
}
public class TextFieldTest extends javax.swing.JFrame implements FocusListener {
   
    /** Creates new form TextFieldTest */
    JTextField textfield[]=new JTextField[10];
    String strValues[]=new String[10];
   
    public TextFieldTest() {
        initComponents();
        AddTextField();
        setSize(400,400);
        setVisible(true);
       
    }
    protected void AddTextField() {
       
        JPanel panel1=new JPanel();
       
        panel1.setLayout(new FlowLayout());
        for(int i=0;i<10;i++) {
            strValues[i]="";
           
            JPanel panel=new JPanel();
            panel.setLayout(new BorderLayout());
           
            int cols = 20;
            textfield[i] = new JTextField("Initial Text"+i, cols);
            textfield[i].addFocusListener(this);
            textfield[i].addActionListener(new MyActionListener());
            panel.add(textfield[i],BorderLayout.NORTH);
            panel.add(new JLabel(),BorderLayout.CENTER);
            panel1.add(panel);
        }
        getContentPane().setFocusable(true);
        getContentPane().add(panel1);
       
       
    }
   
    private void initComponents() {

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        pack();
    }
   
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
   
    public static void main(String args[]) {
        new TextFieldTest().show();
    }
    public void focusLost(FocusEvent e) {    }
    public void focusGained(FocusEvent e) {
        for(int i=0;i<10;i++) {            
            if(e.getSource()==textfield[i] ) {                
                if( textfield[i].getText().trim().length()>0 && textfield[i].getText().trim().equals("Initial Text"+i)==false) {
                    int answer = -1;
                    String text=textfield[i].getText();
                    textfield[i].setText("");
                    if(strValues[i]!=null && text.length()>0 && strValues[i].equals(text)==false) {
                        answer=JOptionPane.showConfirmDialog(this, "Do you want to clear the text field");
                        strValues[i]="";
                    }
                    if (answer == JOptionPane.YES_OPTION) {
                        textfield[i].setText("");                        
                        textfield[i].requestFocus();
                        break;
                    }
                    else {                        
                        this.getContentPane().setFocusable(true);
                        textfield[i].setText(text);
                        textfield[i].requestFocus();
                        strValues[i]=text;                        
                    }
                }
                else {
                    textfield[i].setText("");
                    break;
                }
            }
           
        }
    }
   
    // Variables declaration - do not modify
    // End of variables declaration
   
}
0
 
SamooramadAuthor Commented:
ok..thank u
Im working on it
0
 
ThummalaRaghuveerCommented:
Hey got an idea tested it out and it works..... You want it to change its text when ever a user first clicks on the text box......

Remove Focus listener in my last code and add MouseListner instead.....

In the mouse clicked event change the content of the text field

This Will work....


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Client extends JFrame

{
      private JTextField textZipcode,textZipcode1;
      private JLabel labelZipcode,labelZipcode1;

      
      
      private boolean firstFocus = false;

      public Client() {
            Container container = getContentPane();
            container.setLayout(new FlowLayout());
            ButtonHandler handler = new ButtonHandler();

            labelZipcode = new JLabel("ZipCode ");
            container.add(labelZipcode);
            textZipcode = new JTextField(15);
            
            
            textZipcode.addMouseListener(handler);
            
            container.add(textZipcode);
            textZipcode.setText("Code");
            //textZipcode.setEditable(false);
            textZipcode1 = new JTextField(15);
            container.add(textZipcode1);
            
            
            
            

            
            setSize(200, 600);
            setVisible(true);

            

      }
      


      // Button Click Event Handler
      class ButtonHandler implements  MouseListener{
            
            

            
            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
             */
            public void mouseClicked(MouseEvent e) {
                  if(!firstFocus) {
                        ((JTextField)(e.getComponent())).setText("Focus");
                        firstFocus = true;
                  }
                  
                  // TODO Auto-generated method stub
                  
            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
             */
            public void mousePressed(MouseEvent e) {
                  // TODO Auto-generated method stub
                  
            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
             */
            public void mouseReleased(MouseEvent e) {
                  // TODO Auto-generated method stub
                  
            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
             */
            public void mouseEntered(MouseEvent e) {
                  // TODO Auto-generated method stub
                  
            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
             */
            public void mouseExited(MouseEvent e) {
                  // TODO Auto-generated method stub
                  
            }

      }

      public static void main(String a[]) {
            Client abc = new Client();


      }

}
0
 
SamooramadAuthor Commented:
sudhakar, could you please adjust this code you posted to work with internal frames instead of frames?

This never sets initial focus to Textfield



 JFrame frame = new JFrame();
   JTextField field=new JTextField("Hello");
   JButton field1=new JButton("Hello");
   
    // Set component with initial focus; must be done before the frame is made visible
    InitialFocusSetter.setInitialFocus(frame, field1);
   
    class InitialFocusSetter {
        public static void setInitialFocus(Window w, Component c) {
            w.addWindowListener(new FocusSetter(c));
        }
   
        public static class FocusSetter extends WindowAdapter {
            Component initComp;
            FocusSetter(Component c) {
                initComp = c;
            }
            public void windowOpened(WindowEvent e) {
                initComp.requestFocus();
   
                // Since this listener is no longer needed, remove it
                e.getWindow().removeWindowListener(this);
            }
        }
    }
0
 
SamooramadAuthor Commented:
because thats where the textfield is
0
 
sudhakar_koundinyaCommented:

This example associates a label with a text field using setLabelFor(). A mnemonic is set on the label. When the mnemonic keystroke is pressed, the text field will gain the focus.

In the following example, when ALT-L is pressed, the text field gains the focus.

    // Create text field
    JTextField textfield = new JTextField(25);
   
    // Create label and associate with text field
    JLabel label = new JLabel("Text Label");
    label.setDisplayedMnemonic(KeyEvent.VK_L);
    label.setLabelFor(textfield);
0
 
SamooramadAuthor Commented:
you lost me
0
 
SamooramadAuthor Commented:
it worked..thanks
0
 
sudhakar_koundinyaCommented:
Thanks for the points

>> you lost me


I didn't get you
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 6
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now