public class Sumar extends JFrame{
private JTextField jtNumero;
private JTextField jtSuma;
private JButton btSumar;
public Sumar() { jtNumero = new JTextField(4);
jtSuma = new JTextField(4);
jtSuma.setEditable(false);
btSumar = new JButton("SUMAR"); btSumar.addActionListener(new AccionSumar());
JPanel panel = new JPanel();
panel.add(jtNumero);
panel.add(btSumar);
panel.add(jtSuma);
panel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
add(panel);
setTitle("Sumar"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private class AccionSumar implements ActionListener { @Override
public void actionPerformed(ActionEvent e) { String numero = jtNumero.getText();
try { int num = Integer.parseInt(numero);
jtSuma.setText(Integer.toString(num + num));
}catch(NumberFormatException ex) { JOptionPane.showMessageDialog(null, "No ha introducido un número entero",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override
public void run() { new Sumar();
}
});
}
}