How to clear JTextField when mouse clicks the JTextField
Asked Answered
E

7

12

I need to make this program clear the text from the text field when the mouse clicks in that text field. I have tried a few things, but none of them have yet to work for me.

Here is the code in its entirety:

public class TimerClassPanel extends JFrame implements MouseListener{

    public TimerClassPanel(){
        setTitle("Timer Class");
        setSize(WIDTH, HEIGHT);

        timer = new Timer(DELAY, new TimerEventHandler());

        pane = getContentPane();
        pane.setLayout(null);

        int r = (int)(9.0 * Math.random()) + 1;
        String str2 = Integer.toString(r);

        label = new JLabel(str2, SwingConstants.CENTER);
        label.setSize(150,30);
        label.setLocation(0,0);

        textField = new JTextField();
        textField.setSize(150,30);
        textField.setLocation(150,0);

        startB = new JButton("Start");
        startbh = new StartButtonHandler();
        startB.addActionListener(startbh);
        startB.setSize(100,30);
        startB.setLocation(0,30);

        stopB = new JButton("Stop");
        stopbh = new StopButtonHandler();
        stopB.addActionListener(stopbh);
        stopB.setSize(100,30);
        stopB.setLocation(100,30);

        exitB = new JButton("Exit");
        ebHandler = new ExitButtonHandler();
        exitB.addActionListener(ebHandler);
        exitB.setSize(100,30);
        exitB.setLocation(200,30);      

        pane.add(label);

        pane.add(textField);
        pane.add(startB);
        pane.add(stopB);
        pane.add(exitB);

        timer = new Timer(DELAY, new TimerEventHandler());

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private class TimerEventHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            int r = (int)(9.0 * Math.random()) + 1;
            String str = Integer.toString(r);
            currentNum = "";
            currentNum = str;
            label.setText(str);
            repaint();
        }
    }

    public class StartButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            timer.start();
        }
    }

    public class StopButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            timer.stop();
        }
    }

    private class ExitButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.exit(0);
        }
    }

    public static void main(String[] args){
        TimerClassPanel timerPanel = new TimerClassPanel();
        JOptionPane.showMessageDialog(null, "Type your guess (int between 1-9)" +
                " in the field then press 'ENTER'");
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if( e.getX() > 150 && e.getX() < 300 && e.getY() > 0 && e.getY() < 30)
        {   
            textField.setText("");
            repaint();
        }
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
}
Evelynneven answered 12/4, 2012 at 23:40 Comment(1)
*"Here is the code in its entirety:" The 'entire' class would need imports. For better help sooner, post an SSCCE.Danelaw
V
28

TL;DR

Anyway, registering a MouseAdapter and overriding mouseClicked worked for me,

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ClickAndClearDemo {
    private static void createAndShowGUI(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));

        final JTextField textField = new JTextField("Enter text here...");
        textField.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
                textField.setText("");
            }
        });

        frame.add(textField);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

I hope this example gets you started in the right direction!

Vitrescence answered 13/4, 2012 at 0:3 Comment(1)
Although I think the addFocusListener approach is normally the better way, this method has the advantage of working ven when the text field is disabled.Phosphaturia
S
15

You can simply add a FocusListener to the textfield.

 final JTextField textField = new JTextField("Enter text here...");
    textField.addFocusListener(new FocusListener(){
        @Override
        public void focusGained(FocusEvent e){
            textField.setText("");
        }
    });
Situate answered 13/4, 2012 at 0:11 Comment(1)
This is the most appropriate answer when the textfield is not disabled. Note that you also need to provide an override for focusLost to make a valid FocusListener.Phosphaturia
B
3

This worked for me. Of course, the text is cleared when you click, and you can enter new text. To clear the text again via a click, the textfield has to lose focus and then regain focus from the mouse. I am not entirely sure what you are looking for here.

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

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

