Solved

textfield question

Posted on 2004-10-07
18
213 Views
Last Modified: 2010-03-31
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
Comment
Question by:Samooramad
  • 8
  • 6
  • 2
  • +1
18 Comments
 
LVL 92

Expert Comment

by:objects
ID: 12254701
Add a FocusListener to the text field that clears the text when focus gained.
0
 

Author Comment

by:Samooramad
ID: 12254726
never used one. could you give me a short example?
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
ID: 12254758
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
 
LVL 2

Assisted Solution

by:ThummalaRaghuveer
ThummalaRaghuveer earned 50 total points
ID: 12254877
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12256345
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
 

Author Comment

by:Samooramad
ID: 12257074
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
 

Author Comment

by:Samooramad
ID: 12257134
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12257179
// 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
 
LVL 14

Assisted Solution

by:sudhakar_koundinya
sudhakar_koundinya earned 50 total points
ID: 12257240
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12257306
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
 

Author Comment

by:Samooramad
ID: 12260338
ok..thank u
Im working on it
0
 
LVL 2

Expert Comment

by:ThummalaRaghuveer
ID: 12260546
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
 

Author Comment

by:Samooramad
ID: 12260578
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
 

Author Comment

by:Samooramad
ID: 12260591
because thats where the textfield is
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12261537

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
 

Author Comment

by:Samooramad
ID: 12262883
you lost me
0
 

Author Comment

by:Samooramad
ID: 12264050
it worked..thanks
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12265108
Thanks for the points

>> you lost me


I didn't get you
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now