Anda di halaman 1dari 51

Crear un Modelo y Asignarlo a una JList

1. 2. 3.
4. 5. 6. JList lista = new JList(); DefaultListModel modelo = new DefaultListModel(); for(int i = 1; i<=10; i++){ modelo.addElement(i); } lista.setModel(modelo);

JList lista = new JList(); DefaultListModel modelo = new DefaultListModel(); for(int i = 1; i<=10; i++){ modelo.addElement(i); } lista.setModel(modelo);
Este ejemplo mostrar una JList con nmeros del 1 al 10. En este caso creamos primero una lista y luego un modelo. Aadimos los elementos al modelo y finalmente asignamos el modelo a la JList.

Otro Mtodo
Hay ms formas para crear una JList en java. En este caso tenemos los elementos dentro de un array, llamamos el constructor JList y se lo pasamos como parmetro.
ver en popupcopiar a portapapelesimprimir

1. 2.

String [] elementos = {"a","b","c","d"}; javax.swing.JList list = new javax.swing.JList(elementos);

public class JList extends JComponent implements Scrollable, Accessible A component that allows the user to select one or more objects from a list. A separate model, ListModel, represents the contents of the list. It's easy to display an array or vector of objects, using a JList constructor that builds a ListModel instance for you:
// Create a JList that displays the strings in data[] String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data); // The value of the JList model property is an object that provides // a read-only view of the data. It was constructed automatically. for(int i = 0; i < dataList.getModel().getSize(); i++) { System.out.println(dataList.getModel().getElementAt(i)); } // Create a JList that displays the superclass of JList.class. // We store the superclasses in a java.util.Vector. Vector superClasses = new Vector();

Class rootClass = javax.swing.JList.class; for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) { superClasses.addElement(cls); } JList classList = new JList(superClasses);

doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example:
JList JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(dataList);

By default the JList selection model allows any combination of items to be selected at a time, using the constant MULTIPLE_INTERVAL_SELECTION. The selection state is actually managed by a separate delegate object, an instance of ListSelectionModel. However JList provides convenient properties for managing the selection.
String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data); dataList.setSelectedIndex(1); dataList.getSelectedValue(); // select "two" // returns "two"

The contents of a JList can be dynamic, in other words, the list elements can change value and the size of the list can change after the JList has been created. The JList observes changes in its model with a swing.event.ListDataListener implementation. A correct implementation of ListModel notifies it's listeners each time a change occurs. The changes are characterized by a swing.event.ListDataEvent, which identifies the range of list indices that have been modified, added, or removed. Simple dynamic-content JList applications can use the DefaultListModel class to store list elements. This class implements the ListModel interface and provides the java.util.Vector API as well. Applications that need to provide custom ListModel implementations can subclass AbstractListModel, which provides basic ListDataListener support. For example:
// This list model has about 2^16 elements. Enjoy scrolling.

ListModel bigData = new AbstractListModel() { public int getSize() { return Short.MAX_VALUE; } public Object getElementAt(int index) { return "Index " + index; } }; JList bigDataList = new JList(bigData); // // // // // We don't want the JList implementation to compute the width or height of all of the list cells, so we give it a string that's as big as we'll need for any cell. It uses this to compute values for the fixedCellWidth and fixedCellHeight properties.

bigDataList.setPrototypeCellValue("Index 1234567890");

uses a java.awt.Component, provided by a delegate called the cellRendererer, to paint the visible cells in the list. The cell renderer component is used like a "rubber stamp" to paint each visible row. Each time the JList needs to paint a cell it asks the cell renderer for the component, moves it into place using setBounds() and then draws it by calling its paint method. The default cell renderer uses a JLabel component to render the string value of each component. You can substitute your own cell renderer, using code like this:
JList // Display an icon and a string for each object in the list. class MyCellRenderer extends JLabel implements ListCellRenderer { final static ImageIcon longIcon = new ImageIcon("long.gif"); final static ImageIcon shortIcon = new ImageIcon("short.gif"); // This is the only method defined by ListCellRenderer. // We just reconfigure the JLabel each time we're called. public Component getListCellRendererComponent( JList list, Object value, // value to display int index, // cell index boolean isSelected, // is the cell selected boolean cellHasFocus) // the list and the cell have the focus { String s = value.toString(); setText(s); setIcon((s.length() > 10) ? longIcon : shortIcon); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); setOpaque(true); return this; } } String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data); dataList.setCellRenderer(new MyCellRenderer());

doesn't provide any special support for handling double or triple (or N) mouse clicks however it's easy to handle them using a MouseListener. Use the JList method locationToIndex() to determine what cell was clicked. For example:
JList final JList list = new JList(dataModel); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); System.out.println("Double clicked on Item " + index);

} }; list.addMouseListener(mouseListener); }

Note that in this example the dataList is final because it's referred to by the anonymous MouseListener class. For the keyboard keys used by this component in the standard look and feel (L&F) renditions, see the JList key assignments.

How to Use Lists


A JList presents the user with a group of items, displayed in one or more columns, to choose from. Lists can have many items, so they are often put in scroll panes.

In addition to lists, the following Swing components present multiple selectable items to the user: combo boxes, menus, tables, and groups of check boxes or radio buttons. To display hierarchical data, use a tree. The following figures shows two applications that use lists. This section uses these examples as a basis for the discussions that follow.

ListDialog (used by ListDialogRunner)

ListDemo

Try this: 1. Click the Launch button to run ListDemo using Java Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.

2. Click the Launch button to run ListDialogRunner. Alternatively, to compile and run the example yourself, consult the example index.

3. To bring up the ListDialog, click the Pick a new name... button in the window titled Name That Baby. The resulting dialog is a ListDialog instance that has been customized to have the title Name Chooser. 4. In ListDemo, try adding (hiring) and removing (firing) a few items. This rest of this section discusses the following topics: Creating a Model Initializing a List Selecting Items in a List Adding Items to and Removing Items from a List Writing a Custom Cell Renderer The List API Examples that Use Lists

Creating a Model
There are three ways to create a list model: DefaultListModel everything is pretty much taken care of for you. The examples in this page use DefaultListModel. AbstractListModel you manage the data and invoke the "fire" methods. For this approach, you must subclass AbstractListModel and implement the getSize and getElementAt methods inherited from the ListModel interface. ListModel you manage everything.

Initializing a List
Here is the code from ListDialog.java that creates and sets up its list:
list = new JList(data); //data has type Object[] list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP); list.setVisibleRowCount(-1); ... JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80));

The code passes an array to the list's constructor. The array is filled with strings that were passed in from another object. In our example, the strings happen to be boys' names.

Other JList constructors let you initialize a list from a Vector or from an object that adheres to the ListModel interface. If you initialize a list with an array or vector, the constructor implicitly creates a default list model. The default list model is immutable you cannot add, remove, or replace items in the list. To create a list whose items can be changed individually, set the list's model to an instance of a mutable list model class, such as an instance of DefaultListModel. You can set a list's model when you create the list or by calling the setModel method. See Adding Items to and Removing Items from a List for an example. The call to setSelectionMode specifies how many items the user can select, and whether they must be contiguous; the next section tells you more about selection modes. The call to setLayoutOrientation lets the list display its data in multiple columns. The value JList.HORIZONTAL_WRAP specifies that the list should display its items from left to right before wrapping to a new row. Another possible value is JList.VERTICAL_WRAP, which specifies that the data be displayed from top to bottom (as usual) before wrapping to a new column. The following figures show these two wrapping possibilities, together with the default, JList.VERTICAL.

