名前用と電話番号用に2つのテキストを入力した単純なGUIフォームを作成しています。ボタンをクリックすると、それらを検証して空に設定しようとしています。しかし、もう一度ボタンをクリックすると、私が望んでいない JOptionPane Opened が表示されます。このアプローチを手伝ってください。
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
public class Form {
public static void main(String args[]) {
final JFrame frame = new JFrame("Hello");
final JButton btnOne = new JButton("save");
final JTextField jname = new JTextField(8);
final JTextField jphno = new JTextField(8);
final JLabel lname = new JLabel("Name");
final JLabel lphno = new JLabel("Phone no");
frame.getContentPane().setBackground(new Color(58, 192, 126));
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jname.getText().length() <= 2) {
JOptionPane.showMessageDialog(null,
"please enter at least Three digits");
}
}
});
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jphno.getText().trim().length() != 10) {
JOptionPane.showMessageDialog(null,
"Please enter Valid Phone no");
}
}
});
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int j = jphno.getText().length();
int h = jname.getText().length();
if (e.getSource() == btnOne && j == 10 && h >= 3) {
jname.setText("");
jphno.setText("");
}
}
});
jname.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
if (fe.getSource() == jname) {
jname.setText("");
}
}
});
jphno.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
if (fe.getSource() == jphno) {
jphno.setText("");
}
}
});
// adding components
frame.setLayout(gbl);
gbc.anchor = gbc.WEST;
gbc.insets = new Insets(0, 30, 20, 30);
gbc.gridx = 0;
gbc.gridy = 0;
frame.add(lname, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
frame.add(jname, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
frame.add(lphno, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
frame.add(jphno, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
frame.add(btnOne, gbc);
btnOne.setBackground(Color.CYAN);
btnOne.setBackground(Color.GRAY);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}