检查JTextField是否为空

时间:2017-02-27 03:20:59

标签: java swing actionlistener java-7 jtextfield

我正在尝试为GUI创建示例,它从JTextFiled中的用户获取名称,并为用户显示在JtextField中输入的名称的消息,现在我想要方法检查用户是否输入按钮而不输入任何内容,我试图在ActionListener中使用这个方法,但我在编辑器中看到错误,而当我在ActionListener之外使用它时,我看到它的工作原理! ,请参阅附件图片

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

}

error message

修改 问题是因为我把代码置于可执行上下文之外的“方法”

1 个答案:

答案 0 :(得分:4)

以...

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