【问题标题】:Checking if JTextField not empty检查 JTextField 是否不为空
【发布时间】:2017-07-17 13:37:54
【问题描述】:

我正在尝试为 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

编辑
问题是因为我将代码放在可执行上下文“方法”之外

【问题讨论】:

  • 这个链接可能对stackoverflow.com/questions/17132452/…有帮助
  • 您正试图在可执行上下文之外执行代码,即方法
  • 我看到了这个,但我不明白 addDocumentListener 到底在做什么,我尝试为我的 Jtextfield 添加此代码并进行一些编辑,我看到多个错误

标签: java swing actionlistener java-7 jtextfield


【解决方案1】:

采取...

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

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 2016-07-16
    • 2015-06-21
    • 2017-04-17
    • 2011-10-17
    • 1970-01-01
    • 2021-10-17
    • 2012-01-07
    相关资源
    最近更新 更多