HORIZONTAL_WRAP

VERTICAL_WRAP

VERTICAL

In combination with the call to setLayoutOrientation, invoking setVisibleRowCount(-1) makes the list display the maximum number of items possible in the available space onscreen. Another common use of setVisibleRowCount is to specify to the lists's scroll pane how many rows the list prefers to display.

Selecting Items in a List


A list uses an instance of ListSelectionModel to manage its selection. By default, a list selection model allows any combination of items to be selected at a time. You can specify a different selection mode by calling the setSelectionMode method on the list. For example, both ListDialog and ListDemo set the selection mode to SINGLE_SELECTION (a constant defined by ListSelectionModel) so that only one item in the list can be selected. The following table describes the three list selection modes: Mode
SINGLE_SELECTION

Description Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first.

SINGLE_INTERVAL_SELECTION

Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first.

MULTIPLE_INTERVAL_SELECTION The default. Any combination of items can be

selected. The user must explicitly deselect items.

No matter which selection mode your list uses, the list fires list selection events whenever the selection changes. You can process these events by adding a list selection listener to the list with the addListSelectionListener method. A list selection listener must implement one method: valueChanged. Here is the valueChanged method for the listener in ListDemo:
public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { //No selection, disable fire button. fireButton.setEnabled(false); } else { //Selection, enable the fire button. fireButton.setEnabled(true); } } }

Many list selection events can be generated from a single user action such as a mouse click. The getValueIsAdjusting method returns true if the user is still manipulating the selection. This particular program is interested only in the final result of the user's action, so the valueChanged method does something only if getValueIsAdjusting returns false.

Because the list is in single-selection mode, this code can use getSelectedIndex to get the index of the just-selected item. JList provides other methods for setting or getting the selection when the selection mode allows more than one item to be selected. If you want, you can listen for events on the list's list selection model rather than on the list itself. ListSelectionDemo is an example that shows how to listen for list selection events on the list selection model and lets you change the selection mode of a list dynamically.

Adding Items to and Removing Items from a List


The ListDemo example that we showed previously features a list whose contents can change. You can find the source code for ListDemo in ListDemo.java. Here is the ListDemo code that creates a mutable list model object, puts the initial items in it, and uses the list model to create a list:
listModel = new DefaultListModel(); listModel.addElement("Jane Doe"); listModel.addElement("John Smith"); listModel.addElement("Kathy Green"); list = new JList(listModel);

This particular program uses an instance of DefaultListModel, a class provided by Swing. In spite of the class name, a list does not have a DefaultListModel unless your program explicitly makes it so. If DefaultListModel does not suit your needs, you can write a custom list model, which must adhere to the ListModel interface.

The following code snippet shows the actionPerformed method for the action listener registered on the Fire button. The bold line of code removes the selected item in the list. The remaining lines in the method disable the fire button if the list is now empty, and make another selection if it is not.
public void actionPerformed(ActionEvent e) { int index = list.getSelectedIndex(); listModel.remove(index); int size = listModel.getSize(); if (size == 0) { //Nobody's left, disable firing. fireButton.setEnabled(false); } else { //Select an index. if (index == listModel.getSize()) { //removed item in last position index--; } list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } }

Here is the actionPerformed method for the action listener shared by the Hire button and the text field:

public void actionPerformed(ActionEvent e) { String name = employeeName.getText(); //User did not type in a unique name... if (name.equals("") || alreadyInList(name)) { Toolkit.getDefaultToolkit().beep(); employeeName.requestFocusInWindow(); employeeName.selectAll(); return; } int index = list.getSelectedIndex(); //get selected index if (index == -1) { //no selection, so insert at beginning index = 0; } else { //add after the selected item index++; } listModel.insertElementAt(employeeName.getText(), index); //Reset the text field. employeeName.requestFocusInWindow(); employeeName.setText(""); //Select the new item and make it visible. list.setSelectedIndex(index); list.ensureIndexIsVisible(index); }

This code uses the list model's insertElementAt method to insert the new name after the current selection or, if no selection exists, at the beginning of the list. If you just wish to add to the end of the list, you can use DefaultListModel's addElement method instead.

Whenever items are added to, removed from, or modified in a list, the list model fires list data events. Refer to How to Write a List Data Listener for information about listening for these events. That section contains an example that is similar to ListDemo, but adds buttons that move items up or down in the list.

Writing a Custom Cell Renderer


A list uses an object called a cell renderer to display each of its items. The default cell renderer knows how to display strings and icons and it displays Objects by invoking toString. If you want to change the way the default renderer display icons or strings, or if you want behavior different than what is provided by toString, you can implement a custom cell renderer. Take these steps to provide a custom cell renderer for a list: Write a class that implements the ListCellRenderer interface. Create an instance of your class and call the list's setCellRenderer using the instance as an argument.

We do not provide an example of a list with a custom cell renderer, but we do have an example of a combo box with a custom renderer and combo boxes

use the same type of renderer as lists. See the example described in Providing a Custom Renderer.

The List API


The following tables list the commonly used JList constructors and methods. Other methods you are most likely to invoke on a JList object are those such as setPreferredSize that its superclasses provide. See The JComponent API for tables of commonly used inherited methods.

Much of the operation of a list is managed by other objects. The items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll pane to handle scrolling. For the most part, you do not need to worry about the models because JList creates them as necessary and you interact with them implicitly with JList's convenience methods. That said, the API for using lists falls into these categories:
Initializing List Data Displaying the List Managing the List's Selection Managing List Data Initializing List Data Method or Constructor JList(ListModel) JList(Object[]) JList(Vector) JList() Purpose Create a list with the initial list items specified. The second and third constructors implicitly create an immutable ListModel; you should not subsequently modify the passedin array or Vector.

void setModel(ListMode l) Set or get the model that contains the contents of the list. ListModel getModel() void setListData(Object Set the items in the list. These methods implicitly create an []) immutable ListModel. void setListData(Vector ) Displaying the List

Method

Purpose

Set or get the visibleRowCount property. For a VERTICAL layout orientation, this sets or gets the preferred number void setVisibleRowCount(i of rows to display without requiring scrolling. For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it nt) int defines how the cells wrap. See the getVisibleRowCount() setLayoutOrientation(int) for more information. The default value of this property is VERTICAL. Set or get the way list cells are laid out. The possible void layout formats are specified by the JList-defined values setLayoutOrientation( VERTICAL (a single column of cells; the default), int) HORIZONTAL_WRAP ("newspaper" style with the content int flowing horizontally then vertically), and VERTICAL_WRAP getLayoutOrientation ("newspaper" style with the content flowing vertically () then horizontally). int getFirstVisibleIndex() Get the index of the first or last visible item. int getLastVisibleIndex() void Scroll so that the specified index is visible within the ensureIndexIsVisible( viewport that this list is in. int) Managing the List's Selection Method Purpose

void Register to receive notification of addListSelectionListener(ListSelection selection changes. Listener) void setSelectedIndex(int) void setSelectedIndices(int[]) void setSelectedValue(Object, boolean) void setSelectionInterval(int, int) int getAnchorSelectionIndex() int getLeadSelectionIndex() Set the current selection as indicated. Use setSelectionMode to set what ranges of selections are acceptable. The boolean argument specifies whether the list should attempt to scroll itself so that the selected item is visible. Get information about the current selection as indicated.

int getSelectedIndex() int getMinSelectionIndex() int getMaxSelectionIndex() int[] getSelectedIndices() Object getSelectedValue() Object[] getSelectedValues() Set or get the selection mode. Acceptable values are: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, or MULTIPLE_INTERVAL_SELECTION (the default), which are defined in ListSelectionModel. Set or get whether any items are selected. Determine whether the specified index is selected. Managing List Data Class or Method Purpose

void setSelectionMode(int) int getSelectionMode()

void clearSelection() boolean isSelectionEmpty() boolean isSelectedIndex(int)

Given the starting index, search through the list for an item that starts with the specified string and return that index (or -1 if the string is not found). The int getNextMatch(String, third argument, which specifies the search direction, can be either Position.Bias.Forward or int, javax.swing.text.Position. Position.Bias.Backward. For example, if you have a Bias) 6-item list, getNextMatch("Matisse", 5, javax.swing.text.Position.Bias.Forward) searches for the string "Matisse" in the item at index 5, then (if necessary) at index 0, index 1, and so on. void Set or get the property that determines whether setDragEnabled(boolean) automatic drag handling is enabled. See Drag and boolean Drop and Data Transfer for more details. getDragEnabled()

JList

Archivos necesarios:

El JList nos permite crear una lista para agregar a nuestras aplicaciones. A diferencia del JComboBox que puede crecer muy fcilmente, el JList es un poco ms difcil de manejar pero nos permite hacer cosas ms interesantes que el JComboBox. Tambin veremos cmo utilizar algunas otras clases que nos van a permitir manejar un JList de una manera ms eficiente por ejemplo para permitir que crezca de manera dinmica. Podemos utilizar listas para mostrar a los jugadores en un juego de mesa o tambin podemos utilizarla para mostrar una lista de contactos. La clase que incluye este trial es un programa que nicamente incluye un JList con los nombres de los empleados de una empresa. El programa nos permite contratar ms empleados y despedirlos segn sea necesario.

Main.java

Cmo utilizar un JList?

Construir un JList es muy sencillo si no queremos que sea dinmico, es decir: si queremos que el usuario no pueda agregar ms items. Para hacerlo basta con declarar un arreglo de String y pasarlo como parmetro al constructor del JList.

Para hacer que el JList tenga una barra de desplazamiento es necesario utilizar una clase auxiliar llamada JScrollPane. Esta clase se va a detallar en algn trial ms adelante, pero por el momento se debe de construir como se ve en la foto. Es importante notar que el JScrollPane es el que se aade a la forma y no la lista en si. Esto es porque el JScollPane contiene a la lista. Para escuchar eventos en una lista (por ejemplo para saber cuando se seleccion un elemento) es necesario importar un nuevo tipo de escuchador de eventos. Primero que nada tenemos que importar la librera: javax.swing.event.* despus la clase tiene que implementar ListSelectionListener y por ltimo tenemos que hacer un mtodo valueChanged() que recibe un objeto ListSelectionEvent. Dentro de este mtodo podemos utilizar la variable ListSelectionEvent para saber cul fue el JList que mand llamar el mtodo mediante el mtodo getSource() que es igual que el que habamos utilizado hasta ahora.

Un paso ms all

Una parte importante de las listas es el poder agregar y eliminar registros. Para hacer esto necesitamos crear un objeto llamado DefaultListModel e iniciar el JList con este objeto en vez de con el arreglo de String como habamos visto en la primera parte. Como podemos ver aqui podemos agregar elementos al DefaultListModel utilizando el mtodo addElement() que recibe un String con el elemento a aadir. Una vez que ya tengamos el DefaultListModel con todos los elementos que queramos es hora de crear la lista con el constructor que recibe el DefaultListModel. Recuerda que la variable listModel que estamos utilizando en el cdigo es un objeto tipo DefaultListModel. Una vez que ya creamos la lista podemos utilizar nuestro DefaultListModel para eliminar los elementos que queramos, si sabemos el ndice en que lugar fueron agregados (que es la misma posicin en la que aparecen en el JList) con el mtodo removeElementAt() que recibe nicamente un nmero que es el ndice a borrar. Tambin hay un

mtodo del JList que nos permite saber qu elemento est seleccionado. El mtodo getSelectedIndex() nos devuelve el ndice del elemento que est seleccionado en ese momento. Entonces, para poder borrar un elemento de un JList podemos utilizar juntos el mtodo para borrar el registro en un ndice y el mtodo que nos devuelve el ndice que est actualmente seleccioando, con lo que podemos borrar el elemento que seleccion el usuario. Si nuestro JList permite elegir ms de un elemento entonces el mtodo getSelectedIndex() no funciona, para leer un poco ms acerca de cmo manejar listas donde se puedan manejar multiples selecciones consulten la clase Main.java que se les da al principio. Tambin es importante saber cmo guardar los datos de un DefaultListModel a un archivo. Tambin hay un mtodo que nos devuelve que tantos elementos se han agregado al DefaultListModel llamado getSize(), este mtodo lo podemos utilizar para hacer un for que guarde desde 0 hasta el tamao todos los registros que encuentre, es ms sencillo manejar este tipo de guardado en archivos de texto por lo que les recomiendo que lo hagan as.

JList

Java Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directlyinstead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.

JList Source Code


import import import import import javax.swing.*; javax.swing.event.ListSelectionEvent; javax.swing.event.ListSelectionListener; java.awt.*; java.awt.event.*;

public class JListDemo extends JFrame { JList list; String[] listColorNames = { "black", "blue", "green", "yellow", "white" }; Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.WHITE }; Container contentpane; public JListDemo() { super("List Source Demo"); contentpane = getContentPane(); contentpane.setLayout(new FlowLayout()); list = new JList(listColorNames); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentpane.add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) {
contentpane.setBackground(listColorValues[list .getSelectedIndex()]);

} public static void main(String[] args) { JListDemo test = new JListDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

} }); setSize(200, 200); setVisible(true);

} Output

Create a JList Component in Java


In this section, you will learn how to create a JList component of swing. JList is a component of GUI. It provides the multiple items in a list and some times it shows the data in multiple columns in a list. Lists are used to select item from the item's group like combo box but the major difference between list and the combo box is that you can select only one item from the combo box since you can select more than one item at once from the list. You can easily add or remove items from or to the JList component of swing. The JList component has been shown in this article below:

This program provides a List. The given List has multiple subjects as items like: Math, Computer, Physics and Chemistry. JList: This is the class which is used to create a list which contains items. This class extends the JComponent class in java swing. There has been using string array values in this program.

Here is the code of program: import javax.swing.*; public class CreateJList{ public static void main(String[] args) { String subject[] = {"Math", "Computer", "Phisics", "Chemestry"}; JFrame frame = new JFrame("Creating a JList Component"); JPanel panel = new JPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JList list = new JList(subject); frame.setUndecorated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); panel.add(list); frame.add(panel); frame.setSize(400,400); frame.setVisible(true); } }

