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);
}
}
Edit
the problem is because I put code outside of an executable context "a method"
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());
}
});