当鼠标单击JTextField时如何清除JTextField?

12

我需要让这个程序在鼠标点击文本字段时清除文本。我已经尝试了一些方法,但是它们都没有为我工作。

以下是完整的代码:

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

    }
}

1
以下是完整的代码:整个类都需要导入。为了更快地获得帮助,请发布一个SSCCE - Andrew Thompson
7个回答

27

简而言之:

无论如何,对MouseAdapter进行注册并覆盖mouseClicked方法对我有效。

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();
            }
        });
    }
}

我希望这个例子能够为你提供正确的方向!


虽然我认为addFocusListener方法通常是更好的方式,但这种方法有一个优势,即在文本字段被禁用时也能正常工作。 - beldaz

15
你可以简单地向文本框添加一个 FocusListener
 final JTextField textField = new JTextField("Enter text here...");
    textField.addFocusListener(new FocusListener(){
        @Override
        public void focusGained(FocusEvent e){
            textField.setText("");
        }
    });

1
当文本字段未被禁用时,这是最合适的答案。请注意,您还需要提供一个focusLost的覆盖来创建一个有效的FocusListener - beldaz

3

你是想清除“提示”文本吗?

我认为这就是你想做的...

textField.addMouseListener(new MouseAdapter())
    {
        public void mouseClicked(MouseEvent e)
        {
            if(textField.getText().equals("Default Text"))
            {
                textField.setText("");
                repaint();
                revalidate();
            }           
        }
    });

3

这对我很有用。当然,文本将在单击时清除,并且您可以输入新文本。要通过单击再次清除文本,文本字段必须失去焦点,然后从鼠标重新获得焦点。我不太确定您在这里寻找什么。

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

}

}

如果您不添加真正的新功能(即:无法通过配置访问),“子类化”就不是最佳选择。在面向对象的世界中,公开API而不打算公开使用是一种罪过 :_) - kleopatra

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) {

            }
        });

你也可以尝试这种方法。


0

我也曾经遇到过这个问题。我的解决方法是制作一个自定义的JTextField。像这样:

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

在这个自定义的TextField中,我只是简单地使用了一个MouseListener。制作自定义TextField的优点包括:
  1. 我可以直接实现MouseListener(而不必使用一些令人困惑的匿名内部类)
  2. 我可以进行大量的自定义(包括让用户右键单击TextField并从PopupMenu中选择项目的选项。//我目前正在为用户提供复制、粘贴和拖放选项。
  3. 我可以在不拥挤主要的.java文件的情况下完成所有这些额外的代码,这将导致更多的后续工作。虽然MikeWarren.getAnswer(this)扩展richard.getAnswer(this),但我认为我应该详细说明一下我在其中一个程序中实际使用的一些代码。

  1. 错误的做法:不要公开暴露不适用于公众使用的API。
  2. 安装弹出窗口的方法是使用setComponentPopupMenu,所有文本组件已经具有可在弹出窗口中使用的复制/粘贴/剪切操作。
  3. 听起来你把太多东西耦合在一起了:将数据与视图分离将清理大部分的“拥挤” - 总之:到目前为止没有理由进行子类化 :-)
- kleopatra

-1

公共的 JTextField userInput;

执行以下文本后:

userInput.setText(""); // 清空

应该可以了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接