La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Programando GUI y Eventos

Presentaciones similares


Presentación del tema: "Programando GUI y Eventos"— Transcripción de la presentación:

1 Programando GUI y Eventos
Capitulo 14 Programando GUI y Eventos ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

2 Intro to OOP with Java, C. Thomas Wu
Objetivos Definir una subclase de JFrame para implementar una ventana marco a medida Escribir programas manejados por eventos usando el modelo de delegación de Java Disponer objetos GUI (interfase de usuario gráfica) sobre una ventana usando manejadores de diseño (layout managers) y paneles anidados Escribir aplicaciones GUI usando objetos JButton, JLabel, ImageIcon, JTextField, JTextArea, JCheckBox, JRadioButton, JComboBox, Jlist y JSlider del paquete javax.swing Escribir aplicaciones GUI con menúes Escribir aplicaciones GUI que que procese eventos de ratón We will learn how to create a customized frame window by defining a subclass of the JFrame class. Among the many different types of GUI objects, arguably the buttons are most common. We will learn how to create and place buttons on a frame in this lesson. ©The McGraw-Hill Companies, Inc.

3 Interfase Gráfica de Usuarios GUI
Intro to OOP with Java, C. Thomas Wu Interfase Gráfica de Usuarios GUI Una aplicación normalmente consta de una o más ventanas con las q’ el usuario puede interactuar. Las ventanas y los objetos con los que interactua el usuario se conocen como GUI En Java, programas basados en GUI se implementan usando clases de los paquetes javax.swing y java.awt . Las clases Swing dan mayor compatibilidad entre los distintos SO. Están totalmente implementadas en Java, y se comportan de la misma forma, independientemente del SO. Swing livianas totalmente en java lightweight awt pesadas usan los GUI nativos heavyweight Ej el botón se implementa usando los botones de windows en windows, el botón Macintosh en Mac, etc Classes we use to develop GUI-based programs are located in two packages javax.swing and java.awt. Many of the classes in the java.awt package are replaced by Swing counterparts, and for the most part, using the Swing classes over the AWT classes is the preferred approach because the newer Swing classes are better implementation. We still have to refer to java.awt package because there are some classes that are defined only in the java.awt package. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

4 Intro to OOP with Java, C. Thomas Wu
Ej Objetos GUI Varios objetos GUI del paquete javax.swing. Here's a sample frame that includes a number of common Swing components. We will see examples using JFrame and JButton in this lesson. We will see other components in the later lessons of this module. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

5 Prog orientada a eventos
Para crear una aplicación efectiva usando GUI se usa un nuevo estilo de control de operación llamado programación manejada por eventos. Ocurre un evento cuando: se mueve el cursor, se presiona un botón, se elige una opción de menú, etc Los objetos se programan para que respondan a los eventos diseñando métodos de manejo de eventos. La mayoría de las aplicaciones actuales GUI se maneja por eventos. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

6 Herencia de JFrame Object java.lang
Component * def un obj q’ pde mostrarse ej botón Container * def un componente q’ pde contener otro componente Windows * def una ventana básica sin título ni borde, eventos Frame * def un ventana con título y bordes JFrame ** def un frame con capacidades extendidas Paquetes * java.awt ** javax.swing ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

7 Intro to OOP with Java, C. Thomas Wu
Subclase de JFrame Para crear una marco de ventana a medida, definimos una subclase de la clase JFrame . La clase JFrame contiene la funcionalidad rudimentaria para soportar las características encontradas en cualquier marco de ventana. The standard JFrame class includes only most basic functionalities. When we need a frame window in our application, it is typical for us to define a subclass of JFrame to create a frame window that is customized to our needs. We will study the basics of this customization. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

