我正在创建一个简单的 GUI 表单,其中我有两个文本,一个用于名称,另一个用于电话号码,我试图验证它们并在单击按钮时将它们设置为空。但是再次单击按钮时,我不想要打开的 JOptionPane,请帮助我采用这种方法。
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);
}
}