Hola a todos, hoy os dejo una serie de ejercicios de Java para practicar todo aquello que hemos explicado en anteriores posts, haciendo hincapié en las aplicaciones en Java. Todos los ejercicios que proponemos están resueltos en este mismo post, intenta hacerlo por ti mismo y si te quedas atascado puedes mirar la solución.Recuerda, que no tiene por que estar igual tu solución con la del post, el objetivo es que aprendas no que me copies la solución.
Crea un proyecto en Java por ejercicio.
Estos ejercicios han sido creado con netBeans, si usas eclipse, te recomiendo que copies simplemente aquella parte del código que te interese o instales netbeans, ya que puedes importar el proyecto.
Colocare en las soluciones algunos comentarios para que sean más fácilmente entendible.
Te recomiendo que uses mensajes de trazas, donde te sean necesarios. Si tienes problemas también puedes usar el depurador.
Si tienes alguna duda, recuerda que puedes consultarnos escribiendo un comentario en este post o enviándonos un e-mail a administrador@discoduroderoer.es
Aquí tienes todos los posts relacionados con Java:
Si tienes alguna duda, recuerda que puedes consultarnos escribiendo un comentario en este post o enviándonos un e-mail a administrador@discoduroderoer.es
1) Crea un saludador personalizable. Consiste en un simple JFrame con un campo de texto (JTextField) y un botón (JButton). Cuando pulsemos el botón, aparecerá un mensaje emergente (JOptionPane) con el texto «¡Hola <texto escrito en el campo de texto>!».
Spoiler Inside | SelectShow> |
---|---|
import javax.swing.JOptionPane; /** * @author DiscoDurodeRoer */ public class SaludadorApp extends javax.swing.JFrame { public SaludadorApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnSaludador = new javax.swing.JButton(); txtNombre = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Saludador"); btnSaludador.setText("¡Saludar!"); btnSaludador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSaludadorActionPerformed(evt); } }); jLabel1.setText("Escribe un nombre para saludar"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(172, 172, 172) .addComponent(btnSaludador)) .addGroup(layout.createSequentialGroup() .addGap(70, 70, 70) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(124, 124, 124) .addComponent(jLabel1))) .addContainerGap(73, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jLabel1) .addGap(41, 41, 41) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addComponent(btnSaludador) .addContainerGap(55, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btnSaludadorActionPerformed(java.awt.event.ActionEvent evt) { //Muestra el texto que esta en el textbox JOptionPane.showMessageDialog(this, "¡Hola "+txtNombre.getText()+"!"); } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SaludadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SaludadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SaludadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SaludadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SaludadorApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnSaludador; private javax.swing.JLabel jLabel1; private javax.swing.JTextField txtNombre; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
2) Crea una simple lista de peliculas. tendremos un JComboBox, donde almacenaremos las peliculas, que vayamos almacenando en un campo de texto. Al pulsar el botón Añadir la pelicula que hayamos metido, se introducirá en el JComboBox.
Spoiler Inside | SelectShow> |
---|---|
/** * @author DiscoDurodeRoer */ public class PeliculasApp extends javax.swing.JFrame { public PeliculasApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { cmbPeliculas = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); txtPelicula = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); btnanadir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Peliculas"); jLabel1.setText("Peliculas"); jLabel2.setText("Escribe el titulo de una pelicula"); btnanadir.setText("Añadir"); btnanadir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnanadirActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(txtPelicula, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(cmbPeliculas, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(47, 47, 47)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(106, 106, 106)))) .addGroup(layout.createSequentialGroup() .addGap(54, 54, 54) .addComponent(btnanadir) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbPeliculas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPelicula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(btnanadir) .addContainerGap(29, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btnanadirActionPerformed(java.awt.event.ActionEvent evt) { //Cogemos el texto del campo de texto String pelicula=txtPelicula.getText(); //Añadimos la pelicula al combobox cmbPeliculas.addItem(pelicula); //Reiniciamos el campo de texto txtPelicula.setText(""); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PeliculasApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PeliculasApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PeliculasApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PeliculasApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PeliculasApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnanadir; private javax.swing.JComboBox cmbPeliculas; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField txtPelicula; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
3) Crea una miniencuesta gráfica. Daremos una serie de opciones para que el usuario elija. La encuesta preguntará lo siguiente:
- Elije un sistema operativo (solo una opción, JRadioButton)
- Windows
- Linux
- Mac
- Elije tu especialidad (pueden seleccionar ninguna o varias opciones, JCheckBox)
- Programación
- Diseño gráfico
- Administración
- Horas dedicadas en el ordenador (usaremos un slider entre 0 y 10)
Para el slider, os recomiendo usar un JLabel, que os diga que valor tiene el slider, usad el evento stateChanged.
Spoiler Inside | SelectShow> |
---|---|
import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.JRadioButton; /** * @author DiscoDurodeRoer */ public class MiniEncuestaApp extends javax.swing.JFrame { public MiniEncuestaApp() { initComponents(); //Creamos una instacia de ButtonGroup ButtonGroup btg=new ButtonGroup(); //Añadimos los botones radiobutton //Si no lo hacemos, los botones seran independientes btg.add(rdbWindows); btg.add(rdbLinux); btg.add(rdbMac); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { rdbWindows = new javax.swing.JRadioButton(); rdbLinux = new javax.swing.JRadioButton(); rdbMac = new javax.swing.JRadioButton(); jLabel1 = new javax.swing.JLabel(); ckbProgramacion = new javax.swing.JCheckBox(); jLabel2 = new javax.swing.JLabel(); ckbDiseno = new javax.swing.JCheckBox(); ckbAdministracion = new javax.swing.JCheckBox(); jSeparator1 = new javax.swing.JSeparator(); btnGenerar = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); sldHoras = new javax.swing.JSlider(); jLabel3 = new javax.swing.JLabel(); lblHoras = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Mini Encuesta"); rdbWindows.setText("Windows"); rdbLinux.setText("Linux"); rdbMac.setText("Mac"); jLabel1.setText("Elige un sistema operativo"); ckbProgramacion.setText("Programación"); jLabel2.setText("Elige tu especialidad"); ckbDiseno.setText("Diseño gráfico"); ckbAdministracion.setText("Administración"); btnGenerar.setText("Generar"); btnGenerar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerarActionPerformed(evt); } }); sldHoras.setMaximum(10); sldHoras.setValue(0); sldHoras.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { sldHorasStateChanged(evt); } }); jLabel3.setText("Horas que dedicas en el ordenador"); lblHoras.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblHoras.setText("0"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ckbProgramacion) .addComponent(jLabel2) .addComponent(ckbAdministracion) .addComponent(ckbDiseno) .addComponent(jLabel3) .addComponent(jLabel1) .addComponent(rdbLinux) .addComponent(rdbMac) .addComponent(rdbWindows))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(lblHoras, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sldHoras, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(24, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGap(66, 66, 66) .addComponent(btnGenerar) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(rdbWindows) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rdbLinux) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rdbMac) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addGap(13, 13, 13) .addComponent(ckbProgramacion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ckbDiseno) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ckbAdministracion) .addGap(19, 19, 19) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(sldHoras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 1, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblHoras, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(btnGenerar) .addContainerGap(21, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) { String informacion="Tu sistema operativo preferido es "; //Cogemos todos los radiobutton en un array JRadioButton[] rdbs={rdbWindows, rdbLinux, rdbMac}; for(int i=0;i<rdbs.length;i++){ //Si esta seleccionado, coge el texto if(rdbs[i].isSelected()){ informacion+=rdbs[i].getText(); } } //Hacemos igual con los checkboxes JCheckBox[] ckbs={ckbProgramacion, ckbDiseno, ckbAdministracion}; informacion+=", \ntus especialidades son "; for(int i=0;i<ckbs.length;i++){ if(ckbs[i].isSelected()){ informacion+=ckbs[i].getText()+" "; //Ponemos un espacio por si hay mas de un elemento seleccionado } } informacion+=" \ny el numero de horas dedicadas al ordenador son "+sldHoras.getValue(); JOptionPane.showMessageDialog(this, informacion, "Muestra de datos", JOptionPane.INFORMATION_MESSAGE); } private void sldHorasStateChanged(javax.swing.event.ChangeEvent evt) { lblHoras.setText(String.valueOf(sldHoras.getValue())); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MiniEncuestaApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MiniEncuestaApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MiniEncuestaApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MiniEncuestaApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MiniEncuestaApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnGenerar; private javax.swing.JCheckBox ckbAdministracion; private javax.swing.JCheckBox ckbDiseno; private javax.swing.JCheckBox ckbProgramacion; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JLabel lblHoras; private javax.swing.JRadioButton rdbLinux; private javax.swing.JRadioButton rdbMac; private javax.swing.JRadioButton rdbWindows; private javax.swing.JSlider sldHoras; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
4) Crea un generador de números gráfico. Nosotros escribiremos seleccionaremos dos números en unos JSpinner (contadores) y se nos mostrara en un JTextField, el número generado entre esos dos números, al pulsar en el botón. El JTextField no debe ser editable.
Spoiler Inside | SelectShow> |
---|---|
/** * @author DiscoDurodeRoer */ public class GeneradorNumerosApp extends javax.swing.JFrame { public GeneradorNumerosApp() { initComponents(); } /** * Genera un numero aleatorio entre dos numeros. * Entre el minimo y el maximo incluidos * @param minimo Número mínimo * @param maximo Número máximo * @return Número entre minimo y maximo */ private int generaNumeroAleatorio(int minimo, int maximo){ int num=(int)Math.floor(Math.random()*(minimo-(maximo+1))+(maximo+1)); return num; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnGenerar = new javax.swing.JButton(); spnNumero1 = new javax.swing.JSpinner(); spnNumero2 = new javax.swing.JSpinner(); txtNumeroGenerado = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Generador de números"); btnGenerar.setText("Generar"); btnGenerar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerarActionPerformed(evt); } }); spnNumero1.setModel(new javax.swing.SpinnerNumberModel()); spnNumero2.setModel(new javax.swing.SpinnerNumberModel()); txtNumeroGenerado.setEditable(false); jLabel1.setText("Número 1"); jLabel2.setText("Número 2"); jLabel3.setText("Número generado"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(spnNumero2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtNumeroGenerado) .addComponent(spnNumero1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 36, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnGenerar) .addGap(87, 87, 87)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(spnNumero1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(spnNumero2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNumeroGenerado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(32, 32, 32) .addComponent(btnGenerar) .addContainerGap(27, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) { //Sacamos el valor de los JSpinner int numero1=(int)spnNumero1.getValue(); int numero2=(int)spnNumero2.getValue(); //Pasamos a cadena el número que generamos String numeroGenerado=String.valueOf(generaNumeroAleatorio(numero1,numero2)); //Mostramos el numero generado txtNumeroGenerado.setText(numeroGenerado); } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GeneradorNumerosApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GeneradorNumerosApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GeneradorNumerosApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GeneradorNumerosApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GeneradorNumerosApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnGenerar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JSpinner spnNumero1; private javax.swing.JSpinner spnNumero2; private javax.swing.JTextField txtNumeroGenerado; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
5) Vamos a crear un imitador, como si fuera un espejo. Tendremos dos pares de conjunto de elementos separados (puedes usar un separador) y cuando nosotros pinchamos en un elemento o escribimos en un campo, se debe cambiar el otro lado.
Por ejemplo, si yo tengo un campo de texto y escribo en él, el campo de texto que es su reflejo también recibirá ese texto.
Podeis usar los elementos que queráis, os recomiendo: JTextField, JRadioButton, JCheckBox, JTextArea, JSpinner, etc.
Mirad los eventos, os serán útiles.
Solo podéis modificar de un lado, el otro conjunto no lo podéis modificar, es decir, que no es bidireccional.
Spoiler Inside | SelectShow> |
---|---|
import javax.swing.ButtonGroup; /** * @author DiscoDurodeRoer */ public class ImitadorApp extends javax.swing.JFrame { public ImitadorApp() { initComponents(); //añadimos los radiobutton en sus respectivos grupos ButtonGroup btg1=new ButtonGroup(); btg1.add(rdb1Original); btg1.add(rdb2Original); btg1.add(rdb3Original); ButtonGroup btg2=new ButtonGroup(); btg2.add(rdb1Imitacion); btg2.add(rdb2Imitacion); btg2.add(rdb3Imitacion); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jSeparator1 = new javax.swing.JSeparator(); spnOriginal = new javax.swing.JSpinner(); rdb3Original = new javax.swing.JRadioButton(); ckb1Original = new javax.swing.JCheckBox(); ckb2Original = new javax.swing.JCheckBox(); rdb1Original = new javax.swing.JRadioButton(); ckb3Original = new javax.swing.JCheckBox(); rdb2Original = new javax.swing.JRadioButton(); cmbOriginal = new javax.swing.JComboBox(); txtOriginal = new javax.swing.JTextField(); txtImitacion = new javax.swing.JTextField(); spnImitacion = new javax.swing.JSpinner(); cmbImitacion = new javax.swing.JComboBox(); rdb3Imitacion = new javax.swing.JRadioButton(); ckb1Imitacion = new javax.swing.JCheckBox(); ckb2Imitacion = new javax.swing.JCheckBox(); rdb1Imitacion = new javax.swing.JRadioButton(); ckb3Imitacion = new javax.swing.JCheckBox(); rdb2Imitacion = new javax.swing.JRadioButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Imitador"); spnOriginal.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { spnOriginalStateChanged(evt); } }); rdb3Original.setText("Opcion 3"); rdb3Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdb3OriginalActionPerformed(evt); } }); ckb1Original.setText("Opcion 4"); ckb1Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ckb1OriginalActionPerformed(evt); } }); ckb2Original.setText("Opcion 5"); ckb2Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ckb2OriginalActionPerformed(evt); } }); rdb1Original.setText("Opcion 1"); rdb1Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdb1OriginalActionPerformed(evt); } }); ckb3Original.setText("Opcion 6"); ckb3Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ckb3OriginalActionPerformed(evt); } }); rdb2Original.setText("Opcion 2"); rdb2Original.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdb2OriginalActionPerformed(evt); } }); cmbOriginal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cmbOriginal.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { cmbOriginalItemStateChanged(evt); } }); txtOriginal.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtOriginalKeyTyped(evt); } }); txtImitacion.setEnabled(false); spnImitacion.setEnabled(false); cmbImitacion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cmbImitacion.setEnabled(false); rdb3Imitacion.setText("Opcion 3"); rdb3Imitacion.setEnabled(false); ckb1Imitacion.setText("Opcion 4"); ckb1Imitacion.setEnabled(false); ckb2Imitacion.setText("Opcion 5"); ckb2Imitacion.setEnabled(false); rdb1Imitacion.setText("Opcion 1"); rdb1Imitacion.setEnabled(false); ckb3Imitacion.setText("Opcion 6"); ckb3Imitacion.setEnabled(false); rdb2Imitacion.setText("Opcion 2"); rdb2Imitacion.setEnabled(false); jLabel1.setText("Original"); jLabel2.setText("Espejo"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(rdb2Original) .addComponent(rdb1Original) .addComponent(rdb3Original)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ckb2Original) .addComponent(ckb1Original) .addComponent(ckb3Original)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtOriginal) .addComponent(cmbOriginal, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(spnOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(rdb2Imitacion) .addComponent(rdb1Imitacion) .addComponent(rdb3Imitacion)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ckb2Imitacion) .addComponent(ckb1Imitacion) .addComponent(ckb3Imitacion)) .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtImitacion) .addComponent(cmbImitacion, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(spnImitacion, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2))) .addContainerGap(26, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(ckb1Original)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rdb1Original))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rdb2Original) .addComponent(ckb2Original)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ckb3Original) .addComponent(rdb3Original)) .addGap(41, 41, 41)) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(txtOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cmbOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(spnOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rdb1Imitacion) .addComponent(ckb1Imitacion)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(txtImitacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cmbImitacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rdb2Imitacion) .addComponent(ckb2Imitacion))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(spnImitacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ckb3Imitacion) .addComponent(rdb3Imitacion)) .addGap(0, 39, Short.MAX_VALUE)))) ); pack(); }// </editor-fold> private void rdb1OriginalActionPerformed(java.awt.event.ActionEvent evt) { rdb1Imitacion.setSelected(true); } private void rdb2OriginalActionPerformed(java.awt.event.ActionEvent evt) { rdb2Imitacion.setSelected(true); } private void rdb3OriginalActionPerformed(java.awt.event.ActionEvent evt) { rdb3Imitacion.setSelected(true); } private void ckb1OriginalActionPerformed(java.awt.event.ActionEvent evt) { ckb1Imitacion.setSelected(ckb1Original.isSelected()); } private void ckb2OriginalActionPerformed(java.awt.event.ActionEvent evt) { ckb2Imitacion.setSelected(ckb2Original.isSelected()); } private void ckb3OriginalActionPerformed(java.awt.event.ActionEvent evt) { ckb3Imitacion.setSelected(ckb3Original.isSelected()); } private void txtOriginalKeyTyped(java.awt.event.KeyEvent evt) { txtImitacion.setText(txtOriginal.getText()); } private void spnOriginalStateChanged(javax.swing.event.ChangeEvent evt) { spnImitacion.setValue((Integer)spnOriginal.getValue()); } private void cmbOriginalItemStateChanged(java.awt.event.ItemEvent evt) { cmbImitacion.setSelectedIndex(cmbOriginal.getSelectedIndex()); } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ImitadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ImitadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ImitadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ImitadorApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ImitadorApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JCheckBox ckb1Imitacion; private javax.swing.JCheckBox ckb1Original; private javax.swing.JCheckBox ckb2Imitacion; private javax.swing.JCheckBox ckb2Original; private javax.swing.JCheckBox ckb3Imitacion; private javax.swing.JCheckBox ckb3Original; private javax.swing.JComboBox cmbImitacion; private javax.swing.JComboBox cmbOriginal; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JRadioButton rdb1Imitacion; private javax.swing.JRadioButton rdb1Original; private javax.swing.JRadioButton rdb2Imitacion; private javax.swing.JRadioButton rdb2Original; private javax.swing.JRadioButton rdb3Imitacion; private javax.swing.JRadioButton rdb3Original; private javax.swing.JSpinner spnImitacion; private javax.swing.JSpinner spnOriginal; private javax.swing.JTextField txtImitacion; private javax.swing.JTextField txtOriginal; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
6) Crea una aplicación donde pueda mostrar la ruta de un fichero que seleccionemos. Simplemente es un JFrame con un JTextField y un botón. Donde al pulsar el botón, aparecerá una ventana donde se listan los ficheros (JFileChooser) y al elegir un fichero txt (solo ficheros txt) en el JTextField aparecerá la ruta completa del fichero.
Spoiler Inside | SelectShow> |
---|---|
import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /** * @author DiscoDurodeRoer */ public class RutaArchivoApp extends javax.swing.JFrame { /** * Creates new form RutaArchivoApp */ public RutaArchivoApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { txtRuta = new javax.swing.JTextField(); btnElegir = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Mostrar ruta fichero"); txtRuta.setEditable(false); btnElegir.setText("..."); btnElegir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnElegirActionPerformed(evt); } }); jLabel1.setText("Pulsa en el botón y elige una ruta"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(43, 43, 43) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnElegir))) .addContainerGap(31, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(49, 49, 49) .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnElegir)) .addContainerGap(44, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btnElegirActionPerformed(java.awt.event.ActionEvent evt) { //Creamos una instancia de JFileChooser JFileChooser fc=new JFileChooser(); //Escribimos el nombre del titulo fc.setDialogTitle("Elige un fichero"); //Indicamos que solo se puedan elegir ficheros fc.setFileSelectionMode(JFileChooser.FILES_ONLY); //Creamos un filtro para JFileChooser FileNameExtensionFilter filtro = new FileNameExtensionFilter("*.txt", "txt"); fc.setFileFilter(filtro); int eleccion=fc.showSaveDialog(this); if(eleccion==JFileChooser.APPROVE_OPTION){ txtRuta.setText(fc.getSelectedFile().getPath()); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RutaArchivoApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnElegir; private javax.swing.JLabel jLabel1; private javax.swing.JTextField txtRuta; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
7) Modifica el ejercicio anterior, haciendo que en lugar de usar el botón para abrir el dialogo de archivos, usemos una de las opciones del menú, que se llamará abrir. También habra una opción que se llamará Salir, que cerrará el programa.
Spoiler Inside | SelectShow> |
---|---|
import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /** * @author DiscoDurodeRoer */ public class MenuApp extends javax.swing.JFrame { public MenuApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { txtRuta = new javax.swing.JTextField(); jMenuBar1 = new javax.swing.JMenuBar(); miSalir = new javax.swing.JMenu(); miAbrir = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Menu"); txtRuta.setEditable(false); miSalir.setText("File"); miAbrir.setText("Abrir..."); miAbrir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miAbrirActionPerformed(evt); } }); miSalir.add(miAbrir); jMenuItem3.setText("Salir"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); miSalir.add(jMenuItem3); jMenuBar1.add(miSalir); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(57, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(80, 80, 80) .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(77, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); } private void miAbrirActionPerformed(java.awt.event.ActionEvent evt) { //Creamos una instancia de JFileChooser JFileChooser fc=new JFileChooser(); //Escribimos el nombre del titulo fc.setDialogTitle("Elige un fichero"); //Indicamos que solo se puedan elegir ficheros fc.setFileSelectionMode(JFileChooser.FILES_ONLY); //Creamos un filtro para JFileChooser FileNameExtensionFilter filtro = new FileNameExtensionFilter("*.txt", "txt"); fc.setFileFilter(filtro); int eleccion=fc.showSaveDialog(this); if(eleccion==JFileChooser.APPROVE_OPTION){ txtRuta.setText(fc.getSelectedFile().getPath()); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuApp().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem miAbrir; private javax.swing.JMenu miSalir; private javax.swing.JTextField txtRuta; // End of variables declaration } Pincha aquí para descargar el proyecto. Importalo en tu NetBeans. |
Espero que os sea de ayuda. Si tenéis dudas, preguntad, estamos para ayudarte.
hola buenos ejercicios, solo una cosa en el ejercicio numero 4 (Generador de Numeros), no se si no se explicaron bien o no comprendi bien lo que se queria lograr ya que de a cuerdo al enunciado comprendi una cosa y en la estructura del codigo comprendi otra saludos :)
Exelente, me ha sido de mucha ayuda. Gracias
Muy buenos ejercicios para practicar, me gustaría seguir viendo información de este tipo.
muy buen ejercicio … me sirvió mucho y desearía mas ejercicios como este …
me fue de mucha ayuda muchas gracias espero seguir contando con vuestro apoyo
Gracias . Estos ejemplos me han ayudado mucho
El ejercicio 4 tira error
hola desearia poder tener muchos ejercicios de netbeans , todos los que se pudieran, desde el mas sencillo al mas complejo pero paso a paso, con texto e imagenes explicativas .
se lo agradecere
Aqui te dejo una lista de reproducción de youtube.
https://www.youtube.com/watch?v=inKumOh1QUw&list=PLaxZkGlLWHGXs8cv0EhPJHA1g6O2PFaZ4
Hola que tal a todos, les pido por favor que me ayuden hacer un programa en java netbeans que sirva para como programa para un hospital en donde le pida datos y que los guarde en una tabla