5

我正在使用 Netbeans IDE。我想以JTextfield这样一种方式提供提示文本,即当用户输入文本时,JTextField它会被清除并接受用户输入。

4

2 回答 2

4

我不知道 David Kroukamp 已经看到了什么 propt-text-fields,但是使用以下代码我创建了我知道的那些 textFields ;)

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

public class PTextField extends JTextField {

    public PTextField(final String proptText) {
        super(proptText);
        addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                if(getText().isEmpty()) {
                    setText(proptText);
                }
            }

            @Override
            public void focusGained(FocusEvent e) {
                if(getText().equals(proptText)) {
                    setText("");
                }
            }
        });

    }

}
于 2013-11-25T18:50:53.387 回答
2

您可以向文本字段添加一个简单的焦点侦听器,并在焦点丢失时验证文本字段的数据,如下所示:

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author David
 */
public class Test extends JFrame {

    private JTextField textField, textField2;

    public Test() {
        createAndShowUI();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    private void createAndShowUI() {
        setTitle("Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        createComponents();
        addComponentsToContentPane();
        addListeners();

        pack();
        setVisible(true);
    }

    private void addComponentsToContentPane() {
        getContentPane().setLayout(new GridLayout(2, 1));

        getContentPane().add(textField);
        getContentPane().add(textField2);
    }

    private void createComponents() {
        textField = new JTextField(10);
        textField2 = new JTextField("Click here to lose focus of above textField");
    }

    private void addListeners() {
        textField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent fe) {
            }

            @Override
            public void focusLost(FocusEvent fe) {
                if (textField.getText().length() >=1) {
                    JOptionPane.showMessageDialog(null, "You entered valid data");
                    textField.setText("");
                }else {
                    JOptionPane.showMessageDialog(null, "You entered invalid data");
                    textField.grabFocus();//make the textField in foucs again
                }
            }
        });
    }
}

为此,请在 NetBeans 中右键单击Component,选择Events -> Focus -> focusLost

于 2012-06-26T04:35:13.750 回答