1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
public class MonPanel extends JFrame implements PropertyChangeListener {
private static final long serialVersionUID = -1100471146694377850L;
private JFormattedTextField jtf, jtf1;
private JTextField jt;
private JPanel pan;
public MonPanel() {
this.setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // opération par défaut
pan = new JPanel();
pan.setLayout((LayoutManager) new BoxLayout(pan, BoxLayout.PAGE_AXIS));
jtf1 = isNumeric(150, "##");
jt = new JTextField();
jt.setMinimumSize(new Dimension(150, 200));
pan.add(jtf1);
pan.add(jt);
jtf1.addPropertyChangeListener("value", this);
this.setContentPane(pan);// defini le panel de la JFrame
this.setVisible(true); // affiche la JFrame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // opération par
// défaut
}
public JFormattedTextField isNumeric(int size, String length) {
try {
jtf = new JFormattedTextField(size);
MaskFormatter format = new MaskFormatter(length);
jtf = new JFormattedTextField(format);
} catch (ParseException e) {
e.getStackTrace();
}
return jtf;
}
@Override
public void propertyChange(PropertyChangeEvent e) {
if ( e.getSource() == jtf1 && jtf1.getValue() != null ) {
System.out.println("jtf1 1 : " + jtf1.getValue());
try {
if(jtf1.isEditValid() && jtf1.getText().length() <= 1){
jtf1.commitEdit();
jtf1.setValue(jtf1.getValue());
}
} catch (ParseException e1) {
}
jt.requestFocus();
} else {
System.out.println("jtf1 3 : " + jtf1.getValue());
jtf1.requestFocus();
}
}
public static void main(String[] args) {
new MonPanel();
}
} |
Partager