Cdigo de: Seleccin Mltiple


Ejemplos prcticos para la programacin en java. Visualiza el cdigo fuente o descrgalo directamente a tu PC. Estes ejemplos son bsicos para la programar en java y puramente orientativos. Esperemos que te ayuden. Descripcin: Copiar elementos de una JList a otra.
Fichero: PruebaSeleccionMultiple.java

1 // Cmo copiar elementos de una lista a otra. 2 import java.awt.*; 3 import java.awt.event.*; 4 import javax.swing.*; 5 6 public class PruebaSeleccionMultiple extends JFrame 7{ 8 private JList listaColores, listaCopia;

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

private JButton botonCopiar; private final String nombresColores[] = { "Negro", "Azul", "Cyan", "Gris oscuro", "Gris", "Verde", "Gris claro", "Magenta", "Naranja", "Rosa", "Rojo", "Blanco", "Amarillo" };

// configurar GUI public PruebaSeleccionMultiple() { super( "Listas de seleccin mltiple" );

// obtener panel de contenido y establecer su esquema Container contenedor = getContentPane(); contenedor.setLayout( new FlowLayout() );

// establecer objeto JList listaColores listaColores = new JList( nombresColores ); listaColores.setVisibleRowCount( 5 ); listaColores.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); contenedor.add( new JScrollPane( listaColores ) );

