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
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
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") // 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(); }// 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 */ // /* 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); } // /* 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.
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
/** * @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") // 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(); }// 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 */ // /* 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); } // /* 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.
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
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") // 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(); }// 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 */ // /* 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); } // /* 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.
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
/** * @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") // 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(); }// 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 */ // /* 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); } // /* 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.
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
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") // 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(); }// 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 */ // /* 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); } // /* 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.
|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
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") // 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(); }// 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 */ // /* 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); } // /* 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.

|
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
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") // 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(); }// 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 */ // /* 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); } // /* 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! Primero, gracias por estos ejercicios, están buenos para hacer cada tanto y refrescar conceptos. Sin embargo, soy el único que cree que varias de las soluciones son innecesariamente complejas y pueden lograrse con mucho menos código? Saludos y gracias nuevamente!
buenas tardes quisiera saber como solucionar este ejercicio ya que soy aprendiz y no tengo el conocimiento total en net bean
tengo que hacer este ejercicio Se tiene el siguiente arreglo de 20 nombres de atletas de Maratón y de los tiempos que usaron en la maratón. Los tiempos de los 20 atletas son aleatorios entre 150 y 200 minutos. Sacar por pantalla, por línea el nombre del atleta ganador y el nombre del atleta que quedo de último y su tiempo.
ejemplo nombre tiempo puesto
juean 150 1primero
carlos 160 4
andres 180 20 ultimo
Que mierda de programas, uno copia esa chimbadas y ni corren. Hagan bien eso malpardas:D
https://mega.nz/file/g1tClJxQ#SenNvhS8GqU9IgTdUKxOMjvL_f-Av8BxJYg4z5ATXAQ
alguno que pueda ayudarme con este ejercicio por favor:
Hola bunas es que me mandaron este taller y la verdad estoy perdido si me pueden ayudar seria muy amable :)
Hacer una aplicación con interfaz gráfica para gestionar una tienda de electrónica:
● En la interfaz debe aparecer un JTextArea donde se verá en todo momento el estado actual de la compra de un usuario
● Un usuario podrá seleccionar un producto de una lista desplegable
● Después de seleccionar un producto(cada producto tiene un nombre y un costo por unidad), debe aparecer un campo de texto donde se puedan seleccionar el número de unidades que el cliente desea comprar
● Cada vez que se añade un producto, este mismo y su número de unidades aparecerá en el JTextArea en conjunto con los productos que previamente se hayan seleccionado
● Debe existir un botón para generar factura, donde lo que activa es un evento donde el JTextArea además de la información que ya tenía, aparezca al final el costo total de todos los productos
● Deben generarse excepciones para malos numero de unidades (como números negativos, o que ingrese no números, etc.) con un mensaje personalizado
muy bueno el contenido
Como cuando eres pibe, los pibes.