检查JTextField是否为空
问题描述:
我正在尝试为GUI创建示例,它取自用户在JTextFiled中的名称,并为用户输入其在JtextField中输入的名称的消息,现在我想使用方法检查用户是否输入按钮没有输入任何东西,我试图在ActionListener中使用此方法,但我看到编辑器中的错误,而当我在ActionListener外部使用它时,我发现它是行得通的!请参阅附件图片检查JTextField是否为空
public class Example01 extends JFrame {
public JTextField text;
public Example01() {
setTitle("Example 01");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
JLabel label = new JLabel("Enter Your Name : ");
text = new JTextField();
text.setSize(30, 10);
JButton btn1 = new JButton("Enter");
btn1.addActionListener(new ActionListener() {
if (text.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Please enter anything");
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText());
}
});
panel.add(label);
panel.add(Box.createRigidArea(new Dimension(0, 20)));
panel.add(text);
panel.add(Box.createRigidArea(new Dimension(0, 20)));
panel.add(btn1);
add(panel);
setVisible(true);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
答
以...
if (text.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Please enter anything");
}
,并把它放在你actionPerformed
方法里面......
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (text.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Please enter anything");
}
JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText());
}
});
+0
感谢MadProgrammer其工作正常! – MML
此链接可能帮助http://stackoverflow.com/questions/17132452/java-check-if-jtext field-is-empty-or-not – SomeStudent
您试图在可执行上下文之外执行代码,即,方法 – MadProgrammer
我看到这个,但我不明白addDocumentListener究竟做了什么,我试图添加一些编辑代码为我的Jtextfield我看到多个错误 – MML