// crear botn copiar y registrar su componente de escucha botonCopiar = new JButton( "Copiar >>>" ); botonCopiar.addActionListener(

new ActionListener() { // clase interna annima

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 setSize( 325, 130 ); setVisible( true ); // establecer objeto JList listaCopia listaCopia = new JList( ); listaCopia.setVisibleRowCount( 5 ); listaCopia.setFixedCellWidth( 100 ); listaCopia.setFixedCellHeight( 15 ); listaCopia.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION ); contenedor.add( new JScrollPane( listaCopia ) ); contenedor.add( botonCopiar ); ); // fin de la llamada a addActionListener } // fin de clase interna annima } // manejar evento de botn public void actionPerformed( ActionEvent evento ) { // colocar valores seleccionados en listaCopia listaCopia.setListData( listaColores.getSelectedValues() );

61 62 63 64 65 66 67 68

} // fin del constructor PruebaSeleccionMultiple

public static void main( String args[] ) { PruebaSeleccionMultiple aplicacion = new PruebaSeleccionMultiple(); aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }

69 } // fin de la clase PruebaSeleccionMultiple

Cdigo de: Lneas Rectngulos y valos


Ejemplos prcticos para la programacin en java. Visualiza el cdigo fuente o descrgalo directamente a tu PC. Estes ejemplos son bsicos para la programar en java y puramente orientativos. Esperemos que te ayuden. Descripcin: Dibujo de lneas rectngulos y valos con la clase Graphics
Fichero: LineasRectsOvalos.java

1 // Dibujo de lneas, rectngulos y valos. 2 import java.awt.*; 3 import javax.swing.*; 4 5 public class LineasRectsOvalos extends JFrame { 6 7 8 9 // establecer la cadena de la barra de ttulo y dimensiones de la ventana public LineasRectsOvalos() {

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 }

super( "Dibujo de lneas, rectngulos y valos" );

setSize( 400, 165 ); setVisible( true );

// mostrar varias lneas, rectngulos y valos public void paint( Graphics g ) { super.paint( g ); // llamar al mtodo paint de la superclase

g.setColor( Color.RED ); g.drawLine( 5, 30, 350, 30 );

g.setColor( Color.BLUE ); g.drawRect( 5, 40, 90, 55 ); g.fillRect( 100, 40, 90, 55 );

g.setColor( Color.CYAN ); g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); g.drawRoundRect( 290, 40, 90, 55, 20, 20 );

g.setColor( Color.YELLOW ); g.draw3DRect( 5, 100, 90, 55, true ); g.fill3DRect( 100, 100, 90, 55, false );

36 37 38 39 40 41 42 43 44 45 46 47 48 }

g.setColor( Color.MAGENTA ); g.drawOval( 195, 100, 90, 55 ); g.fillOval( 290, 100, 90, 55 );

} // fin del mtodo paint

// ejecutar la aplicacin public static void main( String args[] ) { LineasRectsOvalos aplicacion = new LineasRectsOvalos(); aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

49 } // fin de la clase LineasRectsOvalos

MOSTRAR RECTANGULO CON Rectangle


hola!como estan?tengo esto: DefaultListModel modelo = new DefaultListModel(); if (listaLibros== null) { listaLibros = new JList(modelo); listaLibros.setBounds(new Rectangle(228, 60, 188, 190)); } listaLibros.setListData(Libreria.getInstancia_Libreria().getListaDeLibros().toArray()); y no se como hacer para que me muestre los datos en la pantalla. me aparece un rectangulo blanco nomas.que tengo mal bueno, espero que me puedan ayudar.

