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
| public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel pan = new JPanel();
JTextField a = new JTextField();
JTextField b = new JTextField();
JTextArea c = new JTextArea();
Font police = new Font("Serif", Font.PLAIN, 20);
a.setFont(police);
b.setFont(police);
c.setFont(police);
a.setBounds(100, 100, 100, 25);
b.setBounds(300, 100, 100, 25);
c.setBounds(200, 200, 100, 25);
class DocumentAdapter implements DocumentListener {
private final JTextField field;
private final BiFunction<Integer, Integer, Integer> function;
public DocumentAdapter(JTextField field, BiFunction<Integer, Integer, Integer> function) {
this.field=field;
this.function=function;
}
public void changedUpdate(DocumentEvent e) {
update(e);
}
public void insertUpdate(DocumentEvent e) {
update(e);
}
public void removeUpdate(DocumentEvent e) {
update(e);
}
private void update(DocumentEvent e) {
try {
calcul(field.getText().trim(), e.getDocument().getText(0, e.getDocument().getLength()).trim(),c, function);
} catch (BadLocationException ex) {
}
}
}
a.getDocument().addDocumentListener(new DocumentAdapter(b, (o1,o2)-> o2/o1));
b.getDocument().addDocumentListener(new DocumentAdapter(a, (o1,o2)-> o1/o2));
pan.setLayout(null);
pan.add(a);
pan.add(b);
pan.add(c);
window.setContentPane(pan);
window.setSize(600, 400);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void calcul(String a, String b, JTextArea c, BiFunction<Integer, Integer, Integer> function) {
try {
int valuea = Integer.parseInt(a);
int valueb = Integer.parseInt(b);
c.setText(String.valueOf(function.apply(valuea, valueb)));
}
catch (NumberFormatException e) {
if ( !a.isEmpty() && !b.isEmpty() ) {
c.setText("ERROR");
}
else {
c.setText("");
}
}
}
} |
Partager