Java How to Read Text File Into Jlist
A JList
presents the user with a grouping of items, displayed in ane 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: philharmonic boxes, menus, tables, and groups of check boxes or radio buttons. To display hierarchical data, utilise a tree.
The post-obit figures shows two applications that apply lists. This department uses these examples equally a footing for the discussions that follow.
Try this:
- Click the Launch button to run ListDemo using Java™ Web Start (download JDK seven or later). Alternatively, to compile and run the case yourself, consult the example index.
- Click the Launch push to run ListDialogRunner. Alternatively, to compile and run the instance yourself, consult the example index.
- To bring up the ListDialog, click the Pick a new name... button in the window titled Name That Infant.
The resulting dialog is a ListDialog instance that has been customized to have the title Proper name Chooser. - 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 Prison cell Renderer
- The List API
- Examples that Utilize Lists
Creating a Model
In that location are iii ways to create a listing model:
- DefaultListModel — everything is pretty much taken intendance of for you lot. The examples in this folio employ
DefaultListModel
. - AbstractListModel — you manage the data and invoke the "burn down" methods. For this approach, you must subclass
AbstractListModel
and implement thegetSize
andgetElementAt
methods inherited from theListModel
interface. - ListModel — you manage everything.
Initializing a Listing
Hither is the code from ListDialog.java
that creates and sets up its list:
listing = new JList(information); //data has type Object[] list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP); list.setVisibleRowCount(-ane); ... JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, lxxx));
The code passes an assortment to the list's constructor. The array is filled with strings that were passed in from another object. In our instance, 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 assortment or vector, the constructor implicitly creates a default list model. The default list model is immutable — y'all cannot add together, remove, or replace items in the list. To create a listing whose items can exist changed individually, ready the list'southward model to an instance of a mutable list model class, such equally an example of DefaultListModel
. You can set a list's model when you lot create the listing or by calling the setModel
method. Meet Adding Items to and Removing Items from a List for an instance.
The phone call to setSelectionMode
specifies how many items the user tin can select, and whether they must be contiguous; the next section tells you more well-nigh selection modes.
The telephone call to setLayoutOrientation
lets the listing display its data in multiple columns. The value JList.HORIZONTAL_WRAP
specifies that the list should display its items from left to right earlier wrapping to a new row. Some other possible value is JList.VERTICAL_WRAP
, which specifies that the data be displayed from height to lesser (as usual) before wrapping to a new column. The following figures show these two wrapping possibilities, together with the default, JList.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. Some other common use of setVisibleRowCount
is to specify to the lists's curlicue pane how many rows the list prefers to brandish.
Selecting Items in a List
A list uses an instance of ListSelectionModel
to manage its choice. By default, a list selection model allows any combination of items to be selected at a time. You tin can specify a different selection mode by calling the setSelectionMode
method on the list. For example, both ListDialog
and ListDemo
set the option manner to SINGLE_SELECTION
(a constant divers by ListSelectionModel
) so that simply i detail in the listing can be selected. The following tabular array describes the iii list pick modes:
Style | Description |
---|---|
SINGLE_SELECTION | Only one item can exist selected at a time. When the user selects an particular, any previously selected detail is deselected get-go. |
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. Whatever combination of items can be selected. The user must explicitly deselect items. |
No thing which choice style your list uses, the list fires list pick events whenever the choice changes. You tin process these events by calculation a list selection listener to the list with the addListSelectionListener
method. A listing choice listener must implement ane method: valueChanged
. Here is the valueChanged
method for the listener in ListDemo
:
public void valueChanged(ListSelectionEvent e) { if (due east.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -i) { //No selection, disable burn push button. fireButton.setEnabled(false); } else { //Option, enable the burn button. fireButton.setEnabled(truthful); } } }
Many listing choice events can be generated from a single user activity such as a mouse click. The getValueIsAdjusting
method returns truthful
if the user is still manipulating the selection. This particular plan is interested only in the final result of the user's action, so the valueChanged
method does something but if getValueIsAdjusting
returns false
.
Considering the list is in single-selection mode, this lawmaking tin 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 desire, you can heed for events on the list'due south list option model rather than on the list itself. ListSelectionDemo is an example that shows how to heed for list selection events on the list choice model and lets you alter the selection fashion of a list dynamically.
Adding Items to and Removing Items from a List
The ListDemo example that we showed previously features a listing whose contents tin modify. Y'all tin 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 programme uses an example of DefaultListModel
, a class provided past 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 tin can write a custom listing model, which must adhere to the ListModel
interface.
The following lawmaking snippet shows the actionPerformed
method for the activity listener registered on the Burn button. The bold line of code removes the selected particular in the listing. The remaining lines in the method disable the burn down button if the list is now empty, and make another pick if it is not.
public void actionPerformed(ActionEvent e) { int index = listing.getSelectedIndex(); listModel.remove(alphabetize); int size = listModel.getSize(); if (size == 0) { //Nobody's left, disable firing. fireButton.setEnabled(fake); } else { //Select an index. if (alphabetize == listModel.getSize()) { //removed item in final position alphabetize--; } listing.setSelectedIndex(index); list.ensureIndexIsVisible(index); } }
Here is the actionPerformed
method for the action listener shared past the Hire button and the text field:
public void actionPerformed(ActionEvent e) { String proper noun = employeeName.getText(); //User did not type in a unique name... if (name.equals("") || alreadyInList(name)) { Toolkit.getDefaultToolkit().beep(); employeeName.requestFocusInWindow(); employeeName.selectAll(); render; } int alphabetize = listing.getSelectedIndex(); //become selected index if (alphabetize == -1) { //no pick, so insert at starting time index = 0; } else { //add together after the selected item index++; } listModel.insertElementAt(employeeName.getText(), index); //Reset the text field. employeeName.requestFocusInWindow(); employeeName.setText(""); //Select the new detail and brand information technology visible. list.setSelectedIndex(index); listing.ensureIndexIsVisible(index); }
This code uses the list model's insertElementAt
method to insert the new proper noun later on the current selection or, if no selection exists, at the beginning of the list. If you just wish to add together to the cease of the list, you tin utilise DefaultListModel
's addElement
method instead.
Whenever items are added to, removed from, or modified in a listing, the list model fires list data events. Refer to How to Write a List Data Listener for information about listening for these events. That department contains an instance that is similar to ListDemo
, but adds buttons that motility 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 Object
due south by invoking toString
. If you lot want to modify the way the default renderer display icons or strings, or if y'all want beliefs different than what is provided by toString
, y'all can implement a custom prison cell renderer. Have these steps to provide a custom cell renderer for a list:
- Write a grade that implements the
ListCellRenderer
interface. - Create an example of your form and phone call the listing's
setCellRenderer
using the instance as an argument.
We do not provide an example of a listing with a custom prison cell renderer, but we do have an instance of a combo box with a custom renderer — and philharmonic boxes utilize the same blazon of renderer equally lists. Meet the instance 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 probable to invoke on a JList
object are those such as setPreferredSize
that its superclasses provide. See The JComponent API for tables of usually used inherited methods.
Much of the operation of a list is managed by other objects. The items in the listing are managed by a list model object, the selection is managed by a list selection model object, and most programs put a listing in a scroll pane to handle scrolling. For the most role, yous do not need to worry about the models because JList
creates them as necessary and you collaborate with them implicitly with JList
'due south convenience methods.
That said, the API for using lists falls into these categories:
- Initializing List Information
- Displaying the Listing
- Managing the List'south Selection
- Managing List Data
Method or Constructor | Purpose |
---|---|
JList(ListModel) JList(Object[]) JList(Vector) JList() | Create a list with the initial list items specified. The second and tertiary constructors implicitly create an immutable ListModel ; you lot should not subsequently modify the passed-in array or Vector . |
void setModel(ListModel) ListModel getModel() | Set or get the model that contains the contents of the listing. |
void setListData(Object[]) void setListData(Vector) | Set the items in the listing. These methods implicitly create an immutable ListModel . |
Method | Purpose |
---|---|
void setVisibleRowCount(int) int getVisibleRowCount() | Fix or get the visibleRowCount holding. For a VERTICAL layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap. See the setLayoutOrientation(int) for more data. The default value of this property is VERTICAL . |
void setLayoutOrientation(int) int getLayoutOrientation() | Set up or get the fashion list cells are laid out. The possible layout formats are specified by the JList -defined values VERTICAL (a unmarried column of cells; the default), HORIZONTAL_WRAP ("newspaper" way with the content flowing horizontally then vertically), and VERTICAL_WRAP ("newspaper" style with the content flowing vertically then horizontally). |
int getFirstVisibleIndex() int getLastVisibleIndex() | Become the index of the first or concluding visible detail. |
void ensureIndexIsVisible(int) | Scroll so that the specified alphabetize is visible within the viewport that this listing is in. |
Method | Purpose |
---|---|
void addListSelectionListener(ListSelectionListener) | Register to receive notification of selection changes. |
void setSelectedIndex(int) void setSelectedIndices(int[]) void setSelectedValue(Object, boolean) void setSelectionInterval(int, int) | Set the current selection as indicated. Use setSelectionMode to gear up what ranges of selections are acceptable. The boolean argument specifies whether the list should effort to scroll itself so that the selected particular is visible. |
int getAnchorSelectionIndex() int getLeadSelectionIndex() int getSelectedIndex() int getMinSelectionIndex() int getMaxSelectionIndex() int[] getSelectedIndices() Object getSelectedValue() Object[] getSelectedValues() | Get information nearly the current selection as indicated. |
void setSelectionMode(int) int getSelectionMode() | Set or get the choice manner. Acceptable values are: SINGLE_SELECTION , SINGLE_INTERVAL_SELECTION , or MULTIPLE_INTERVAL_SELECTION (the default), which are defined in ListSelectionModel . |
void clearSelection() boolean isSelectionEmpty() | Set or get whether any items are selected. |
boolean isSelectedIndex(int) | Determine whether the specified index is selected. |
Class or Method | Purpose |
---|---|
int getNextMatch(String, int, javax.swing.text.Position.Bias) | Given the starting alphabetize, search through the listing for an particular that starts with the specified string and return that alphabetize (or -1 if the string is not found). The third argument, which specifies the search management, can be either Position.Bias.Forrad or Position.Bias.Backward . For case, if you take a 6-item listing, getNextMatch("Matisse", 5, javax.swing.text.Position.Bias.Frontwards) searches for the string "Matisse" in the item at alphabetize v, then (if necessary) at alphabetize 0, index 1, and and then on. |
void setDragEnabled(boolean) boolean getDragEnabled() | Set or get the holding that determines whether automatic elevate treatment is enabled. See Drag and Drop and Information Transfer for more details. |
Examples that Apply Lists
This table shows the examples that employ JList
and where those examples are described.
Example | Where Described | Notes |
---|---|---|
SplitPaneDemo | How to Use Divide Panes | Contains a single-pick, immutable list. |
ListDemo | This section | Demonstrates how to add and remove items from a list at runtime. |
ListDialog | This section, How to Use BoxLayout | Implements a modal dialog with a single-selection list. |
ListDataEventDemo | How to Write a List Data Listener | Demonstrates listening for list data events on a list model. |
ListSelectionDemo | How to Write a List Selection Listener | Contains a list and a table that share the aforementioned selection model. You lot can dynamically choose the selection way. |
SharedModelDemo | Using Models | Modifies ListSelectionDemo so that the listing and tabular array share the same data model. |
CustomComboBoxDemo | Providing a Custom Renderer | Shows how to provide a custom renderer for a combo box. Considering lists and combo boxes use the same type of renderer, you can apply what y'all larn in that location an apply it to lists. In fact, a list and a combo box tin can share a renderer. |
See the Using JavaFX UI Controls: List View tutorial to learn how to create lists in JavaFX.
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/list.html
0 Response to "Java How to Read Text File Into Jlist"
Post a Comment