Solved

textfield question

Posted on 2004-10-07
18
206 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
powerN  challenge 3 49
strCount chalenge 3 50
json example 39 115
Problem to start Neon 20 54
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

760 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

18 Experts available now in Live!

Get 1:1 Help Now