Dynamically Updating a List
The previous example demonstrated the most basic list box example which included only static data and supported no selection management.
However, there is much more to the JList class. The more advanced list box application, DynListExample.java to demonstrate some of the functionality provided by this useful Swing component.
A list box will be able to dynamically updated by the user:
- Initially the list is empty.
- The User can add new text to the list by entering text in a text field and clicking the Add button.
- The user may want to delete items, we will create a Remove button and, to it, attach code to delete list items.
- we will also intercept list selections and transfer the selected item back into the text field.
DynListExample Program Output
The DynListExample.java program has the following main additions to the previous ListExample.java program:
- A string vector has replaced the static string array so that the code can dynamically insert and remove strings.
- The list may grow beyond the bounds of the application frame so the list instance has been added to a scrolling pane, and it will automatically attach scroll bars when required.
- A ListSelectionListener is implemented which is responsible for detecting user list selections. The list box attaches the listener code using the following line:
listbox.addListSelectionListener( this );
- The valueChanged() method is called any time the user selects an item from the list. When this occurs, the code determines the current list selection and copies its text to the text field.
- The valueChanged() method, like other action handlers shown previously, uses the event.getSource() call to determine the component generating the event:
if( event.getSource() == listbox && !event.getValueIsAdjusting() )
However note that List selection events are generated in clusters:
- one for each item that is being deselected,
- one for each selected item, and one final event that indicates that the selection values are no longer changing.
This final event is the one the program needs to detect, while all others can be disregarded. To accomplish this, the code uses the event's getValueIsAdjusting() method.
The full code listing for DynListExample.java is as follows:
// Imports import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class DynListExample extends JFrame implements ActionListener, ListSelectionListener { // Instance attributes used in this example private JPanel topPanel; private JList listbox; private Vector listData; private JButton addButton; private JButton removeButton; private JTextField dataField; private JScrollPane scrollPane; // Constructor of main frame public DynListExample() { // Set the frame characteristics setTitle( "Advanced List Box Application" ); setSize( 300, 100 ); setBackground( Color.gray ); // Create a panel to hold all other components topPanel = new JPanel(); topPanel.setLayout( new BorderLayout() ); getContentPane().add( topPanel ); // Create the data model for this example listData = new Vector(); // Create a new listbox control listbox = new JList( listData ); listbox.addListSelectionListener( this ); // Add the listbox to a scrolling pane scrollPane = new JScrollPane(); scrollPane.getViewport().add( listbox ); topPanel.add( scrollPane, BorderLayout.CENTER ); CreateDataEntryPanel(); } public void CreateDataEntryPanel() { // Create a panel to hold all other components JPanel dataPanel = new JPanel(); dataPanel.setLayout( new BorderLayout() ); topPanel.add( dataPanel, BorderLayout.SOUTH ); // Create some function buttons addButton = new JButton( "Add" ); dataPanel.add( addButton, BorderLayout.WEST ); addButton.addActionListener( this ); removeButton = new JButton( "Delete" ); dataPanel.add( removeButton, BorderLayout.EAST ); removeButton.addActionListener( this ); // Create a text field for data entry and display dataField = new JTextField(); dataPanel.add( dataField, BorderLayout.CENTER ); } // Handler for list selection changes public void valueChanged( ListSelectionEvent event ) { // See if this is a listbox selection and the // event stream has settled if( event.getSource() == listbox && !event.getValueIsAdjusting() ) { // Get the current selection and place it in the // edit field String stringValue = (String)listbox.getSelectedValue(); if( stringValue != null ) dataField.setText( stringValue ); } } // Handler for button presses public void actionPerformed( ActionEvent event ) { if( event.getSource() == addButton ) { // Get the text field value String stringValue = dataField.getText(); dataField.setText( "" ); // Add this item to the list and refresh if( stringValue != null ) { listData.addElement( stringValue ); listbox.setListData( listData ); scrollPane.revalidate(); scrollPane.repaint(); } } if( event.getSource() == removeButton ) { // Get the current selection int selection = listbox.getSelectedIndex(); if( selection >= 0 ) { // Add this item to the list and refresh listData.removeElementAt( selection ); listbox.setListData( listData ); scrollPane.revalidate(); scrollPane.repaint(); // As a nice touch, select the next item if( selection >= listData.size() ) selection = listData.size() - 1; listbox.setSelectedIndex( selection ); } } } // Main entry point for this example public static void main( String args[] ) { // Create an instance of the test application DynListExample mainFrame = new DynListExample(); mainFrame.setVisible( true ); } }
'자바(JAVA)' 카테고리의 다른 글
새창으로 데이타 submit 해서 넘기기 (0) | 2008.10.11 |
---|---|
Process 관리하기 (0) | 2008.10.04 |
non-ui thread 에서 main-ui thread 사용시 에러 (0) | 2008.09.28 |
JTextArea 예제 (0) | 2008.09.24 |
구분자로 문자열을 분리하여 얻고자할때 StringTokenizer 사용법 (0) | 2008.09.10 |
문자, 숫자 변환관련 총집합 (0) | 2008.09.10 |
byte stream 을 얻어서 한줄씩 작업을 하고자할때 (0) | 2008.09.06 |
SWT 플러그인으로 파일자동생성시 swt-win32-3236 load error (0) | 2008.08.30 |