LAB. 13 - Programación gráfica Programas básicos en Java - EJERCICIOS PRACTICOS PDF

Title LAB. 13 - Programación gráfica Programas básicos en Java - EJERCICIOS PRACTICOS
Course Programación
Institution Universidad del Norte Mexico
Pages 10
File Size 140.4 KB
File Type PDF
Total Downloads 74
Total Views 148

Summary

Programación de objetos practica - LABORATORIO PROGRAMACION DE OBJETOS - LABORATORIO PROGRAMACION DE OBJETOS - LABORATORIO PROGRAMACION DE OBJETOS - LABORATORIO PROGRAMACION DE OBJETOS - LABORATORIO PROGRAMACION DE OBJETOS...


Description

LAB. PROGRAMACION ORIENTADO A OBJETOS

SEMANA 13

UNMSM – FIEE EAP ING. TELECOMUNICACIONES

PROGRAMACION GRAFICA EN JAVA

I. OBJETIVOS Desarrollar programas básicos en Java empleado las librerías gráficas de Java: AWT para eventos y Swing para componentes. II. PROCEDIMIENTO I – CREACION DE UN PROYECTO DE APLICACIÓN JAVA EN NETBEANS Crear un proyecto Java en Netbeans Ubicarla en una carpeta especial para proyectos Java. Crear y dar nombre a la carpeta del proyecto (Semana_13). III –EJERCICIOS Analizar/completar/comentar los códigos mostrados para los casos planteados.

