Supposons que vous écriviez votre code dans une classe public class Inventory extends javax.swing.JFrame
(comme vous l'avez précisé dans votre commentaire), j'écrirais un ActionListener
pour gérer l'événement de clic sur le bouton
public class Inventory extends javax.swing.JFrame
private String currPhoneNumber; // it may contains something like "1-(80..2)-321-0361"
...
// this code can be *within* your class, but *outside* any method declaration
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.out.println(currPhoneNumber.length());
String regex = "^\\+?[0-9. ()-]{10,25}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(currPhoneNumber);
}
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
// throw an exception or do something that will prevent the data to be
// saved (what to do here really depends on the application you are writing)
}
}
...
private void createMyFancyInterface(...) {
...
JButton source = new JButton("Do something");
source.addActionListener(new ButtonListener());
...
}
}
Vous pouvez également (comme quelqu'un l'a souligné) utiliser des classes anonymes, ce qui réduit le problème à ce qui suit :
public class Inventory extends javax.swing.JFrame
private String currPhoneNumber; // it may contains something like "1-(80..2)-321-0361"
...
// this code can be *within* your class, but *outside* any method declaration
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.out.println(currPhoneNumber.length());
String regex = "^\\+?[0-9. ()-]{10,25}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(currPhoneNumber);
}
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
// throw an exception or do something that will prevent the data to be
// saved (what to do here really depends on the application you are writing)
}
}
...
private void createMyFancyInterface(...) {
...
JButton source = new JButton("Do something");
source.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// the same code as ButtonListener.actionPerformed above
...
}
});
...
}
}