Tarea de Programación II Con Interfaces Graficas
Tarea de Programación II Con Interfaces Graficas
2-21-0505.
Tarea de Programación II
package com.mycompany.peliculas;
/**
* Creates new form ventana
*/
public ventana() {
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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTpelicula.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTpeliculaActionPerformed(evt);
}
});
jButton1.setText("Añadir");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("peliculas");
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jButton1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCPeliculas, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(58, 58, 58))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jTpelicula, javax.swing.GroupLayout.PREFERRED_SIZE, 129,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(jLabel2)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTpelicula, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jCPeliculas, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(146, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @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(ventana.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ventana().setVisible(true);
}
});
}
2- Crea una mini encuesta 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, le recomiendo usar un JLabel, que le diga qué valor tiene el slider, usad el
eventostateChanged.
package com.mycompany.nn;
public class Ejercicio_2 {
public JLabel lblNewLabel_3;
private JFrame frmMiniEncuesta;
private final ButtonGroup buttonGroup = new ButtonGroup();
private final ButtonGroup buttonGroup_1 = new ButtonGroup();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ejercicio_3 window = new Ejercicio_3();
window.frmMiniEncuesta.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Ejercicio_2() {
initialize();
}
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* 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() {
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);
}
});
.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.LE
ADING)
.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>
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.Le
vel.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RutaArchivoApp.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
}
//</editor-fold>
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
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() {
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);
pack();
}// </editor-fold>
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>
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class Ejemplo {
public Ejemplo() {
JFrame frame = new JFrame("Ejemplo");
JPanel contentPane = (JPanel) frame.getContentPane();
JPanel panel = new JPanel();
JButton button = new JButton("Botón");
panel.add(button);
contentPane.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,100);
frame.setVisible(true);
}
}
Corrida
Aceptar
Perro
Gato Ratón
CORRIDA
9-Realice un nuevo proyecto.
1- En la ventana principal debes añadir lo siguiente:
a) Un botón “Aceptar” llamado btnAceptar
b) Una etiqueta con borde llamado etiResultado
c) Añada un panel. Un panel es una zona rectangular que puede contener
elementos (botones, etiquetas, etc,)
d) Una vez añadido el panel en el JFrame, le pondremos un borde para poder
localizarlo fácilmente. Debes hacer lo siguiente:
1- Selecciona el panel que has añadido
2- Activa la propiedad Border (Boton de tres puntos)
3- Busca el tipo de borde llamado TitledBorder (Borde con titulo) y pon el
titulo en colores.
4- Ahora debes añadir tres botones de opción (Botones de radio) dentro del
panel. Estos botones son objetos del tipo JRadioButton.
5- Añade tres JRadioButton y Cambia el texto de ellos, de forma que
aparezca “Verde”, “Azul” y “Rojo”.
6- Debes cambiar el nombre de cada uno de ellos. Se llamarán : optVerde,
OptAzul y OptRojo.
2- Si ejecuta el programa te dará cuenta que puede seleccionar varios colores a la vez,
pero los botones de opción se usan para activar solo una opción a la vez entre
varias. Por lo tanto añada un objeto del tipo ButtonGroup al formulario y llamale
grupocolores. Asocia las variables al contenedor el objeto creado con el método add.
Ejemplo grupocolores.add(optVerde) y asi para las demás variables.
3- Queremos que la opción Verde salga activada desde el principio. Una forma de
hacerlo en programando en el “Constructor” el siguiente comando:
optVerde.setSelected(True); // hay otras formas de activarlo
4- Ahora programa el botón “Aceptar” y en la etiqueta aparezca el color elegido.
5- Añada un botón llamado “Salir” que permita salir sin seleccionar ningún tipo de
opciones.
corrida