CREAR LA CLASE RECTANGULO Volvemos de nuevo al estudio de la clase Rectangulo que contiene un subobjeto de la clase Punto. A dichas clases se les ha aadido la redefinicin de la funcin toString miembro de la clase base Object (esta redefinicin no es necesaria aunque es ilustrativa para explicar el

comportamiento de un objeto compuesto). Como podemos apreciar, ambas clases implementan el interface Serializable. En el cuadro que sigue se muestra parte del cdigo que define la clase Punto.
public class Punto implements java.io.Serializable{ private int x; private int y; //otros miembros... public String toString(){ return new String("("+x+", "+y+")"); } }

La definicin de la clase Rectangulo se muestra en el siguiente cuadro


public class Rectangulo implements java.io.Serializable{ private int ancho ; private int alto ; private Punto origen; //otras funciones miembro... public String toString(){ String texto=origen+" w:"+ancho+" h:"+alto; return texto; }

Como podemos observar, en la definicin de toString de la clase Rectangulo se hace una llamada implcita a la funcin toString miembro de la clase Punto. La composicin como se ha estudiado permite reutilizar el cdigo existente. Para guardar en un archivo un objeto de la clase Rectangulo hay que seguir los mismos pasos que para guardar un objeto de la clase Lista o de la clase Cliente.
Rectangulo rect=new Rectangulo(new Punto(10,10), 30, 60); ObjectOutputStream salida=new ObjectOutputStream(new FileOutputStream("figura.obj")); salida.writeObject("guardar un objeto compuesto\n"); salida.writeObject(rect); salida.close();

Para reconstruir un objeto de la clase Rectangulo a partir de los datos guardados en el archivo hay que seguir los mismos pasos que en los dos ejemplos previos.
ObjectInputStream entrada=new ObjectInputStream(new FileInputStream("figura.obj")); String str=(String)entrada.readObject(); Rectangulo obj1=(Rectangulo)entrada.readObject(); System.out.println("------------------------------"); System.out.println(str+obj1); System.out.println("------------------------------"); entrada.close();

En el caso de que nos olvidemos de implementar el interface Serializable en la clase Punto que describe el subobjeto de la clase Rectangulo, se lanza una excepcin, imprimindose en la consola.

java.io.NotSerializableException: archivo5.Punto.

HERENCIA CON FIGURAS COMO RECTANGULO Y CIRCUNFERENCIA


En el apartado anterior hemos examinado la composicin, ahora examinemos la herencia. En el captulo de la herencia examinamos una jerarqua formada por una clase base denominada Figura y dos clases derivadas denominadas Circulo y Rectangulo. Como podemos observar en el cuadro adjunto se han hecho dos modificaciones. La clase base Figura implementa el interface Serializable y en la clase Circulo en vez de usar el nmero PI proporcionado por la clase Math, definimos una constante esttica PI con una aproximacin de 4 decimales. De este modo probamos el comportamiento de un miembro esttico en el proceso de serializacin. Para serializar objetos de una jerarqua solamente la clase base tiene que implementar el interface Serializable
public abstract class Figura implements java.io.Serializable{ protected int x; protected int y; public Figura(int x, int y) { this.x=x; this.y=y; } public abstract double area(); } class Circulo extends Figura{ protected double radio; private static final double PI=3.1416; public Circulo(int x, int y, double radio){ super(x,y); this.radio=radio; } public double area(){ return PI*radio*radio; } } class Rectangulo extends Figura{ protected double ancho, alto; public Rectangulo(int x, int y, double ancho, double alto){ super(x,y); this.ancho=ancho; this.alto=alto; } public double area(){ return ancho*alto; } }

Vamos a serializar dos objetos uno de la clase Rectangulo y otro de la clase Circulo, y a continuacin reconstruiremos dichos objetos. Una vez de que dispongamos de los objetos llamaremos a las funciones area para calcular el rea de cada una de las figuras. Para guardar en el archivo figura.obj un objeto fig1 de la clase Rectangulo y otro objeto fig2 de la clase Circulo, se siguen los mismos pasos que hemos estudiado en apartados anteriores
Figura fig1=new Rectangulo(10,15, 30, 60); Figura fig2=new Circulo(12,19, 60); ObjectOutputStream salida=new ObjectOutputStream(new FileOutputStream("figura.obj")); salida.writeObject("guardar un objeto de una clase derivada\n"); salida.writeObject(fig1); salida.writeObject(fig2); salida.close();

Fijarse que fig1 y fig2 son dos referencias de la clase base Figura en la que se guardan objetos de las clases derivadas Rectangulo y Circulo, respectivamente Para leer los datos guardados en el archivo figura.obj y reconstruir dos objetos obj1 y obj2 de las clases Rectangulo y Circulo respectivamente, se procede de forma similar a la estudiada en los apartados previos.
ObjectInputStream entrada=new ObjectInputStream(new FileInputStream("figura.obj")); String str=(String)entrada.readObject(); Figura obj1=(Figura)entrada.readObject(); Figura obj2=(Figura)entrada.readObject(); System.out.println("------------------------------"); System.out.println(obj1.getClass().getName()+" origen ("+obj1.x+", "+obj1.y+")"+" area="+obj1.area()); System.out.println(obj2.getClass().getName()+" origen ("+obj2.x+", "+obj2.y+")"+" area="+obj2.area()); System.out.println("------------------------------"); entrada.close();

Fijarse que obj1 y obj2 son referencias a la clase base Figura. Sin embargo, cuando obj1 llama a la funcin area nos devuelve (correctamente) el rea del rectngulo y cuando, obj2 llama a la funcin area devuelve el rea del crculo. Fijarse tambin que aunque PI es un miembro esttico de la clase Circulo, se reconstruye el objeto obj2 con el valor del miembro esttico con el que se calcula el rea del crculo

La clase Punto
La clase Punto tiene dos miembros dato, la abscisa x y la ordenada y de un punto del plano. Definimos dos constructores uno por defecto que sita el punto en el origen, y otro constructor explcito que proporciona las coordenadas x e y de un punto concreto.
public class Punto { int x; int y; //funciones miembro }

El constructor explcito de la clase Punto podemos escribirlo de dos formas


public Punto(int x1, int y1) { x = x1; y = y1; }

Cuando el nombre de los parmetros es el mismo que el nombre de los miembros datos escribimos
public Punto(int x, int y) { this.x = x; this.y = y; }

this.x que est a la izquierda y que recibe el dato x que se le pasa al constructor se refiere al miembro dato, mientras que x que est a la derecha es el parmetro. this es una palabra reservada que guarda una refrencia al objeto propio, u objeto actual. Tendremos ocasin a lo largo del curso de encontrar esta palabra en distintas situaciones. La funcin miembro desplazar simplemente cambia la posicin del punto desde (x, y) a (x+dx, y+dy). La funcin desplazar cuando es llamada recibe en sus dos parmetros dx y dy el desplazamiento del punto y actualiza las coordenadas x e y del punto. La funcin no retorna ningn valor
public void desplazar(int dx, int dy){ x+=dx; y+=dy; }

Para crear un objeto de la clase Punto cuyas coordenadas x e y valgan repectivamente 10 y 23 escribimos
Punto p=new Punto(10, 23);

Para desplazar el punto p 10 unidades hacia la izquierda y 40 hacia abajo, llamamos desde el objeto p a la funcin desplazar y le pasamos el desplazamiento horizontal y vertical.
p.desplazar(-10, 40);

El cdigo completo de la clase Punto, es el siguiente


public class Punto { int x = 0; int y = 0; public Punto(int x, int y) { this.x = x; this.y = y; } public Punto() { x=0; y=0; } void desplazar(int dx, int dy){ x+=dx; y+=dy; } }

La clase Rectangulo
La clase Rectangulo tiene como miembros dato, el origen que es un objeto de la clase Punto y las dimensiones ancho y alto.
public class Rectangulo { Punto origen; int ancho ; int alto ; //funciones miembro }

El constructor por defecto, crea un rectngulo situado en el punto 0,0 y con dimensiones nulas
public Rectangulo() { origen = new Punto(0, 0); ancho=0; alto=0; }

El constructor explcito crea un rectngulo situado en un determinado punto p y con unas dimensiones que se le pasan en el constructor
public Rectangulo(Punto p, int w, int h) { origen = p; ancho = w; alto = h; }

Podemos definir otros constructores en trminos del constructor explcito usando la palabra reservada this.
public Rectangulo(Punto p) { this(p, 0, 0); } public Rectangulo(int w, int h) { this(new Punto(0, 0), w, h); }

El primero crea un rectngulo de dimensiones nulas situado en el punto p. El segundo, crea un rectngulo de unas determinadas dimensiones situndolo en el punto 0, 0. Dentro del cuerpo de cada constructor se llama al constructor explcito mediante this pasndole en sus parmetros los valores apropiados. Para desplazar un rectngulo, trasladamos su origen (esquina superior izquierda) a otra posicin, sin cambiar su anchura o altura. Desde el objeto origen, llamamos a la funcin desplazar miembro de la clase Punto
void desplazar(int dx, int dy) { origen.desplazar(dx, dy); }

El cdigo completo de la nueva clase Rectangulo, es el siguiente.


public class Rectangulo { Punto origen; int ancho ; int alto ; public Rectangulo() {

} public Rectangulo(Punto p) { this(p, 0, 0); } public Rectangulo(int w, int h) { this(new Punto(0, 0), w, h); } public Rectangulo(Punto p, int w, int h) { origen = p; ancho = w; alto = h; } void desplazar(int dx, int dy) { origen.desplazar(dx, dy); } int calcularArea() { return ancho * alto; }

origen = new Punto(0, 0); ancho=0; alto=0;

Objetos de la clase Rectangulo


Para crear un rectngulo rect1 situado en el punto (0, 0) y cuyas dimensiones son 100 y 200 escribimos
Rectangulo rect1=new Rectangulo(100, 200);

Para crear un rectngulo rect2, situado en el punto de coordenadas 44, 70 y de dimensiones nulas escribimos
Punto p=new Punto(44, 70); Rectangulo rect2=new Rectangulo(p);

O bien, en una sla lnea


Rectangulo rect2=new Rectangulo(new Punto(44, 70));

Para desplazar el rectngulo rect1 desde el punto (100, 200) a otro punto situado 40 unidades hacia la derecha y 20 hacia abajo, sin modificar sus dimensiones, escribimos
rect1.desplazar(40, 20);

Para hallar y mostrar el rea del rectngulo rect1 podemos escribir


System.out.println("el rea es "+rect1.calcularArea());

Para hallar el rea de un rectngulo de 100 unidades de largo y 50 de alto y guardar el resultado en la variable entera areaRect, escribimos en una sla lnea.
int areaRect=new Rectangulo(100, 50).calcularArea(); public class RectanguloApp { public static void main(String[] args) { Rectangulo rect1=new Rectangulo(100, 200); Rectangulo rect2=new Rectangulo(new Punto(44, 70)); Rectangulo rect3=new Rectangulo(); rect1.desplazar(40, 20);

System.out.println("el rea es "+rect1.calcularArea()); int areaRect=new Rectangulo(100, 50).calcularArea(); System.out.println("el rea es "+areaRect); } } }

MOSTRAR UNA CAJA DE TEXTO EN UN LISTBOX


Supongamos que tengo un archivo en txt, en este se ve asi: Nombre Telefono Pedro 545668 Carlos 2646468 Rosa 294686 .... ...... .... ...... quiero mostrar esto usando una lsita o list box en java,

El cdigo sera algo as: Primero hay que crear una clase que extiende de AbstractListModel MyListModel extends AbstractListModel { Vector _data=new Vector(); public MyListModel(String fichero){ java.io.BufferedReader reader= new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(fichero))); String linea=null; while (null! =(linea=reader. ReadLine())){ _data. Add(linea); } } public int getSize() { return Short. MAX_VALUE; } public Object getElementAt(int index) { _data. Get(index); }

};

Y luego, para crear la lista: JList lista=new JList(new MyListModel("Nombrearchivo. Txt"));

EJEMPLOS DE LISTA
Las listas (List) aparecen en los interfaces de usuario para facilitar a los operadores la manipulacin de muchos elementos. Se crean utilizando mtodos similares a los de los botones Choice. La lista es visible todo el tiempo, utilizndose una barra de desplazamiento para visualizar los elementos que no caben en el rea que aparece en la pantalla.

El ejemplo siguiente, Lista.java, crea una lista que muestra cuatro lneas a la vez y no permite seleccin mltiple.

import java.awt.*; import java.applet.Applet;

public class Lista extends Applet {

public void init() { List l = new List( 4,false );

l.addItem( "Mercurio" ); l.addItem( "Venus" ); l.addItem( "Tierra" ); l.addItem( "Marte" ); l.addItem( "Jupiter" ); l.addItem( "Saturno" ); l.addItem( "Neptuno" ); l.addItem( "Urano" ); l.addItem( "Pluton" ); add( l ); }

public boolean action( Event evt,Object obj ) { if( evt.target instanceof List ) System.out.println( "Entrada de la Lista: " + obj );

return true; } }

Para acceder a los elementos seleccionados se utilizan los mtodos getSelectedItem() o getSelectedItems(). Para listas de seleccin simple, cualquier seleccin con doble-click en la lista disparar el mtodo action() de la misma forma que con los eventos de seleccin en mens.

En el applet siguiente, ListaMult.java, se permite al usuario seleccionar varios elementos de los que constituyen la lista. En la figura se muestra la apariencia de una seleccin mltiple en este applet.

import java.awt.*; import java.applet.Applet;

public class ListaMult extends Applet { List lm = new List( 6,true );

public void init() { Button boton = new Button( "Aceptar" );

lm.addItem( "Mercurio" ); lm.addItem( "Venus" ); lm.addItem( "Tierra" ); lm.addItem( "Marte" ); lm.addItem( "Jupiter" ); lm.addItem( "Saturno" ); lm.addItem( "Neptuno" );

lm.addItem( "Urano" ); lm.addItem( "Pluton" ); add( lm ); add( boton ); }

public boolean action( Event evt,Object obj ) { if( evt.target instanceof Button ) { if( "Aceptar".equals( obj ) ) { String seleccion[];

seleccion = lm.getSelectedItems(); for( int i=0; i < seleccion.length; i++ ) System.out.println( seleccion[i] ); } }

return true; } }

En este caso de la seleccin mltiple en una lista, utilizamos un evento externo para disparar las acciones asociadas a la lista. En el ejemplo, hemos incluido un botn para generar el evento que hace que el applet recoja los elementos que hay seleccionados en la lista.

COMO USAR UN JLIST CON IMGENES


El JList es un componente que permite seleccionar un o varios items de un panel desplegable. Es muy util cuando queremos mostrar el contendido de una lista para que el usuario pueda seleccionar dichos items.

Todo JList esta compuesto por un DefaultListModel, es el que define el modelo de la JList, es decir, el que agregar y borrar los items de la JList Como agregar elementos a un JList? Hay varias formas de hacerlo, una de ellas es usar el DefaultListModel, ya que tiene el mtodo addElement que inserta un elemento a la vez: view source print?
1 JList lista = new JList(); 2 DefaultListModel modelo;

3 4 lista.setModel(modelo);

5 modelo.addElement("uno"); 6 modelo.addElement("dos");

El mtodo addElement recibe por parmetro un objeto de tipo Object, esto lo podemos aprovechar para insertar tambien imgenes:

view source print?


1 //se crea un imagen a partir de una ruta absoluta del proyecto donde se encuentra la imagen fisica

2 ImageIcon imagen = new ImageIcon(getClass().getResource("/imagenes/imagen.png"));

3 4 //se inserta la imagen en el modelo

5 modelo.addElement(imagen);

Como eliminar elementos de un JList? Se pueden eliminar elementos de cualquier posicin, incluso, se puede vaciar la lista, sigamos trabajando con el modelo de la JList: view source print?
1 //elimina el primer elemento de la JList 2 modelo.removeElementAt(0);

3 4 //Vaca la JList

5 modelo.clear();

Como alinear los items en la JList? Para darle a los items de la JList un alineamiento especfico se debe de crear un objeto de tipo UIResource, sta propiedad permite darle esa caracterstica a todas las celdas de la JList: view source print?
1 UIResource posicion = new UIResource(); 2

3 //se alinean las celdas a la izquierda 4 posicion.setHorizontalAlignment(SwingConstants.RIGHT);

5 6 lista.setCellRenderer(posicion);

Las constantes de posicin son: * SwingConstants.LEFT * SwingConstants.RIGHT * SwingConstants.CENTER

JList con Iconos


Ahora veremos como lo que vimos anteriormente tambin lo podemos aplicar a otros componentes no solo a los JComboBox, este post lo hago a peticin de usuario que

dejo su comentario en la entrada sobre un filtro para un JList, pueden ver la entrada y el comentario desde aqu.

Imgenes

Cdigo Clase Principal


package Clases;

import java.awt.FlowLayout; import javax.swing.JApplet; import javax.swing.JList;

public class Principal extends JApplet { JList lista; public void init(){ lista=new JList(); Object datos[]=new Object[4]; datos[0]="Elemento 1"; datos[1]="Elemento 2"; datos[2]="Java Zone"; datos[3]="Elemento 3"; lista.setListData(datos); RenderLista rl=new RenderLista(); lista.setCellRenderer(rl); add(lista); } }

Clase RenderLista

package Clases;

import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.util.Hashtable;

import javax.swing.*;

public class RenderLista extends JLabel implements ListCellRenderer{ Hashtable<object, imageicon> elementos; ImageIcon icononulo=new ImageIcon(this.getClass().getResource("../Iconos/imagen nulo.png")); public RenderLista(){ elementos=new Hashtable<object, imageicon>(); ImageIcon icono1=new ImageIcon(this.getClass().getResource("../Iconos/imagen 1.png")); ImageIcon icono2=new ImageIcon(this.getClass().getResource("../Iconos/imagen 2.png")); ImageIcon icono3=new ImageIcon(this.getClass().getResource("../Iconos/imagen 3.png")); elementos.put("Elemento 1", icono1); elementos.put("Elemento 2", icono2); elementos.put("Elemento 3", icono3); }

@Override public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) { if(elementos.get(value)!=null){ setIcon(elementos.get(value)); setText(""+value); if(isSelected){ setFont(new Font("Verdana",Font.BOLD,16)); }else{ setFont(null);

} }else{ setIcon(icononulo); setText(""+value); if(isSelected){ setFont(new Font("Verdana",Font.BOLD,16)); }else{ setFont(null); } } return this; } } El cdigo es muy parecido a la entrada anterior sobre iconos en un JComboBox, pero de todas formas har la explicacin. La clase principal lo que hace es crear un JList, crea un vector de Objects para insertarlo al JList y ademas creamos un objeto RenderLista el cual se encarga de todo. Luego le mando dicho objeto a la lista con el mtodo setCellRenderer(); de la clase JList.

La clase RenderLista crea un HashTable para almacenar los iconos predefinidos, ademas esta clase hereda de JLabel para facilitarnos el uso de Iconos, y tambin se implementa la interfaz ListCellRenderer la cual posee un mtodo que debemos implementar y es el mtodo que nos permite devolver lo que queramos, en este caso un JLabel, lo que se devuelva debe heredar de Component.

Lo que hacemos en el mtodo es comparar lo que se aade a la lista para ver si esta en la coleccin de los iconos predefinidos, si es as se coloca el icono indicado y sino se coloca un icono por defecto. Ademas en este mtodo indicamos que si el elemento es seleccionado que la fuente cambie a Verdana, se ponga en negrita y aumente de tamao.

Cmo utilizar la Clase Lists


Un JList le presenta al usuario un grupo de tems para elegir. Los tems pueden ser cualquier Object. Normalmente son un String. Un lista puede

tener muchos tems, o podra crecer hasta tenerlos. Cmo la mayora de las listas se sitan dentro de paneles desplazables, JList es una clase scroll-savvy.

Adems de las listas, los siguientes componentes Swing tambin presentan mltiples tems seleccionables al usuario: check boxes, combo boxes,menus, radio buttons, y tables. Slos los checkbox, las tablas, y las listas permiten seleccionar varios tems a la vez. Aqu podemos ver una imagen de una aplicacin que utiliza JList para mostrar los nombres de las imgenes a ver.

Intenta esto: 1. Compila y ejecuta la aplicacin. El cdigo fuente est en SplitPaneDemo.java. imagenames.properties proporciona los nombres de las imgenes para ponerlos en el JList. 2. Elige una imagen de la lista. Utiliza las barras de desplazamiento para ver ms nombres. Abajo est el cdigo de SplitPaneDemo.java que crea y configura la lista:
...where member variables are declared this Vector is initialized from a properties file... static Vector imageList; ...where the GUI is created... // Create the list of images and put it in a scroll pane JList listOfImages = new JList(imageList); listOfImages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listOfImages.setSelectedIndex(0); listOfImages.addListSelectionListener(this); JScrollPane listScrollPane = new JScrollPane(listOfImages);

El cdigo utiliza un objeto Vector para proporcionar una lista con los tems iniciales. Tambin podemos inicializar una lista con un array o con un objeto ListModel.

En este ejemplo, el Vector contiene strings obtenidas desde un fichero de propiedades. Sin embargo, los valores de la lista pueden ser cualquier Object, en cuyo caso el mtodo toString de la clase Object proporciona el texto a mostrar. Para mostrar un tem como una imagen u otro valor no-texto, debemos proporcionar una celta personalizada con setCellRenderer. Por defecto, una lista permite que cualquier combinacin de tems sea seleccionada a la vez. Podemos utilizar un valor por defecto diferente utilizando el mtodo setSelectionMode. Por ejemplo, SplitPaneDemo configura el modo de seleccin a SINGLE_SELECTION (una constante definida por ListSelectionModel) para que slo pueda seleccionarse un tem de la lista. La siguiente lista describe los tres modos de seleccin disponibles.
Modo SINGLE_SELECTION Descripcin Slo un tem de la lista puede ser seleccionado. Cuando el usuario selecciona un tem, cualquier tem anteriormente seleccionado se deselecciona primero. Ejemplo

SINGLE_INTERVAL_SELE Se pueden seleccionar varios tems CTION contiguos. Cuando el usuario empieza una nueva seleccin, cualquier tem anteriormente seleccionado se deselecciona primero. MULTIPLE_INTERVAL_SE El valor defecto. Se puede seleccionar LECTION cualquier combinacin de tems. El usuario debe deseleccionar explcitamente los tems.

No importa el modo de seleccin que utiliza la lista, siempre dispara eventos "list selection" cuando cambia la seleccin. Se pueden procesar esos eventos aadiendo un Oyente de "list selection" a la lista con el mtodo addListSelectionListener. Un oyente de 'list selection' debe implementar un mtodo : valueChanged. Aqu podemos ver el mtodo valueChanged para el oyente de SplitPaneDemo:

public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList)e.getSource(); if (theList.isSelectionEmpty()) { picture.setIcon(null); } else { int index = theList.getSelectedIndex(); ImageIcon newImage = new ImageIcon("images/" + (String)imageList.elementAt(index)); picture.setIcon(newImage); picture.setPreferredSize(new Dimension(newImage.getIconWidth(), newImage.getIconHeight() ) } } picture.revalidate();

);