public class ClickTextField extends JTextField implements MouseListener{

public static void main(String[] args) {
    new ClickTextField();
}

public ClickTextField() {
    addMouseListener(this);

    JFrame J = new JFrame();
    J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    J.setSize(100,100);
    J.getContentPane().add(this);
    setText("Texty text...");
    J.show();
}

@Override
public void mouseClicked(MouseEvent e) {

    setText("");

}

@Override
public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

}

}
Bisayas answered 13/4, 2012 at 0:9 Comment(1)
subclassing is sub-optimal if you don't add really new functionality (aka: not approachable by configuration). Exposing public api that's not meant to be used publicly is .. a sin in OO-world :_)Medallist
P
3

Is it to clear the 'hint' text?

I think this is what you're trying to do...

textField.addMouseListener(new MouseAdapter())
    {
        public void mouseClicked(MouseEvent e)
        {
            if(textField.getText().equals("Default Text"))
            {
                textField.setText("");
                repaint();
                revalidate();
            }           
        }
    });
Pollie answered 29/6, 2013 at 17:39 Comment(0)
H
0

I had to do this as well. What I did was simply making a custom JTextField. Something like:

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

@SuppressWarnings("serial")
public class InputField extends JTextField implements MouseListener,ActionListener
{
public InputField(String text) 
{
    super(text);
    super.setHorizontalAlignment(RIGHT);
    super.addMouseListener(this);
}

@Override
public void mouseClicked(MouseEvent e) 
{
    // TODO Auto-generated method stub
    if (getText().equals("0.0"))
    {
        setText("");
    }
}

@Override
public void mouseEntered(MouseEvent e) 
{

}

@Override
public void mouseExited(MouseEvent e)
{

}

@Override
public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    // if the mouse is pressed and "0.0" is the text, we erase the text
    if (getText().equals("0.0"))
    {
        setText("");
    }
}

@Override
public void mouseReleased(MouseEvent e) 
{
    maybeShowPopup(e);
}

private void maybeShowPopup(MouseEvent event)
{
    //if the user clicked the right mouse button
    if (javax.swing.SwingUtilities.isRightMouseButton(event))
    {
        //create (and show) the popup
        createPopup().show(event.getComponent(), event.getX(), event.getY());
    }
}

private JPopupMenu createPopup()
{
    JPopupMenu popupMenu = new JPopupMenu();
    //add the clearTextOption to the JPopupMenu
    JMenuItem clearTextOption = new JMenuItem("Clear text");
    clearTextOption.addActionListener(this);
    popupMenu.add(clearTextOption);
    return popupMenu;
}

@Override
public void actionPerformed(ActionEvent arg0) {
    //clear the TextField
    setText("");
}

} //end custom TextField

In this custom TextField, I simply used a MouseListener. The advantages of making a custom one are:

  1. I can have it directly implement MouseListener (instead of having to use some confusing anonymous inner class)
  2. I can make a crapton of customizations (including the option for users to right-click the TextField and select an item from a PopupMenu. //I am currently working on options for users to copy, paste, and drag-and-drop.
  3. I can do all this without crowding the main .java file with extra code that would make for more stuff to dig through later. Although MikeWarren.getAnswer(this) extends richard.getAnswer(this), I thought I would elaborate a little more and show some code I actually used in one of my programs.
Hodgepodge answered 5/7, 2013 at 15:15 Comment(1)
1. is wrong: never expose api that's not meant for public use 2. the way to install a popup without subclassing is setComponentPopupMenu, all textComponents already have copy/paste/cut actions which can be used in a popup 3. sounds like you are coupling too many thingies: separate out the data from the view will clean up most of the "crowding" - in summary: no reason to subclass so far :-)Medallist
M
0
 jTextField2.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton()==1) {
                    jTextField2.setText("");
                }//3 = for right click 
                //2 for middlemouse
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });

you can try with this approach too.

Masorete answered 22/4, 2016 at 14:53 Comment(0)
H
-1

public JTextField userInput;

right after executing the text:

userInput.setText(""); // empty

This should do.

Hartzell answered 20/4, 2016 at 3:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.