-1

I am trying to create example for GUI its take the name from user in JTextFiled and appear message for user with their name that was entered in JtextField, now I wanna make method check if the user enter on the button without enter anything, I trying to use this method in ActionListener but I see error in editor, while when I use it outside the ActionListener I see it's works! , please see the attachment picture

    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

Edit
the problem is because I put code outside of an executable context "a method"

MML
  • 44
  • 1
  • 8
  • 21
  • this link might help http://stackoverflow.com/questions/17132452/java-check-if-jtextfield-is-empty-or-not – SomeStudent Feb 27 '17 at 03:23
  • You're trying to execute code outside of an executable context, ie, a method – MadProgrammer Feb 27 '17 at 03:26
  • I see this but I did not understand what's addDocumentListener doing exactly , I tried to add this code with some edits for my Jtextfield i seeing multiple errors – MML Feb 27 '17 at 03:29

1 Answers1

4

Take...

if (text.getText().equals("")) {
    JOptionPane.showMessageDialog(rootPane, "Please enter anything");
}

and put it inside you actionPerformed method...

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());
    }
});
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366