Observa que el mtodo valueChanged slo actualiza la imagen si getValueIsAdjusting devuelve false. La mayora de los eventos 'list selection' pueden ser generados desde una simple accin del usuario como una pulsacin del ratn. Este programa particular slo est interesado en el resultado final de la accin del usuario.

Cmo la lista esta en modo de seleccin sencillo, este cdigo puede utilizar getSelectedIndex para obtener el ndice slo del ndice seleccionado. JList proporciona otros mtodos para Seleccionar u Obtener la Seleccin cuando el modo de seleccin permite seleccionar ms de un tem. Por ejemplo, cambiemos el modo de seleccin de una lista dinmicamente, podemos ver Ejemplos de Manejos de Eventos 'List Selection'.
El API List Las siguientes tablas listan los mtodos y constructores ms utilizados de JList. Otros mtodos tiles estn definidos por las clases JComponent y Component.

Muchas de las operaciones de una lista estn manejadas por otros objetos. Por ejemplo, los tems de la lista estn manejados por un objeto ListModel, la seleccin est manejada por un objeto ListSelectionModel, y la mayora de los programas ponen una lista en un panel desplazable para menajar el desplazamiento. No tenemos que preocuparnos de la mayor parte de estos objetos auxiliares, porque JList los crea cuando son necesarios, y nosotros interactuamos con ellos implicitamente con los mtodos de conveniencia de JList. Cmo se ha dicho, el API para utilizar Lists de divide en estas categoras:
Seleccionar los tems de una Lista

