
Vamos a realizar un programa de escritorio usando Java Swing. Consiste en hacer un juego de adivinar la suma de dos números generados aleatoriamente.
Necesitamos los siguientes controles:
- 6 JTextField
- 6 JLabel
- 3 JButton
Un botón se encargará de generar y mostrar los dos números aleatorios, el siguiente botón activa una ventanita para introducir la suma de esos dos y comprobar si es correcta (acierto) o no (fallo) y mostrará el número de intentos realizados.
Y por último un botón para quitar la aplicación.
Como se trata de una aplicación gráfica es necesario importar las librerías javax.swing.* y java.awt.*.
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.*;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class Aleatorio extends JFrame{
public Aleatorio(){
//..
//..
}
}
Los controles a usar para los que utilizaremos las clases JTextField y JButton:
final private JTextField txtNum1,txtNum2,txtResultado,txtIntentos,txtAciertos,txtFallas;
private JButton btnActiva,btnComprueba;
private JButton btnSalir;
También necesitamos definir las variables que controlarán los valores aleatorios y su suma, así como los aciertos, fallos e intentos:
//los dos números tomarán un valor aleatoriamete
private long num1,num2,valor;
//la suma
long suma_prog;
int intentos=0,aciertos=0,fallas=0;
Para generar los números aleatorios creamos una función:
public long obtenerAleatorio1(){
return (long)(Math.random()*1000);
}
Puedes leer más información sobre como crear un número aleatorio con Java.
Ahora pasamos a codificar los botones Activar, Comprobar y Salir.
Activar
Este botón inicia el juego, para ello lo que hacemos es crear dos números aleatorios, con la clase creada anteriormente, y los ponemos dentro de los campos de texto sus valores.
btnActiva= new JButton("Activar");
btnActiva.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Aleatorio aleatorio=new Aleatorio();
aleatorio.setNum1(aleatorio.obtenerAleatorio1());
aleatorio.setNum2(aleatorio.obtenerAleatorio2());
txtNum1.setText(String.valueOf(aleatorio.getNum1()));// no. 1
txtNum2.setText(String.valueOf(aleatorio.getNum2()));// no.2
txtResultado.setText("");
}
});
Comprobar
Es el botón que lanza el juego, lo que hace es crear un dialogo, mediante una clase JOptionPane. Cogemos el valor insertado por el usuario y comprobamos si coincide con la suma de los números aleatorios. Si es así incrementamos los aciertos, si no coincide, incrementamos los fallos.
btnComprueba= new JButton("Comprobar");
btnComprueba.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Aleatorio alea=new Aleatorio();
valor=Long.parseLong(JOptionPane.showInputDialog("Introduce valor"));
alea.setValor(valor);
txtResultado.setText(String.valueOf(alea.getValor()));//valor del usuario
suma_prog=Long.parseLong(txtNum1.getText())+ Long.parseLong(txtNum2.getText());
if(suma_prog==alea.getValor()){
aciertos+=1;
intentos+=1;
txtIntentos.setText(String.valueOf(intentos));
txtAciertos.setText(String.valueOf(aciertos));
}else{
fallas+=1;
intentos+=1;
txtIntentos.setText(String.valueOf(intentos));
txtFallas.setText(String.valueOf(fallas));
}
}
});
Salir
En este caso, lo que hacemos es salir de la aplicación mediante el método System.exit.
btnSalir= new JButton("Salir");
btnSalir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Espero les sea de utilidad.
Dani
No me quiere correr el programa. Sabes lo que me falta?
import java.awt.BorderLayout;
import javax.swing.UIManager;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.*;
public class OperacionesMedio extends JFrame {
private JPanel contentPane;
final private JTextField txtNum1,txtNum2,txtResultado,txtIntentos,txtAciertos,txtFallas;
private JButton btnActiva,btnComprueba;
private JButton btnSalir;
private long num1,num2,valor;
long suma_prog;
int intentos=0,aciertos=0,fallas=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OperacionesMedio frame = new OperacionesMedio();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public OperacionesMedio() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNumero = new JLabel(«Numero 1»);
lblNumero.setBounds(10, 11, 71, 14);
contentPane.add(lblNumero);
txtNum1 = new JTextField();
txtNum1.setBounds(60, 8, 86, 20);
contentPane.add(txtNum1);
txtNum1.setColumns(10);
JLabel label = new JLabel(«+»);
label.setBounds(156, 11, 46, 14);
contentPane.add(label);
JLabel lblNumero_1 = new JLabel(«Numero2»);
lblNumero_1.setBounds(171, 11, 46, 14);
contentPane.add(lblNumero_1);
JLabel label_1 = new JLabel(«=»);
label_1.setBounds(273, 11, 71, 14);
contentPane.add(label_1);
JLabel lblResultado = new JLabel(«Resultado»);
lblResultado.setBounds(288, 11, 46, 14);
contentPane.add(lblResultado);
txtNum2= new JTextField();
txtNum2.setBounds(223, 8, 40, 20);
contentPane.add(txtNum2);
txtNum2.setColumns(10);
txtResultado = new JTextField();
txtResultado.setBounds(354, 8, 70, 20);
contentPane.add(txtResultado);
txtResultado.setColumns(10);
JLabel lblIntentos = new JLabel(«Intentos»);
lblIntentos.setBounds(10, 60, 46, 14);
contentPane.add(lblIntentos);
txtIntentos = new JTextField();
txtIntentos.setBounds(60, 57, 86, 20);
contentPane.add(txtIntentos);
txtIntentos.setColumns(10);
txtAciertos = new JTextField();
txtAciertos.setBounds(207, 57, 86, 20);
contentPane.add(txtAciertos);
txtAciertos.setColumns(10);
JLabel lblAciertos = new JLabel(«Aciertos»);
lblAciertos.setBounds(156, 60, 46, 14);
contentPane.add(lblAciertos);
JLabel lblFallas = new JLabel(«Fallas»);
lblFallas.setBounds(303, 60, 46, 14);
contentPane.add(lblFallas);
txtFallas = new JTextField();
txtFallas.setBounds(338, 57, 86, 20);
contentPane.add(txtFallas);
txtFallas.setColumns(10);
JButton btnActivar = new JButton(«Activar»);
btnActivar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OperacionesMedio aleatorio=new OperacionesMedio();
aleatorio.setNum1(aleatorio.obtenerAleatorio1());
aleatorio.setNum2(aleatorio.obtenerAleatorio2());
txtNum1.setText(String.valueOf(aleatorio.getNum1()));// no. 1
txtNum2.setText(String.valueOf(aleatorio.getNum2()));// no.2
txtResultado.setText(«»);
}
});
btnActivar.setBounds(87, 105, 89, 23);
contentPane.add(btnActivar);
JButton btnComprobar = new JButton(«Comprobar»);
btnComprobar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OperacionesMedio alea=new OperacionesMedio();
valor=Long.parseLong(JOptionPane.showInputDialog(«Introduce valor»));
alea.setValor(valor);
txtResultado.setText(String.valueOf(alea.getValor()));//valor del usuario
suma_prog=Long.parseLong(txtNum1.getText())+ Long.parseLong(txtNum2.getText());
if(suma_prog==alea.getValor()){
aciertos+=1;
intentos+=1;
txtIntentos.setText(String.valueOf(intentos));
txtAciertos.setText(String.valueOf(aciertos));
}else{
fallas+=1;
intentos+=1;
txtIntentos.setText(String.valueOf(intentos));
txtFallas.setText(String.valueOf(fallas));
}
}
});
btnComprobar.setBounds(186, 105, 89, 23);
contentPane.add(btnComprobar);
JButton btnSalir = new JButton(«Salir»);
btnSalir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnSalir.setBounds(300, 105, 89, 23);
contentPane.add(btnSalir);
}
public long obtenerAleatorio1(){
return (long)(Math.random()*1000);
}
public JButton getBtnActiva() {
return btnActiva;
}
public void setBtnActiva(JButton btnActiva) {
this.btnActiva = btnActiva;
}
}
Fabian
podrias hacer un comentario programandolo?
ARIEL
Que bueno que le sirvió :)
Nefi
Excelente :D