Anda di halaman 1dari 6

ACTIVIDAD AUTOAPRENDIZAJE Programa: Programacin Curso: Desarrollo de Aplicaciones que utilizan Archivos Unidad didctica: Uso de Nombre de la actividad:

Aplicaciones que utilizan el Java Swing y manejan Java las Excepciones Swing

Descripcin de la actividad

1. Hacer la lectura definida de Aplicaciones con Java Swing. 2. Utilizar los ejemplos descritos en la lectura para compilarlos y ejecutarlos y entender mejor la definicin y el
manejo de los archivos de texto.

**A continuacin se muestra una aplicacin que a travs del uso de un men nos permite * cambiar el estilo del texto utilizado en un objeto de la clase JTextPane, en esta aplicacin * utilizamos un men para seleccionar el estilo de letra a utilizar: * */ package IV_Manejo_Archivos_Texto_Excepciones_en_Java; /** * @author Profesor: LUIS FERNANDO TEMOCHE ESPINOZA * Alumno: Carlos Arturo Prieto Gonzlez */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class AplicacionSwing5 extends JPanel implements ActionListener { /** * */ private static final long serialVersionUID = 1L; private Style estiloMorado,estiloGris,estiloCeleste,estiloRojo,estiloAzul; private JTextPane texto; public AplicacionSwing5() { setLayout( new BorderLayout() ); JMenuBar menu = new JMenuBar(); JMenu estilo = new JMenu( "Estilo" ); menu.add( estilo ); JMenuItem mi = new JMenuItem( "Morado" ); estilo.add( mi ); mi.addActionListener(this); mi = new JMenuItem( "Gris" ); estilo.add( mi ); mi.addActionListener(this); mi = new JMenuItem( "Celeste" ); estilo.add( mi ); mi.addActionListener(this); mi = new JMenuItem( "Rojo" ); estilo.add( mi ); mi.addActionListener(this); mi = new JMenuItem( "Azul" ); estilo.add( mi ); mi.addActionListener( this ); add( menu,BorderLayout.NORTH ); StyleContext sc = new StyleContext(); estiloMorado = sc.addStyle( null,null ); StyleConstants.setForeground( estiloMorado,Color.magenta ); estiloGris = sc.addStyle( null,null ); StyleConstants.setForeground( estiloGris,Color.gray ); StyleConstants.setFontSize( estiloGris,24 ); estiloCeleste = sc.addStyle( null,null ); StyleConstants.setForeground( estiloCeleste,Color.cyan ); estiloRojo = sc.addStyle( null,null ); StyleConstants.setForeground( estiloRojo,Color.red ); estiloAzul = sc.addStyle( null,null ); StyleConstants.setForeground( estiloAzul,Color.blue ); DefaultStyledDocument doc = new DefaultStyledDocument(sc); JTextPane texto = new JTextPane(doc); add( texto,BorderLayout.CENTER ); } public void actionPerformed( ActionEvent e ) { Style estilo = null; String color = (String) e.getActionCommand(); if( color.equals( "Morado" ) ) { estilo = estiloMorado; } else if( color.equals( "Celeste" ) ) { estilo = estiloCeleste;

} else if( color.equals( "Gris" ) ) { estilo = estiloGris; } else if( color.equals( "Rojo" ) ) { estilo = estiloRojo; } else if( color.equals( "Azul" ) ) { estilo = estiloAzul; } texto.setCharacterAttributes( estilo,false ); } public static void main( String argv[] ) { JFrame app = new JFrame( "Tutorial de Java, Swing" ); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent evt ){ System.exit( 0 ); } } ); app.getContentPane().add( new AplicacionSwing5(),BorderLayout.CENTER ); app.setSize( 300,180 ); app.setVisible( true ); } }

3. Entrar a Internet a las clases de la Java API y en la clase MenuBar y Menu detente a revisarlas ms

cuidadosamente. Utiliza el Google para hacer la bsqueda MenuBar Java Tutorial y revisa ms sobre lo aprendido en la lectura. Utiliza tambien en el Google Math.random() Tutorial lo utilizars en el siguiente punto.

Methods inherited from class java.awt.MenuItem


addActionListener, deleteShortcut, disable, disableEvents, enable, enable, enableEvents, getAc tionCommand, getActionListeners, getLabel,getListeners, getShortcut, isEnabled, processActionE vent, processEvent, removeActionListener, setActionCommand, setEnabled, setLabel,setShortcut

Methods inherited from class java.awt.MenuComponent


dispatchEvent, getFont, getName, getParent, getPeer, getTreeLock, postEvent, setFont, setName, toString

Methods inherited from class java.lang.Object


clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.awt.MenuContainer


getFont, postEvent

Constructor Detail
Menu

public Menu() throws HeadlessException

Constructs a new menu with an empty label. This menu is not a tear-off menu.

Throws:

HeadlessException - if GraphicsEnvironment.isHeadless() returns true.


Since:
JDK1.1

See Also:

GraphicsEnvironment.isHeadless()

Menu public Menu(String label) throws HeadlessException


Constructs a new menu with the specified label. This menu is not a tear-off menu.

Parameters:

label - the menu's label in the menu bar, or in another menu of which this menu is a submenu.
Throws:

HeadlessException - if GraphicsEnvironment.isHeadless() returns true.


See Also:

GraphicsEnvironment.isHeadless()

Menu public Menu(String label, boolean tearOff) throws HeadlessException


Constructs a new menu with the specified label, indicating whether the menu can be torn off. Tear-off functionality may not be supported by all implementations of AWT. If a particular implementation doesn't support tear-off menus, this value is silently ignored.

Parameters:

label - the menu's label in the menu bar, or in another menu of which this menu is a submenu. tearOff - if true, the menu is a tear-off menu.
Throws:

HeadlessException - if GraphicsEnvironment.isHeadless() returns true.


Since:
JDK1.0.

See Also:

GraphicsEnvironment.isHeadless()

Busquedas tutoriales en Google > http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html http://www.roseindia.net/java/example/java/swing/swingmenu.shtml http://dis.um.es/~bmoros/Tutorial/parte13/cap13-6.html

4. Escribe una aplicacin grfica o applet, que tenga tres mens: 1) Color, que presenta al menos 3 nombres de

colores (ej. ROJO, AZUL AMARILLO), 2) Figura, que presente al menos tres nombres de figuras (ej. CIRCULO, CUADRADO y RECTANGULO) y y 3) Nmero, que presente al menos tres numeros (ej, 1, 2, 3). La aplicacin por default dibujar el nmero de figuras seleccionadas en el color seleccionado con la figura seleccionada. La aplicacin dibujar las figuras especificadas con el color especificado y con el nmero especificado al azar en la ventana package IV_Manejo_Archivos_Texto_Excepciones_en_Java; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ActividadTresII extends JFrame

{ private private private private private private private

static final int lt = 0; final Color valoresColor[]={Color.black,Color.blue,Color.red,Color.green }; JRadioButtonMenuItem elementosColor[], elementosFiguras[], elementosNumeros []; JCheckBoxMenuItem elementosEstilo[]; JLabel pantallaEtiqueta; ButtonGroup grupoNumeros, grupoColores, grupoFiguras; int estilo;

private JMenuBar Barra; int colorear=0, fig=0, Num=1, Naleatorio; public ActividadTresII() {

// Crea barra mens Barra = new JMenuBar(); add (Barra, BorderLayout.NORTH ); // crear men Formato, con sus submens y elementos de men JMenu menu = new JMenu( "Menu" ); Barra.add( menu ); // / creacion de submenus JMenu menuColor = new JMenu( "Color" ); menu.add(menuColor); menu.addSeparator(); JMenu menuFiguras = new JMenu( "Figuras" ); menu.add(menuFiguras); menu.addSeparator(); JMenu menuNumeros = new JMenu( "Numeros" ); menu.add(menuNumeros);

// Submenu para colores String colores[] = { "Amarillo", "Azul", "Rojo", "Verde" }; elementosColor = new JRadioButtonMenuItem[ colores.length ]; grupoColores = new ButtonGroup(); ManejadorEventos manejadorEventos = new ManejadorEventos();

// seleccionar primer elemento del men Color elementosColor[ 0 ].setSelected( true );

// Submenu para figuras String figuras[] = { "Cuadrado", "Rectangulo", "Circulo" }; elementosFiguras = new JRadioButtonMenuItem[ figuras.length ]; grupoFiguras = new ButtonGroup();

// seleccionar primer elemento del men Color elementosFiguras[ 0 ].setSelected( true );

// Submenu para numeros String numeros[] = { "1", "2", "3" }; elementosNumeros = new JRadioButtonMenuItem[ numeros.length ]; grupoNumeros = new ButtonGroup(); // ManejadorEventos manejadorEventos2 = new ManejadorEventos();//==============

// seleccionar primer elemento del men Color elementosNumeros[ 0 ].setSelected( true );

setSize( 550, 550 ); setVisible( true );

} // fin del constructor // metodo para obtener la posicion de las figuras se ALEATORIA public int NumAleatorio (){ // Math.random(); nos devolver un nmero aleatorio entre 0,0 y 1,0 // Math.round(); redondea el valor que se encuentre dentro de los parntesis hacia arriba o hacia abajo Al nmero entero que est ms cercano. double nnn = Math.round(Math.random()*400); Naleatorio=(int)nnn ; /// CONVIERTE UN DOUBLE A ENTERO return Naleatorio ; }

public static void main( String args[] ) { ActividadTresII aplicacion = new ActividadTresII(); } //clase interna para manejar eventos de accin de los elementos de men private class ManejadorEventos implements ActionListener { //procesar selecciones de color y tipo de letra public void actionPerformed( ActionEvent evento ) {

//Evalua color if ( elementosColor[ colorear = 0; repaint(); } if ( elementosColor[ colorear = 1; repaint(); } if ( elementosColor[ colorear = 2; repaint(); } if ( elementosColor[ colorear = 3; repaint(); } //Evalua figura

0 ].isSelected() ) {

1 ].isSelected() ) {

2 ].isSelected() ) {

3 ].isSelected() ) {

if ( elementosFiguras[ 0 ].isSelected() ) { fig = 0; repaint(); } else if ( elementosFiguras[ 1 ].isSelected() ) { fig = 1; repaint(); } else if ( elementosFiguras[ 2 ].isSelected() ) { fig = 2; repaint(); } // Numero de figuras

if ( elementosNumeros[ 0 ].isSelected() ) { Num = 1; repaint(); } else if ( elementosNumeros[ 1 ].isSelected() ) { Num = 2; repaint(); } else if ( elementosNumeros[ 2 ].isSelected() ) { Num = 3; repaint(); } } // Fin mtodo actionPerformed

} // Fin clase ManejadorEventos

public void paint(Graphics g) { Barra.repaint(); { switch (colorear){ case 0: g.setColor(Color.YELLOW); break; case 1: g.setColor(Color.BLUE); break; case 2: g.setColor(Color.RED); break; case 3: g.setColor(Color.GREEN);

break; }

switch (fig){ case 0: g.fillRect(NumAleatorio () , NumAleatorio (), 150, 150); break; case 1: g.fillRect(NumAleatorio (), NumAleatorio (), 150, 200); break; case 2: g.fillOval(NumAleatorio (), NumAleatorio (), 150, 150); break; }

Anda mungkin juga menyukai