Manejar la Seleccin de una Lista Trabajar con un ScrollPane Seleccionar los tems de una Lista Mtodo Propsito Crea una lista con los tems especificados. El segundo y tercer constructores crean implicitamente un ListModel. Selecciona u obtiene el modelo que contiene el contenido de la lista. Podemos modificar dinmicamente el contenido de la lista llamado a los mtodos con el objeto devuelto por getModel. Selecciona los tems de la lista. Estos mtodos crean implcitamente un ListModel.

JList(ListModel) JList(Object[]) JList(Vector) void setModel(ListModel) ListModel getModel() void setListData(Object[]) void setListData(Vector)

Manejar la Seleccin de una Lista Mtodo Propsito

void Registra para recibir notificacin de los cambios addListSelectionListener( de seleccin. ListSelectionListener) void setSelectedIndex(int) void setSelectedIndices(int[]) void setSelectedValue(Object, boolean) void setSelectedInterval(int, int) int getSelectedIndex() int getMinSelectionIndex() int getMaxSelectionIndex()

Configura la seleccin actual como indicada. Utiliza el mtodo setSelectionMode para los rangos de selecciones aceptables. El argumento booleano especifica su la lista debera intentar desplazarse a s misma para que el tem seleccionado sea visible.

Obtiene informacin sobre la seleccin actual.

