[go: up one dir, main page]

0% found this document useful (0 votes)
70 views30 pages

Tarea de Programación II Con Interfaces Graficas

The document describes creating a simple movie list application with a text field to add movies to a drop-down list and a mini survey application with radio buttons to select an operating system, checkboxes to select areas of study, and a slider to select hours spent on a computer with a label to display the slider value. It provides code snippets for the user interfaces and event handling for both applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views30 pages

Tarea de Programación II Con Interfaces Graficas

The document describes creating a simple movie list application with a text field to add movies to a drop-down list and a mini survey application with radio buttons to select an operating system, checkboxes to select areas of study, and a slider to select hours spent on a computer with a label to display the slider value. It provides code snippets for the user interfaces and event handling for both applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Ronald Rodríguez.

2-21-0505.

Tarea de Programación II

1- Crea una simple lista de películas. tendremos un JComboBox, donde


almacenaremos las películas, que vayamos almacenando en un campo de texto. Al
pulsar el botón Añadir la película que hayamos metido, se introducirá en el
JComboBox.

package com.mycompany.peliculas;

public class ventana extends javax.swing.JFrame {

/**
* 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() {

jLabel1 = new javax.swing.JLabel();


jTpelicula = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jCPeliculas = new javax.swing.JComboBox<>();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Escribe una pelicula");

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");

jCPeliculas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item


1", "Item 2", "Item 3", "Item 4" }));
jCPeliculas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCPeliculasActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayo
ut.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()

.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>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


jCPeliculas.addItem(jTpelicula.getText());
jTpelicula.setText("");
}

private void jCPeliculasActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
}

private void jTpeliculaActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
}

/**
* @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);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jCPeliculas;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTpelicula;
// End of variables declaration

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();
}

private void initialize() {


frmMiniEncuesta = new JFrame();
frmMiniEncuesta.setTitle("Mini Encuesta");
frmMiniEncuesta.setBounds(100, 100, 229, 480);
frmMiniEncuesta.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMiniEncuesta.setLocationRelativeTo(null);
JPanel panel = new JPanel();
frmMiniEncuesta.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Elige un sistema
operativo"); lblNewLabel.setBounds(10, 27, 180, 14);
panel.add(lblNewLabel);
JRadioButton Radio1 = new JRadioButton("Windows");
buttonGroup.add(Radio1);
Radio1.setBounds(20, 48, 109, 23);
panel.add(Radio1);
JRadioButton Radio2 = new JRadioButton("Linux");
buttonGroup.add(Radio2);
Radio2.setBounds(20, 71, 109, 23);
panel.add(Radio2);
JRadioButton Radio3 = new JRadioButton("Mac");
buttonGroup.add(Radio3);
Radio3.setBounds(20, 97, 109, 23);
panel.add(Radio3);
JSeparator separator = new JSeparator();
separator.setBounds(10, 132, 180, 2);
panel.add(separator);
JLabel lblNewLabel_1 = new JLabel("Elige tu
especialidad"); lblNewLabel_1.setBounds(10, 155, 135, 14);
panel.add(lblNewLabel_1);
JCheckBox Check1 = new JCheckBox("Programaci\u00F3n");
Check1.setBounds(20, 182, 170, 23);
panel.add(Check1);
JCheckBox Check2 = new JCheckBox("Dise\u00F1o gr\u00E1fico");
Check2.setBounds(20, 208, 170, 23);
panel.add(Check2);
JCheckBox Check3 = new JCheckBox("Adimistraci\u00F3n");
Check3.setBounds(20, 234, 170, 23);
panel.add(Check3);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(10, 285, 180, 2);
panel.add(separator_1);
JLabel lblNewLabel_2 = new JLabel("Horas dedicadas en el ordenador");
lblNewLabel_2.setBounds(10, 308, 214, 14);
panel.add(lblNewLabel_2);
JSlider slider = new JSlider();
slider.setMaximum(24);
slider.setMinimum(1);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lblNewLabel_3.setText(String.valueOf(slider.getValue()));
}
});
slider.setBounds(35, 347, 155, 26);
panel.add(slider);
JButton btnNewButton = new JButton("Generar");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JRadioButton[] rad = {Radio1, Radio2, Radio3};
JCheckBox[] check = {Check1, Check2, Check3};
String info = "Tu sistema operativo favorito es: ";
for (int i = 0; i <rad.length; i++) {
if(rad[i].isSelected()) {
info+= rad[i].getText() + ". ";
}
}
info += "Tus especialidad es: ";
for (int i = 0; i <check.length; i++) {
if(check[i].isSelected()) {
info+= check[i].getText() + " ";
}
}
info += ". Numero de horas dedicadas al ordenador: " +
slider.getValue();
JOptionPane.showMessageDialog(panel,info, "Resultado",
JOptionPane.INFORMATION_MESSAGE);
}
});
btnNewButton.setBounds(56, 394, 89, 23);
panel.add(btnNewButton);
lblNewLabel_3 = new JLabel("0");
lblNewLabel_3.setBounds(20, 347, 23, 14);
panel.add(lblNewLabel_3);
}
}
3- 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.
public class WindowsForm2 {
public JSpinner spinner, spinner_1;
private JFrame frmGeneradorDeNmeros;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindowsForm2 window = new WindowsForm2();
window.frmGeneradorDeNmeros.setVisible(true);
} catch (Exception e)
{ e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WindowsForm2() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmGeneradorDeNmeros = new JFrame();
frmGeneradorDeNmeros.setTitle("Generador de n\u00FAmeros");
frmGeneradorDeNmeros.setBounds(100, 100, 300, 300);
frmGeneradorDeNmeros.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frmGeneradorDeNmeros.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Numero 1");
lblNewLabel.setBounds(42, 51, 46, 14);
panel.add(lblNewLabel);
spinner = new JSpinner();
spinner.setBounds(138, 48, 63, 20);
panel.add(spinner);
JLabel lblNewLabel_1 = new JLabel("Numero 2");
lblNewLabel_1.setBounds(42, 100, 46, 14);
panel.add(lblNewLabel_1);
spinner_1 = new JSpinner();
spinner_1.setBounds(138, 97, 63, 20);
panel.add(spinner_1);
JLabel lblNewLabel_2 = new JLabel("Numero generado");
lblNewLabel_2.setBounds(42, 150, 100, 14);
panel.add(lblNewLabel_2);
textField = new JTextField();
textField.setEditable(false);
textField.setBounds(138, 147, 79, 20);
panel.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Generar");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n1 = (int)spinner.getValue();
int n2 = (int)spinner_1.getValue();
int n3 = (int) Math.floor(Math.random() * (n2 - n1 + 1) + (n1));
textField.setText(n3+"");
}
});
btnNewButton.setBounds(83, 212, 89, 23);
panel.add(btnNewButton);
}
}
4- 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
seleccionamos 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 essu reflejo también recibirá ese texto.

Puedes usar los elementos que quieras, le recomiendo: JTextField,


JRadioButton,JCheckBox, JTextArea, JSpinner, etc.

Observa los eventos, serán útiles.

Solo puedes modificar de un lado, el otro conjunto no lo puedes modificar, es


decir,que no es bidireccional.
ublic class MainJframe {
private JFrame frmImitador;
private JTextField textField;
private JTextField textField_1;
public JRadioButton rdbtnNewRadioButton_3, rdbtnNewRadioButton_1_1,
rdbtnNewRadioButton_2_1;
public JSpinner spinner_1;
public JComboBox comboBox_1;
public JCheckBox chckbxNewCheckBox, chckbxNewCheckBox_1,
chckbxNewCheckBox_2,
chckbxNewCheckBox_3, chckbxNewCheckBox_1_1, chckbxNewCheckBox_2_1;
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 {
MainJframe window = new MainJframe();
window.frmImitador.setVisible(true);
} catch (Exception e)
{ e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainJframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmImitador = new JFrame();
frmImitador.setTitle("Imitador");
frmImitador.setBounds(100, 100, 300, 335);
frmImitador.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmImitador.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.setBounds(10, 11, 264, 134);
frmImitador.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Original");
lblNewLabel.setBounds(0, 0, 46, 14);
panel.add(lblNewLabel);
JRadioButton rdbtnNewRadioButton = new JRadioButton("Opcion
1"); rdbtnNewRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnNewRadioButton.isSelected()) {
rdbtnNewRadioButton_3.setSelected(true);
rdbtnNewRadioButton_1_1.setSelected(false);
rdbtnNewRadioButton_2_1.setSelected(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setBounds(10, 21, 75, 23);
panel.add(rdbtnNewRadioButton);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("Opcion 2");
rdbtnNewRadioButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnNewRadioButton_1.isSelected()) {
rdbtnNewRadioButton_3.setSelected(false);
rdbtnNewRadioButton_1_1.setSelected(true);
rdbtnNewRadioButton_2_1.setSelected(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_1);
rdbtnNewRadioButton_1.setBounds(10, 47, 75, 23);
panel.add(rdbtnNewRadioButton_1);
JRadioButton rdbtnNewRadioButton_2 = new JRadioButton("Opcion 3");
rdbtnNewRadioButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnNewRadioButton_2.isSelected()) {
rdbtnNewRadioButton_3.setSelected(false);
rdbtnNewRadioButton_1_1.setSelected(false);
rdbtnNewRadioButton_2_1.setSelected(true);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_2);
rdbtnNewRadioButton_2.setBounds(10, 73, 75, 23);
panel.add(rdbtnNewRadioButton_2);
chckbxNewCheckBox = new JCheckBox("Opcion 4");
chckbxNewCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (chckbxNewCheckBox.isSelected()) {
chckbxNewCheckBox_3.setSelected(true);
chckbxNewCheckBox_1_1.setSelected(false);
chckbxNewCheckBox_2_1.setSelected(false);
chckbxNewCheckBox.setSelected(true);
chckbxNewCheckBox_1.setSelected(false);
chckbxNewCheckBox_2.setSelected(false);
}
}
});
chckbxNewCheckBox.setBounds(87, 21, 75, 23);
panel.add(chckbxNewCheckBox);
chckbxNewCheckBox_1 = new JCheckBox("Opcion 5");
chckbxNewCheckBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (chckbxNewCheckBox_1.isSelected()) {
chckbxNewCheckBox_3.setSelected(false);
chckbxNewCheckBox_1_1.setSelected(true);
chckbxNewCheckBox_2_1.setSelected(false);
chckbxNewCheckBox.setSelected(false);
chckbxNewCheckBox_1.setSelected(true);
chckbxNewCheckBox_2.setSelected(false);
}
}
});
chckbxNewCheckBox_1.setBounds(87, 47, 75, 23);
panel.add(chckbxNewCheckBox_1);
chckbxNewCheckBox_2 = new JCheckBox("Opcion 6");
chckbxNewCheckBox_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (chckbxNewCheckBox_2.isSelected()) {
chckbxNewCheckBox_3.setSelected(false);
chckbxNewCheckBox_1_1.setSelected(false);
chckbxNewCheckBox_2_1.setSelected(true);
chckbxNewCheckBox.setSelected(false);
chckbxNewCheckBox_1.setSelected(false);
chckbxNewCheckBox_2.setSelected(true);
}
}
});
chckbxNewCheckBox_2.setBounds(87, 73, 75, 23);
panel.add(chckbxNewCheckBox_2);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
textField_1.setText(textField.getText());
}
});
textField.setBounds(168, 22, 86, 20);
panel.add(textField);
textField.setColumns(10);
JComboBox comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
comboBox_1.setSelectedIndex(comboBox.getSelectedIndex());
}
});
comboBox .setModel( new DefaultComboBoxModel( new String[] { "Item1" ,
"Item2" ,
"Item3" }));
comboBox.setMaximumRowCount(3);
comboBox.setToolTipText("Item 1");
comboBox.setBounds(168, 53, 86, 22);
panel.add(comboBox);
JSpinner spinner = new JSpinner();
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
spinner_1.setValue((Integer)spinner.getValue());
}
});
spinner.setModel(new SpinnerNumberModel(1, 1, 20, 1));
spinner.setBounds(168, 86, 86, 20);
panel.add(spinner);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null,
null));
panel_1.setLayout(null);
panel_1.setBounds(10, 151, 264, 134);
frmImitador.getContentPane().add(panel_1);
JLabel lblImitador = new JLabel("Espejo");
lblImitador.setBounds(0, 0, 46, 14);
panel_1.add(lblImitador);
rdbtnNewRadioButton_3 = new JRadioButton("Opcion 1");
buttonGroup_1.add(rdbtnNewRadioButton_3);
rdbtnNewRadioButton_3.setEnabled(false);
rdbtnNewRadioButton_3.setBounds(10, 21, 75, 23);
panel_1.add(rdbtnNewRadioButton_3);
rdbtnNewRadioButton_1_1 = new JRadioButton("Opcion 2");
buttonGroup_1.add(rdbtnNewRadioButton_1_1);
rdbtnNewRadioButton_1_1.setEnabled(false);
rdbtnNewRadioButton_1_1.setBounds(10, 47, 75, 23);
panel_1.add(rdbtnNewRadioButton_1_1);
rdbtnNewRadioButton_2_1 = new JRadioButton("Opcion 3");
buttonGroup_1.add(rdbtnNewRadioButton_2_1);
rdbtnNewRadioButton_2_1.setEnabled(false);
rdbtnNewRadioButton_2_1.setBounds(10, 73, 75, 23);
panel_1.add(rdbtnNewRadioButton_2_1);
chckbxNewCheckBox_3 = new JCheckBox("Opcion 4");
chckbxNewCheckBox_3.setEnabled(false);
chckbxNewCheckBox_3.setBounds(87, 21, 75, 23);
panel_1.add(chckbxNewCheckBox_3);
chckbxNewCheckBox_1_1 = new JCheckBox("Opcion 5");
chckbxNewCheckBox_1_1.setEnabled(false);
chckbxNewCheckBox_1_1.setBounds(87, 47, 75, 23);
panel_1.add(chckbxNewCheckBox_1_1);
chckbxNewCheckBox_2_1 = new JCheckBox("Opcion 6");
chckbxNewCheckBox_2_1.setEnabled(false);
chckbxNewCheckBox_2_1.setBounds(87, 73, 75, 23);
panel_1.add(chckbxNewCheckBox_2_1);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setEnabled(false);
textField_1.setColumns(10);
textField_1.setBounds(168, 22, 86, 20);
panel_1.add(textField_1);
comboBox_1 = new JComboBox();
comboBox_1 .setModel( new DefaultComboBoxModel( new String[] { "Item1" ,
"Item2" ,
"Item3" }));
comboBox_1.setEnabled(false);
comboBox_1.setToolTipText("Item 1");
comboBox_1.setMaximumRowCount(3);
comboBox_1.setBounds(168, 53, 86, 22);
panel_1.add(comboBox_1);
spinner_1 = new JSpinner();
spinner_1.setModel(new SpinnerNumberModel(new Integer (1), null, null, new
Integer (1)));
spinner_1.setEnabled(false);
spinner_1.setBounds(168, 86, 86, 20);
panel_1.add(spinner_1);
}
}
5- Crea una aplicación donde pueda mostrar la ruta de un archivo o 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 archivos o ficheros
(JFileChooser) y al elegir un archivo o fichero txt (solo archivos o ficheros txt) en
el JTextField aparecerá la ruta completa del fichero.

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

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.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>

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.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>

/* 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
}
6- 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 habrá una opción que se llamará Salir, que cerrará el programa.

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

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.LEA
DING)
.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.LEADI
NG)
.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
}
7- Implementa el código que permite generar la siguiente interfaz gráfica. No
olvides importar las clases necesarias y hacer visible la ventana. El programa
debe finalizar al cerrar la ventana. Utiliza JPasswordField para el campo de
texto del password

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

8-Realice un nuevo proyecto.


a) En la Ventana principal debes añadir lo siguiente:
1- Un botón “Aceptar” llamado BotonAceptar. 2-
Una etiqueta llamado EtiResultado
3- Añada también tres cuadros de verificación. Estos cuadros son objetos del
tipo JCheckBox. Cambiele el texto de ellos de forma que aparezca “Perro”,
“Gato” y “Raton”.
4- Debes cambiar el nombre de cada uno de ellos. Se pueden llamar chkPerro,
ChkGato y ChkRaton.
5- La ventana tendrá el siguiente aspecto cuando termine:

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

You might also like