A Ejemplos de aplicación de los gestores de diseño (Layout Managers) Analizar el funcionamiento de los distintos organizadores de layout disponibles en Java. package javaapplication190_borderlayout; import javax.swing.*; import java.awt.*; class MarcoBorder extends JFrame { static int ANCHO = 275; static int ALTO = 200; public MarcoBorder() { super("Mi marco"); //SwingConstants.alineacion //add (Component c, int zona) add(new JLabel("Norte", SwingConstants.LEFT), BorderLayout.NORTH); add(new JLabel("Sur", SwingConstants.CENTER), BorderLayout.SOUTH); add(new JLabel("Centro", SwingConstants.CENTER), BorderLayout.CENTER); add(new JLabel("Oeste", SwingConstants.CENTER), BorderLayout.WEST); add(new JLabel("Este", SwingConstants.CENTER), BorderLayout.EAST); setSize(ANCHO,ALTO); setVisible(true); } } package javaapplication191_flowlayout; import javax.swing.*; import java.awt.*; public class JavaApplication191_FlowLayout { public static void main(String[] args) { MarcoFlow miMarco = new MarcoFlow(); miMarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

LAB. PROGRAMACION ORIENTADO A OBJETOS

class MarcoFlow extends JFrame { static int ANCHO = 225; static int ALTO = 200; public MarcoFlow() { super("Mi marco"); setLayout(new FlowLayout()); add(new JLabel("Primera")); add(new JLabel("Segunda")); add(new JLabel("Tercera")); add(new JLabel("Cuarta")); add(new JLabel("Quinta")); add(new JLabel("Sexta")); setSize(ANCHO,ALTO); setVisible(true); } } package javaapplication192_gridlayout; import javax.swing.*; import java.awt.*; public class JavaApplication192_GridLayout { public static void main(String[] args) { MarcoGrid miMarco = new MarcoGrid(); miMarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class MarcoGrid extends JFrame { static int ANCHO = 275; static int ALTO = 200; public MarcoGrid() { super("Mi marco"); setLayout(new GridLayout(3,2,15,15)); add(new JLabel("Primera")); add(new JLabel("Segunda")); add(new JLabel("Tercera")); add(new JLabel("Cuarta")); add(new JLabel("Quinta")); add(new JLabel("Sexta")); setSize(ANCHO,ALTO); setVisible(true); } } package javaapplication193_boxlayout; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class JavaApplication193_BoxLayout { public static void main(String[] args) { MarcoBox miMarco = new MarcoBox(); miMarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS class MarcoBox extends JFrame { static int ANCHO = 275; static int ALTO = 250; public MarcoBox() { super("Mi marco"); JPanel panel = new JPanel() ; panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(new JLabel("Primera")); panel.add(new JLabel("Segunda")); panel.add(new JLabel("Tercera")); panel.add(new JLabel("Cuarta")); panel.add(new JLabel("Quinta")); panel.add(new JLabel("Sexta")); add(panel); setSize(ANCHO,ALTO); setVisible(true); } } package javaapplication194_box; import javax.swing.*; import java.awt.*; public class JavaApplication194_Box { public static void main(String[] args) { Marco2Box miMarco = new Marco2Box(); miMarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class Marco2Box extends JFrame { static int ANCHO = 375; static int ALTO = 275; public Marco2Box() { super("Mi marco"); JButton b1 = new JButton("Boton 1"); JButton b2 = new JButton("Boton 2"); JButton b3 = new JButton("Boton 3"); JButton b4 = new JButton("Boton 4"); JButton b5 = new JButton("Boton 5"); JButton b6 = new JButton("Boton 6"); Box cajaH = Box.createHorizontalBox(); // método factoría cajaH.add(b1); // separación horizontal de 10 pixeles cajaH.add(Box.createHorizontalStrut(10)); cajaH.add(b2); cajaH.add(Box.createHorizontalStrut(10)); cajaH.add(b3); add(cajaH,BorderLayout.NORTH); Box cajaV = Box.createVerticalBox(); cajaV.add(Box.createHorizontalStrut(70)); cajaV.add(b4); // separación horizontal 10 pixeles cajaV.add(Box.createVerticalStrut(10)); cajaV.add(b5); cajaV.add(Box.createVerticalStrut(10)); cajaV.add(b6); add(cajaV,BorderLayout.CENTER); setSize(ANCHO,ALTO); setVisible(true);

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS

SEMANA 13

} }

B Eventos con botones de comando Analizar/completar el siguiente código para procesar eventos mediante botones de comandos. package javaapplication198_manejoeventos; import java.awt.*; import java.awt.event.*; import javax.swing.*; //Manejo de eventos en Swing class JavaApplication198_ManejoEventos { JLabel jlab; JavaApplication198_ManejoEventos() //CONSTRUCTOR { // Create a new JFrame container JFrame jfrm = new JFrame("An Event Example"); // Specify FlowLayout for the layout manager jfrm.setLayout(new FlowLayout()); // Give the frame an initial size jfrm.setSize(320, 190); jfrm.setBounds(500, 500, 320, 100); // Terminate the program when the user closes the application jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make two buttons JButton jbtnAlpha = new JButton("Alpha"); JButton jbtnBeta = new JButton("Beta"); // Add action listener for Alpha jbtnAlpha.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) jlab.setText("Alpha was pressed."); } }); // Add action listener for Beta ActionListener alBeta = new ActionListener() { public void actionPerformed(ActionEvent evento) jlab.setText("Beta was pressed."); } }; jbtnBeta.addActionListener(alBeta); // Add the buttons to the content pane jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta); // Create a text-based label jlab = new JLabel("Press a button."); // Add the label to the content pane. jfrm.add(jlab); // Display the frame. jfrm.setVisible(true); } public static void main(String args[]) { // Create the frame on the event dispatching thread SwingUtilities.invokeLater(new Runnable()

{

{

LAB. PROGRAMACION ORIENTADO A OBJETOS

SEMANA 13

{ public void run() { new JavaApplication198_ManejoEventos();

C Manejo de eventos mediante menús Analizar/completar el siguiente código para procesar eventos mediante una barra de menús. package javaapplication202_mainmenu; import java.awt.*; import java.awt.event.*; import javax.swing.*; class JavaApplication202_MainMenu implements ActionListener { //La clase implementa el método actionPerformed() JLabel jlab; //La clase se comportan, también, como listener JavaApplication202_MainMenu() { JFrame jfrm = new JFrame("Menu Demo"); jfrm.setLayout(new FlowLayout()); //jfrm.setSize(320, 200); jfrm.setBounds(500, 500, 320, 200); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jlab = new JLabel(); JMenuBar jmb = new JMenuBar(); JMenu jmFile = new JMenu("File"); JMenuItem jmiOpen = new JMenuItem("Open"); JMenuItem jmiClose = new JMenuItem("Close"); JMenuItem jmiSave = new JMenuItem("Save"); JMenuItem jmiExit = new JMenuItem("Exit"); jmFile.add(jmiOpen); jmFile.add(jmiClose); jmFile.add(jmiSave); jmFile.addSeparator(); jmFile.add(jmiExit); jmb.add(jmFile); JMenu jmOptions = new JMenu("Options"); JMenu jmColors = new JMenu("Colors"); JMenuItem jmiRed = new JMenuItem("Red"); JMenuItem jmiGreen = new JMenuItem("Green"); JMenuItem jmiBlue = new JMenuItem("Blue"); jmColors.add(jmiRed); jmColors.add(jmiGreen); jmColors.add(jmiBlue); jmOptions.add(jmColors); JMenu jmPriority = new JMenu("Priority"); JMenuItem jmiHigh = new JMenuItem("High"); JMenuItem jmiLow = new JMenuItem("Low"); jmPriority.add(jmiHigh); jmPriority.add(jmiLow); jmOptions.add(jmPriority); jmOptions.addSeparator(); JMenuItem jmiReset = new JMenuItem("Reset"); jmOptions.add(jmiReset); // Add the entire options menu to the menu bar jmb.add(jmOptions); JMenu jmHelp = new JMenu("Help"); JMenuItem jmiAbout = new JMenuItem("About"); jmHelp.add(jmiAbout); jmb.add(jmHelp); //Añade ActionListener para cada item de menú

LAB. PROGRAMACION ORIENTADO A OBJETOS jmiOpen.addActionListener(this); //La clase es el listener (this) jmiClose.addActionListener(this); jmiSave.addActionListener(this); jmiExit.addActionListener(this); jmiRed.addActionListener(this); jmiGreen.addActionListener(this); jmiBlue.addActionListener(this); jmiHigh.addActionListener(this); jmiLow.addActionListener(this); jmiReset.addActionListener(this); jmiAbout.addActionListener(this); jfrm.add(jlab); jfrm.setJMenuBar(jmb); jfrm.setVisible(true); } // Handle menu item action events. public void actionPerformed(ActionEvent ae) { String comStr = ae.getActionCommand(); if(comStr.equals("Exit")) System.exit(0); jlab.setText(comStr + " Selected"); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new JavaApplication202_MainMenu(); } }); } }

D Programa de ejemplo con distintos elementos gráficos y eventos Analizar el código para el procesamiento de eventos diversos. package application65; import java.awt.EventQueue; import javax.swing.*; import java.awt.event.*; public class Application65 extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JComboBox comboBox; private JRadioButton rdbtnOpcion_1; private JRadioButton rdbtnOpcion_2; private JRadioButton rdbtnOpcion_3; private JLabel lblEstasSobreLa; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Application65 frame = new Application65();

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Application65() { //Añade un titulo, no es estrictamente necesario setTitle("Titulo de la ventana"); // * Coordenadas x y de la aplicacion y su altura y longitud, setBounds(400, 200, 655, 520); //Cuando se cierre la ventana se acaba la aplicacion, //Si no se indica, cuando cerremos la ventana la aplicacion seguira funcionando setDefaultCloseOperation(EXIT_ON_CLOSE); //Hace visible la ventana, si no lo hacemos no veremos la aplicacion setVisible(true); contentPane =new JPanel(); //Creamos el panel contentPane.setLayout(null); //Indicamos su diseño setContentPane(contentPane); //Asigna el pannel a la ventana //Componentes //Etiquetas JLabel lblEscribeElNombre = new JLabel("Escribe el nombre de una persona sin digitos"); lblEscribeElNombre.setBounds(369, 32, 229, 25); contentPane.add(lblEscribeElNombre); JLabel lblEligeUnaOpcin = new JLabel("Elige una opci\u00F3n:"); lblEligeUnaOpcin.setBounds(176, 32, 109, 14); contentPane.add(lblEligeUnaOpcin); JLabel lblPulsaElBoton = new JLabel("Pulsa el boton"); lblPulsaElBoton.setBounds(47, 32, 85, 14); contentPane.add(lblPulsaElBoton); lblEstasSobreLa = new JLabel("Estas sobre la "); lblEstasSobreLa.setBounds(158, 224, 192, 14); contentPane.add(lblEstasSobreLa); JLabel lblSoloSePuede = new JLabel("Solo se puede escribir digitos"); lblSoloSePuede.setBounds(371, 208, 193, 14); contentPane.add(lblSoloSePuede); JLabel lblNombreElegido = new JLabel("Nombre Elegido"); lblNombreElegido.setBounds(175, 124, 110, 14); contentPane.add(lblNombreElegido); //Campo de texto textField = new JTextField(); textField.setBounds(371, 68, 193, 26); contentPane.add(textField); textField_1 = new JTextField(); textField_1.setEditable(false); textField_1.setBounds(175, 150, 141, 20); contentPane.add(textField_1); textField_2 = new JTextField(); textField_2.setBounds(371, 247, 126, 20);

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS contentPane.add(textField_2); //Botones JButton btnPulsame = new JButton("Pulsame"); btnPulsame.setBounds(43, 70, 89, 23); contentPane.add(btnPulsame); JButton btnAnadir= new JButton("A\u00F1adir"); btnAnadir.setBounds(371, 124, 89, 23); contentPane.add(btnAnadir); //Botones de radio rdbtnOpcion_1= new JRadioButton("Opcion 1"); rdbtnOpcion_1.setBounds(43, 194, 109, 23); contentPane.add(rdbtnOpcion_1); rdbtnOpcion_2 = new JRadioButton("Opcion 2"); rdbtnOpcion_2.setBounds(43, 220, 109, 23); contentPane.add(rdbtnOpcion_2); rdbtnOpcion_3 = new JRadioButton("Opcion 3"); rdbtnOpcion_3.setBounds(43, 246, 109, 23); contentPane.add(rdbtnOpcion_3); //Agrupamos los botones de radio ButtonGroup bgroup = new ButtonGroup(); bgroup.add(rdbtnOpcion_1); bgroup.add(rdbtnOpcion_2); bgroup.add(rdbtnOpcion_3); //Menu de opciones comboBox = new JComboBox(); comboBox.setBounds(175, 70, 141, 22); contentPane.add(comboBox); //Añadimos opciones comboBox.addItem("Fernando"); comboBox.addItem("Alberto"); comboBox.addItem("Arturo"); //EVENTOS btnPulsame.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ JOptionPane.showMessageDialog(contentPane, "¡Me has pulsado!"); } }); //En este caso hemos debido de converir el componente en un atributo comboBox.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ textField_1.setText(comboBox.getItemAt(comboBox.getSelectedIndex())); } }); textField.addKeyListener(new KeyListener(){ public void keyTyped (KeyEvent e){ //Si el caracter introducido es un digito... if (Character.isDigit(e.getKeyChar())){ //... no lo escribe e.consume(); } } public void keyReleased(KeyEvent e){ } public void keyPressed(KeyEvent e){

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS } }); btnAnadir.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ comboBox.addItem(textField.getText()); textField.setText(""); JOptionPane.showMessageDialog(contentPane, "Nombre Añadido"); } }); rdbtnOpcion_1.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e){ } public void mouseEntered(MouseEvent e){ lblEstasSobreLa.setText(lblEstasSobreLa.getText()+rdbtnOpcion_1.getText()); } public void mouseExited(MouseEvent e){ lblEstasSobreLa.setText("Estas sobre la "); } public void mousePressed(MouseEvent e){ } public void mouseReleased(MouseEvent e){ } }); rdbtnOpcion_1.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e){ } public void mouseEntered(MouseEvent e){ lblEstasSobreLa.setText(lblEstasSobreLa.getText()+rdbtnOpcion_1.getText()); } public void mouseExited(MouseEvent e){ lblEstasSobreLa.setText("Estas sobre la "); } public void mousePressed(MouseEvent e){ } public void mouseReleased(MouseEvent e){ } }); rdbtnOpcion_2.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e){ } public void mouseEntered(MouseEvent e){ lblEstasSobreLa.setText(lblEstasSobreLa.getText()+rdbtnOpcion_2.getText()); } public void mouseExited(MouseEvent e){ lblEstasSobreLa.setText("Estas sobre la "); } public void mousePressed(MouseEvent e){ } public void mouseReleased(MouseEvent e){ } });

SEMANA 13

LAB. PROGRAMACION ORIENTADO A OBJETOS

SEMANA 13

textField_2.addKeyListener(new KeyListener(){ public void keyTyped (KeyEvent e){ //Si el caracter introducido no es un digito... if (!Character.isDigit(e.getKeyChar())){ //... no lo escribe e.consume(); } } public void keyReleased(KeyEvent e){ } public void keyPressed(KeyEvent e){ } });

IV – EJERCICIOS PROPUESTOS (PRESENTAR INFORME)

01 Implementar una calculadora con las operaciones básicas y algunas funciones científicas usando componentes de Java Swing.

02 Desarrollar un programa en modo gráfico y ArrayLists para gestión de stock. Debe tener botones de comandos y otros para agregar, quitar, modificar, mostrar detalles (en ventana aparte) y mostrar todos los productos en un área de texto. Asuma lo necesario....


Similar Free PDFs