8 Intro to OOP with Java, C. Thomas Wu
Creando un JFrame import javax.swing.*; class Ch7DefaultJFrame { public static void main( String[] args ) { JFrame defaultJFrame; defaultJFrame = new JFrame(); defaultJFrame.setVisible(true); } Before we start to explore how to customize a frame window, let's see the behavior of a plain standard JFrame object. This sample program creates a default JFrame object. When you run this program, a very tiny window appears at the top left corner of the screen. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

9 Creando una Subclase de JFrame
Intro to OOP with Java, C. Thomas Wu Creando una Subclase de JFrame Para definir una subclase de otra, declaramos a la subclase con la palabra reservada extends. import javax.swing.*; class Ch7JFrameSubclass1 extends JFrame { . . . } A subclass of any class is declared by including the keyword 'extends' the class definition header. The example here defines a subclass of JFrame named Ch7JFrameSubclass1. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

10 Customizing Ch14JFrameSubclass1
Intro to OOP with Java, C. Thomas Wu Customizing Ch14JFrameSubclass1 Una instancia de Ch14JFrameSubclass1 tendrá las sig características: El título se pone a My First Subclass. El programa termina cuando se presiona en el cuadro de cerrar El tamaño del marco es de 300 pixeles de ancho por 200 de alto. Se posiciona el marco en las coordenadas (150, 250). Estas propiedades están incluidas en el constructor por defecto. Open the sample Ch7JFrameSubclass1 class and see how the constructor includes a number of statements such as setTitle and setLocation to set the properties. These methods are all inherited from the superclass JFrame. The last statement is setDefaultCloseOperation that defines the frame's behavior when the close box of the frame is clicked. Passing the class constant EXIT_ON_CLOSE specifies to stop the application when the close box of a frame is clicked. Remove this statement and see what happens. ©The McGraw-Hill Companies, Inc.

11 JFrameSubclass1.class import javax.swing.*;
class JFrameSubclass1 extends JFrame{ private static final int ANCHO= 300; private static final int ALTO= 200; private static final int ORIGEN_X= 150; private static final int ORIGEN_Y= 250; public JFrameSubclass1 (){ setTitle (“My First Subclass”); setSize (ANCHO, ALTO); setLocation (ORIGEN_X, ORIGEN_Y); setDefaultCloseOperation(EXIT_ON_CLOSE); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

12 Mostrando JFrameSubclass1
Intro to OOP with Java, C. Thomas Wu Mostrando JFrameSubclass1 La ventana marco JFrameSubclass1 sobre la pantalla This diagram illustrates how the arguments to the setSize and setLocation methods affect the frame window appearance on the screen. The top left corner of the screen has coordinate (0,0). The value of x increases as you move toward right and the value of y increases as you move down. Notice that the screen coordinate is different from the coordinate system of a mathematical 2-D graph. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

13 SetDefaultCloseOperation()
Determina lo que ocurre cuando se cierra la ventana desde el ícono EXIT_ON_CLOSE Cierra la ventana y libera la ventana y todas las componentes y cierra la aplicación DISPOSE_ON_CLOSE El marco y sus componentes se eliminan pero la aplicación no termina DO_NOTHING_ON_CLOSE Hace inefectiva la operación del cierre de ventana HIDE_ON_CLOSE Sólo oculta la ventana llamando a setVisible() false, se puede volver a mostrar ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

14 El panel de contenido (Content Pane) de un JFrame
Intro to OOP with Java, C. Thomas Wu El panel de contenido (Content Pane) de un JFrame El panel de contenido es donde ponemos los objetos GUI tales como botones, títulos, barras de desplazamiento, etc Accedemos al panel de contenido llamando al método getContentPane de su marco. El área gris es el panel de contenido de este marco A frame window is composed of four borders, a title bar, and a content area. The content area is called a content pane in Java, and this is the area we can use to place GUI components. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

15 JRootPane Los contenedor de 1er plano (JFrame, JApplet, JDialog, etc) delegan sus operaciones a JRootPane Este panel raíz maneja el panel de contenidos y la barra de menú a través de otros contenedores Los GUI se agregan a panel de contenidos ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

16 JRootPane El JRootPane está compuesto por un glassPane, un contentPane y una barra de menú opcional. El contentPane y la barra de menú, si existen, son manejados por un objeto JLayeredPane Referencia: java.sun.com Understanding Containers ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

17 Cambiando el color de fondo
Intro to OOP with Java, C. Thomas Wu Cambiando el color de fondo Cambio del color de fondo a azul del panel de contenidos Container contentPane = getContentPane(); contentPane.setBackground(Color.BLUE); Arch fuente: Ch14JFrameSubclass2.java We access the content pane of a frame by calling the JFrame method called getContentPane. We declare the data type for the object returned by the getContentPane method to Container. Once we get the content pane object, we can call its methods. The example here calls the setBackground method to change the default background color of gray to white. The complete sample code can be found in the file Ch7JFrameSubclass2.java. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

18 Poniendo objetos GUI sobre un marco
Intro to OOP with Java, C. Thomas Wu Poniendo objetos GUI sobre un marco Hay dos maneras de poner objetos GUI sobre el panel de contenidos del marco: Usar un manejador de diseño (layout manager) FlowLayout (por defecto) BorderLayout GridLayout Usar un posicionamiento absoluto Poner un manejador de diseño null (null layout manager) The content pane of a frame is where we can place GUI components. Among the approaches available to us to place components, we will study the easier one here. The easier absolute positioning is not a recommended approach for practical applications, but our objective here is to learn the basic handling of events and placement of GUI objects, we will use the easier approach. Chapter 12 of the textbook discusses different layout managers. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

19 Intro to OOP with Java, C. Thomas Wu
Poniendo un Botón Un objeto JButton es un componente GUI que representa un Botón de selección (pushbutton). Ej de como poner un botón usando FlowLayout. contentPane.setLayout( new FlowLayout()); okButton = new JButton("OK"); cancelButton = new JButton("CANCEL"); contentPane.add(okButton); contentPane.add(cancelButton); The key point to remember in using absolute positioning: Set the layout manager of the content pane to null as conentPane.setLayout(null) Set the bounds to a GUI object. For example okButton.setBounds(70, 125, 80, 20); Add a GUI object to the content pane by calling the add method as contentPane.add(okButton); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

20 Ajustar el tamaño de los botones
El tamaño de los botones se ajusta al texto que contiene, el botón Cancel es mayor que el Ok. Usar el método setSize() para especificar el tamaño hay que llamarlo antes que al método add() ...... JButton okButton = new JButton(“OK”); okButton.setSize(80,30); contentPane.add(okButton); JButton cancelButton = new JButton(“CANCEL”); cancelButton.setSize(80,30); contentPane.add(cancelButton); .... ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

21 Eventos y SO Las acciones sobre los GUI son identificadas por el SO
El SO determina a cual de los programas que se están ejecutando debe notificar Un click del mouse es registrado por el SO determinando la posición sobre la pantalla, det que aplicación controla esa ventana y coumunica la accción al programa La señal que recibe el programa desde el SO se llama evento ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

22 Intro to OOP with Java, C. Thomas Wu
Definiciones Una acción sobre un objeto GUI, como presionar un botón se llama evento. El mecanismo para procesar los eventos se llama manejar eventos (event handling). El modelo de Java de manejo de eventos se basa en el concepto conocido como delegación (delegation-based event model). Con este modelo, el manejo de eventos se implementa por dos tipos de objetos : Objetos fuente de eventos (event source objects) Objetos escuchadores de eventos (event listener objects) JButton and other GUI objects are event source objects. Any object can be designated as event listener objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

23 Objetos Fuentes de Eventos
Intro to OOP with Java, C. Thomas Wu Objetos Fuentes de Eventos Un objeto fuente de eventos es el objeto GUI en el que ocurre el evento. Decimos que una fuente de eventos genera un evento. Botones, cajas de texto, listas menús son fuentes de eventos comunes en las aplicaciones basadas en interfase gráfica del usuario. Aunque es posible, en general no definimos nuestras propias fuentes de eventos cuando se escriben aplicaciones basadas en GUI A single event source can generate more than one type of events. When an event is generated, a corresponding event listener is notified. Whether there is a designated listener or not, event sources generates events. If there's a no matching listeners, generated events are simply ignored. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

24 Objetos oyentes de eventos
Intro to OOP with Java, C. Thomas Wu Objetos oyentes de eventos Un oyente de eventos es un objeto que incluye un método que se ejecutará en respuesta a un evento generado El oyente debe asociarse, o registrarse a una fuente, de manera que se notifique cuando la fuente genera el evento. A listener can listen to a single type of events. If an event source generates two types of events, then we need two different listeners if we want process both types of events. A single listener, however, can be set to listen to single type of events from more than one event source. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

25 Conectando Fuentes y escuchadores
Intro to OOP with Java, C. Thomas Wu Conectando Fuentes y escuchadores Fuente de evento Oyente de evento notify JButton Handler register This diagram shows the relationship between the event source and listener. First we register a listener to an event source. Once registered, whenever an event is generated, the event source will notify the listener. Un oyente debe registrarse a la fuente. Una vez registrado él será notificado cuando la fuente genere un evento. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

26 Intro to OOP with Java, C. Thomas Wu
Tipos de eventos La registración y notificación es específica del tipo de eventos Escuchador del ratón maneja eventos de ratón Escuchador de items maneja eventos de selección de items , etc Entre los diferentes tipos de eventos, el evento de acción (action event) es el más común. Elegir un botón genera un evento de acción Elegir un item de menú genera un evento de acción, etc Eventos de acción son generados por fuentes de eventos de acción (action event sources) y manejados por escuchadores de eventos de acción (action event listeners). There are different types of events. Some event sources generate only one type of events, while others generate three or four different types of events. For example, a button can generate an action event, a change event, and a item event. The most common type of event we are interested in processing for various types of GUI components is the action event. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

27 Manejando Eventos de Acción
Intro to OOP with Java, C. Thomas Wu Manejando Eventos de Acción action event source actionPerformed action event listener JButton Button Handler addActionListener This code shows how we register an action event listener to a button. The object we register as an action listener must be an instance of a class that implements the ActionListener interface. The class must define a method named actionPerformed. This is the method executed in response to the generated action events. JButton button = new JButton("OK"); ButtonHandler handler = new ButtonHandler( ); // esta clase se muestra a continuación button.addActionListener(handler); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

28 Registro del listener class MiManejadorBoton implements ActionListener
.... button.addActionListener(this); void actionPerformed(ActionEvent)); // cod a ejecutar cuando se aprieta boton Presion OK Crea Pasado a Objeto ActionEvent ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

29 Interfase ActionListener
Intro to OOP with Java, C. Thomas Wu Interfase ActionListener Cuando llamamos al método addActionListener de una fuente de eventos, debemos pasarle una instancia de la clase que implementa la interfase ActionListener. button.addActionListener(handler) o button.addActionListener(this) La interfase ActionListener incluye un método llamado actionPerformed. Una clase que implemente la interfase ActionListener debe proveer el cuerpo del método de actionPerformed. Ya que actionPerformed es el método que se invoca cuando se genera un evento aquí es donde se coloca el código que deseamos se ejecute en respuesta al evento ocurrido ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

30 La clase ButtonHandler
Intro to OOP with Java, C. Thomas Wu La clase ButtonHandler import javax.swing.*; import java.awt.*; import java.awt.event.*; class ButtonHandler implements ActionListener { // implementación del mét busca la fuente del evento public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); JRootPane rootPane = clickedButton.getRootPane( ); Frame frame = (JFrame) rootPane.getParent(); frame.setTitle(“Ud Eligió " + clickedButton.getText()); } This actionPerformed method is programmed to change the title of the frame to 'You clicked OK' or 'You clicked Cancel'. The actionPerformed method accepts one parameter of type ActionEvent. The getSource method of ActionEvent returns the event source source object. Because the object can be of any type, we type cast it to JButton. The next two statements are necessary to get a frame object that contains this event source. Once we have a reference to this frame object, we call its setTitle method to change the frame's title. More discussion on this actionPerformed method is presented on page 397 of the textbook. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

31 Container como Oyente de Evento
Intro to OOP with Java, C. Thomas Wu Container como Oyente de Evento En vez de definir un oyente de eventos separado, tal como ButtonHandler, es más común tener un objeto que contiene las fuentes de eventos a ser escuchadas Ej: Este marco es el oyente de los eventos de acción de los botones que contiene event listener Oyente de eventos Because ActionListener is a Java interface and not a class, action event listener objects are not limited to instances of fixed classes. Any class can implement the ActionListener interface, so any object from a class that implements this interface can be an action event listener. This adds flexibility as this example illustrates. Instead of using a ButtonHandler object, we can make the frame object itself to be an action event listener. event source Fuente de eventos ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

32 Ch14JButtonFrameHandler
Intro to OOP with Java, C. Thomas Wu Ch14JButtonFrameHandler . . . class Ch14JButtonFrameHandler extends JFrame implements ActionListener { cancelButton.addActionListener(this); // el objeto de la subclase JFrame es el oyente okButton.addActionListener(this); ..... public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); setTitle("You clicked " + buttonText); } This is how a frame that contains the buttons can be made to be their event listeners. Notice that because the actionPerformed method is defined in the frame class, setting the title is matter of calling its setTitle method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

33 Intro to OOP with Java, C. Thomas Wu
Clases GUI de Texto Las clases JLabel, JTextField y JTextArea se usan para campos de texto Un obj JLabel muestra objetos no editables (o imágenes) Un obj JTextField permite que el usuario ingrese una línea de texto Un obj. JTextArea permite que el usuario entre múltiples líneas de texto. Puede usarse para texto no editable taa Notice that JLabel objects are not limited to text. Using them is actually the easiest and quickest way to display an image. JTextArea has dual pursposes. It can be used to display noneditable multi-line text, similar to using multiple JLabel objects. It can also be used to allow the user to enter multiple lines of text, similar to using multiple JTextField objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

34 Jerarquia de clases GUI texto
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Ref: java.sun.com

35 Ej Uso de GUI Texto Ref: java.sun.com
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Ref: java.sun.com

36 Intro to OOP with Java, C. Thomas Wu
JTextField Se genera un evento de acción, al igual que con JButton, cuando se presiona ENTER sobre el GUI El mét getText de JTextField permite obtener el texto ingresado JTextField input = new JTextField( ); input.addActionListener(eventListener); contentPane.add(input); The getText method is most commonly used inside the actionPerformed method of an action listener. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

37 Modif para que maneje el evento la subclase de JFrame
JTextField inputLine = new JTextField( ); inputLine.setColumns(22); // nro de caracteres visibles contentPane.add (inputLine) inputLine.addActionListener(this); public void actionPerformed(ActionEvent event){ if (event.getSource() intanceof JButton ){ JButton elegido = (JButton) event.getSource(); String texto = elegido.getText(); setTitle (“Ha elegido “ + texto); } else { // la fuente del evento es inputline //setTitle (“Ha ingresado ‘ “ + inputLine.getLine() + “ ’ ’”);}......} o JTextField textField = (JTextField) event.getSource(); setTitle(“Ha ingresado ‘ “ + textField.getText() + “ ’ ’”);} } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

38 Intro to OOP with Java, C. Thomas Wu
JLabel JLabel se usa para mostrar una etiqueta Puede ser texto o imágen. No genera eventos Cuando creamos una imágen, se le pasa un objeto ImageIcon en vez de un String JLabel textLabel = new JLabel("Please enter your name"); contentPane.add(textLabel); // imagen JLabel imgLabel = new JLabel(new ImageIcon("cat.gif")); contentPane.add(imgLabel); A JLabel is strictly for displaying noneditable text or image. A JLabel object does not generate any events. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

39 Intro to OOP with Java, C. Thomas Wu
Ch14TextFrame2 JLabel (con un texto) JLabel (con una imágen) JTextField The sample Ch7TextFrame2 class includes five GUI components: two JLabel objects, one JTextField object, and two JButton objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

40 Intro to OOP with Java, C. Thomas Wu
JTextArea JTextArea para mostrar o permitir el ingreso de múltiples líneas de texto El mét setText() asigna el texto a JTextArea, reemplazando el contenido El mét append() agrega el texto al actual JTextArea textArea = new JTextArea( ); . . . textArea.setText("Hello\n"); textArea.append("the lost "); textArea.append("world"); Hello the lost world JTextArea Notice how the append method works. If you want to place the text to be appended on a new line, you have ouput the newline control character \n at the appropriate point. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

41 Intro to OOP with Java, C. Thomas Wu
Ch14TextFrame3 El estado de Ch14TextFrame3 después de ingresar 6 palabras Run the program and explore it. This frame has one JTextField object and one JTextArea object. Every time a text is entered in the text field and the ENTER key is pressed or the ADD button is clicked, the entered text is append to the text area. The border of red color is adorned to the text area to demarcate the region. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

42 Cuadro del JTextArea ... JTextArea areaTexto = new JTextArea();
areaTexto.setColumns(22); areaTexto.setRows(8); // idem new JTextArea(22,8) areaTexto.setBorder(BorderFactory.createLineBorder(Color.RED)); areaTexto.setEditable=(false); // por defecto es editable contentPane.add(areaTexto); String textoIngresado = input.getText(); //areaTexto.append(textoIngresado + “\n”); // dde de la plataf areaTexto.append(textoIngresado + System.getProperty(“line.separator”); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

43 Agregar una barra de desplazamiento
Intro to OOP with Java, C. Thomas Wu Agregar una barra de desplazamiento Por defecto JTextArea no tiene una barra. Para que la tenga hay que colocar al JTextArea en un panel con desplazamiento (JScrollPane). JTextArea textArea = new JTextArea(); . . . JScrollPane scrollText = new JScrollPane(textArea); scrollText.setSize(200, 135); scrollText.setBOrder(BorderFactory.createLineBorder(Color.red)); // se agrega a la barra contentPane.add(scrollText); ... Here's a sample to wrap the text area with scroll bars. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

44 Ch14TextFrame3 con barra desplazam
Intro to OOP with Java, C. Thomas Wu Ch14TextFrame3 con barra desplazam Ej ventana Ch14TextFrame3 usando JScrollPane Initially, there will be no scroll bars. Run the program and confirm this behavior. When the displayed text goes beyond the horizontal or vertical boundary, the corresponding scroll bar appears. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

45 Manejadores de Presentación (Layout Managers)
Los manejadores de presentación determinan como se agregan los objetos GUI al contenedor (content pane o un frame) Entre otros los mas comunes son: - FlowLayout (Ch14FlowLayoutSample.java) BorderLayout (Ch14BorderLayoutSample.java) GridLayout (Ch14GridLayoutSample.java) Taa: CardLayout y GridBagLayout. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

46 FlowLayout Los componentes se ubican de izquierda a derecha y de arriba a abajo Por defecto los componentes en cada línea se centran. Cuando el marco que contiene un componente se modifica de tamaño, los componentes se ajustan de acuerdo al nuevo espacio ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

47 Ej FlowLayout Cinco botones usando FlowLayout.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

48 BorderLayout Este divide al contenedor en 5 regiones:
centro, norte, sur, este y oeste Las regiones norte y sur se expanden o contraen sólo en altura Las regiones este y oeste sólo en ancho La central en ambas ancho y alto. No es necesario que se ocupen todas las regiones Para poner una componente sobre el layout se especifica la región empleando las constantes ej. contentPane.add(boton1, BorderLayout.North); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

49 Intro to OOP with Java, C. Thomas Wu
BorderLayout Sample contentPane.setLayout(new BorderLayout()); contentPane.add(button1, BorderLayout.NORTH); contentPane.add(button2, BorderLayout.SOUTH); contentPane.add(button3, BorderLayout.EAST); contentPane.add(button4, BorderLayout.WEST); contentPane.add(button5, BorderLayout.CENTER); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

50 GridLayout Coloca los componentes en una grilla igualmente espaciada de N x M Los componentes se colocan de arriba a abajo y de izquierda a derecha. El número de filas y columnas permanece sin cambios despues de que se modifica tamaño pero el ancho y alto de cada región se adapta Se puede crear una grilla de sólo una columna o sólo una fila poniendo columna en 0 o fila en 0 setLayout(new GridLayout(0, 6, 10, 10); 1 fila setLayout(new GridLayout(6, 0, 10, 10); 1 columna ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

51 GridLayout Sample ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

52 Paneles Anidados Es posible pero díficil poner a todos los componentes GUI en un sólo contenedor. Es más fácil usar varios paneles, colocando uno dentro de otro. Crearemos dos marcos que contengan paneles anidados. Ch14NestedPanels1.java tablero para el juego del Ta Te Ti Ch14NestedPanels2.java interfase para el juego AltoBajo ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

53 Paneles de Alto Bajo (HiLo)
public Ch14NestedPanels2( ) { JPanel guessPanel, hintPanel, controlPanel, buttonPanel; JButton enterBtn, cancelBtn; Container contentPane; contentPane = getContentPane( ); contentPane.setLayout(new GridLayout(3, 1)); //grilla 3 // 1er panel de la grilla guessPanel = new JPanel(); guessPanel.setBorder(BorderFactory.createTitledBorder( "Your Guess")); guessPanel.add(guessEntry = new JTextField(10)); ..Cont ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

54 cont. paneles HiLo hintPanel = new JPanel(); // 2do panel de la grilla
hintPanel.setBorder(BorderFactory.createTitledBorder ("Hint")); hintPanel.add(hint = new JLabel("Let's Play HiLo")); controlPanel = new JPanel(new BorderLayout()); buttonPanel = new JPanel(); // flowLayout buttonPanel.add(enterBtn = new JButton(ENTER)); buttonPanel.add(cancelBtn = new JButton(CANCEL)); controlPanel.add(buttonPanel, BorderLayout.SOUTH); contentPane.add(guessPanel); contentPane.add(hintPanel); contentPane.add(controlPanel); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

55 Otras componentes GUI comunes
JCheckBox ver Ch14JCheckBoxSample1.java yCh14JCheckBoxSample2.java JRadioButton ver Ch14JRadioButtonSample.java JComboBox verCh14JComboBoxSample.java JList ver Ch14JListSample.java JSlider ver Ch14JSliderSample.java implementar la interfase ItemListener para obtener el item elegido además de ActionListener ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

56 JCheckBox ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

57 JCheckBox Selección Para crear un JChekBox con el texto Java:
JCheckBox cbBtn = new JCheckBox(“Java”); Para ver si ha sido seleccionado: if (cbBtn.isSelected()){ System.out.println (“You can program in ” + cbBtn.getText()); }else { System.out.println (“You cannot program in ” + cbBtn.getText()); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

58 JCheckBox, JRadioButton
JCheckBox genera al = que otros botones un evento de acción Además genera otro tipo de eventos: eventos de item (item events) Este se genera cuando cambia de estado (seleccionado – no seleccionado y viceversa) Cuando se genera un evento de item se llama al met itemStateChanged(ItemEvent event) dentro del mét. se verifica el estado con: getStateChage() ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

59 Intro to OOP with Java, C. Thomas Wu
Menús El paquete javax.swing contiene tres clases de menú: JMenuBar, Jmenu y JMenuItem. JMenuBar es una barra donde se coloca el menú. Hay una barra de menú por marco. JMenu (tal como Archivo o Editar) es un grupo de opciones.Un JMenuBar puede incluir varios JMenu. JMenuItem (tal como copiar, cortar pegar) son las posibles elecciones de un objeto JMenu. Sólo los JMenuItem generan eventos. Almost all nontrivial GUI programs support menus. By using these three menu-related classes, we can easily add menus to our Java programs. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

60 public void itemStateChange(ItemEvent event)
if event.getStateChange()==ItemEvent.SELECTED){ System.out.println (“Eligió esta caja”); }else{ System.out.println (“No eligió esta caja”); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

61 Intro to OOP with Java, C. Thomas Wu
Componentes de un Menú Edit View Help JMenuBar Edit View Help File The diagram shows how the menu-related objects correspond to the actual menus. JMenu JMenuItem separator ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

62 Intro to OOP with Java, C. Thomas Wu
Creación de un Menú Crear un obj JMenuBar y asociarlo a un frame Crear un objeto JMenu Crear un objeto JMenuItem y y agregarlo a un objeto JMenu. Adjuntar el objeto JMenu al JMenuBar. This is not the only valid sequence. Other sequences are possible. We list this sequence as one possible sequence you can follow in creating menus. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

63 Sentencias para crear un Menu
// Crea un Menu filemenu = new JMenu (“File”); // Crea los items de un menu item = new JMenuItem (“New”); item.addActionListener (this); filemenu.add(item); // Crea una linea separadora filemenu.addSeparator(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

64 Sentencias para crear un Menu cont
// adjuntar a la barra de menu JMenuBar menuBar = new JMenuBar(); setMenuBar (menuBar); // la adjunta al frame menuBar.add(fileMenu); menuBar.add(editMenu); // mostrar que item se eligió response = new JLabel (“Prueba del menú”); response.setSize(250, 50); contentPane.add(response); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

65 Obtener el item elegido
- Si la fuente de un evento es un menu, el met getActionComand de ActionEvent devuelve el texto del menu ... String menuName; menuName = event.getActionComand(); if (menuName.equals (“Quit”)){ System.exit(0); } else { response.setText (“Se eligio “ + menuName ); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.


Descargar ppt "Programando GUI y Eventos"

Presentaciones similares


Anuncios Google