Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

textfield question

Posted on 2004-10-07
18
Medium Priority
?
255 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 200 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 2

Assisted Solution

by:ThummalaRaghuveer
ThummalaRaghuveer earned 200 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 200 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
 
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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

916 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