int[] getSelectedIndices() Object getSelectedValue() Object[] getSelectedValues() void setSelectionMode(int) int getSelectionMode() void clearSelection() boolean isSelectionEmpty() boolean isSelectedIndex(int) Selecciona u obtiene el modod de seleccin. Los valores aceptables son: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, o MULTIPLE_INTERVAL_SELECTION. Selecciona u obtiene si hay algn tem seleccionado. Determina si el ndice especficado est seleccionado. Trabajar con un Scroll Pane Mtodo void ensureIndexIsVisible(int) int getFirstVisibleIndex() int getLastVisibleIndex() void setVisibleRowCount(int) int getVisibleRowCount() Propsito Desplaza para que el ndice especificado sea visible dentro del recuadro de la lista. Obtiene el ndice del primer o el ltimo elemento visible de la lista. Selecciona u obtiene cantas filas de la lista son visibles.

Cmo escribir un Oyente de List Selection


Los eventos List selection ocurren cuando una seleccin en una list o una table cambia o acaba de cambiar. Los eventos List selection son disparados por un objeto que implementa el interface ListSelectionModel.

Para detectar un evento list selection debemos registrar un oynete con el objeto selection model apropiado. La clase JList tambin ofrece la opcin de registrar un oyente sobre la propia lista, mejor que directamente al selection model de la lista.

Mtodos de Evento List Selection El interface ListSelectionListener slo tiene un mtodo y por lo tanto ni tiene la correspondiente clase adaptador. Aqu est el mtodo: void valueChanged(ListSelectionEvent) Se le llama cuando cambia la seleccin del componente escuchado, tambin se la llama despus de que la seleccin haya cambiado. Ejemplos de Manejo de Eventos List Selection La seccin Cmo usar Lists proporciona un ejemplo de un oyente que escucha los eventos de una lista single-selection (no del selection model de la lista).

Esta seccin proporciona un ejemplo que mustra cmo escuchar este tipo de eventos en un selection model. El selection model es compartido por un lista y una tabla. Dinmicamente podemos cambiar el modo de seleccin a uno de los tres modos soportados:
single selection single interval selection multiple interval selection

Aqu podmeos ver una imgen del ejemplo ejecutndose:

Prueba esto: 1. Compila y ejecuta la aplicacin. El cdigo fuente est en ListSelectionDemo.java.

2. Selecciona y deselecciona items de la lista y de la tabla. Los comandos requeridos de ratn y de teclado para seleccionar tems dependen del "aspecto y comportamiento". Para Metal, pulsa el botn izquierdo delr atn para empezar una seleccin, usa la tecla Shift para extender una seleccin contiga, y usa la tecla Control para extender una seleccin discontiga. Arrastrar el ratn mueve o extiende la seleccin dependiendeo del modo de seleccin. Aqu est el cdigo de ListSelectionDemo.java que configura el modelo de seleccin y le aade un oyente:
...//where the member variables are defined JList list; JTable table; ...//in the init method: listSelectionModel = list.getSelectionModel(); listSelectionModel.addListSelectionListener( new SharedListSelectionHandler()); ... table.setSelectionModel(listSelectionModel);

Y aqu est el cdigo para el oyente, que funciona para todos los modos de seleccin posibles:
class SharedListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { ListSelectionModel lsm = (ListSelectionModel)e.getSource(); int firstIndex = e.getFirstIndex(); int lastIndex = e.getLastIndex(); boolean isAdjusting = e.getValueIsAdjusting(); output.append("Event for indexes " + firstIndex + " - " + lastIndex + "; isAdjusting is " + isAdjusting + "; selected indexes:"); if (lsm.isSelectionEmpty()) { output.append(" <none>"); } else { // Find out which indexes are selected. int minIndex = lsm.getMinSelectionIndex(); int maxIndex = lsm.getMaxSelectionIndex(); for (int i = minIndex; i <= maxIndex; i++) { if (lsm.isSelectedIndex(i)) { output.append(" " + i); } } } output.append(newline);

} }

El mtodo valueChanged muestra el primer y ltimo ndices reportados por el evento, el valor de la bandera isAdjusting del evento, y el indice actualmente seleccionado.

Observa que el primer y tlimo indices reportados por el eventos indican el rango inclusivo de tems para los que la seleccin ha cambiado. Si el modo de seleccin es multiple interval selection algunos tems dentro del rango podran no haber cambiado. La bandera isAdjusting es true si el usuario todava est manipulando la seleccin, y false si el usuario ha terminado de modificar la seleccin. El objeto ListSelectionEvent pasado dentro de valueChanged indica slo que la seleccin ha cambiado. El evento no contiene informacin sobre la seleccin actual. Por eso, este mtodo le pide al selection model que se imagine la seleccin actual.
Nota: La salida de este programa depende de la verin Swing que estemos utilizando. Swing 1.0.x contiene varios bugs y la operacin de listas y tablas era inconsistente. Las versiones posteriores de Swing corrigieron estos problemas.

La clase ListSelectionEvent Cada mtodo de evento list selection tiene un slo parmetro: un objeto ListSelectionEvent. Este objeto le dice al oyente que la seleccin ha cambiado. Un evento list selecton puede indicar un cambio en la seleccin de mltiples tems, discontigos de la lista.

Para obtener la fuente de un ListSelectionEvent, se usa el mtodo getSource, que ListSelectionEvent hereda de EventObject. Si registramos un oyente de list selection directamente sobre una lista, la fuente de cada evento ser la propia lista. De otra forma, sera el selection model. La clase ListSelectionEvent define los siguientes mtodos:
int getFirstIndex() Devuelve el ndice del primer tem cuyo valor de seleccin ha cambiado. Observa que para selecciones de intervalo mltiple, el primer y ltimo tems es seguro que han cambiado, pero los tems que hay entre medias podran no haberlo hecho. int getLastIndex()

Devuelve el ndice del ltimo tem cuyo valor de seleccin ha cambiado. Observa que para selecciones de intervalo mltiple, el primer y ltimo tems es seguro que han cambiado, pero los tems que hay entre medias podran no haberlo hecho. int getValueIsAdjusting() Devuelve true si se est modificando todava la seleccin. Muchos oyentes de list selectionslo estn intereados en el estado final de la seleccin y pueden ignorar eventos cuando este mtodo devuelve true.

Anda mungkin juga menyukai