This program demonstrates a simple fixed list of strings : List « Swing JFC « Java






This program demonstrates a simple fixed list of strings

This program demonstrates a simple fixed list of strings
 
/*
   This program is a part of the companion code for Core Java 8th ed.
   (http://horstmann.com/corejava)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * This program demonstrates a simple fixed list of strings.
 * @version 1.23 2007-08-01
 * @author Cay Horstmann
 */
public class ListTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               JFrame frame = new ListFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * This frame contains a word list and a label that shows a sentence made up from the chosen words.
 * Note that you can select multiple words with Ctrl+click and Shift+click.
 */
class ListFrame extends JFrame
{
   public ListFrame()
   {
      setTitle("ListTest");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      String[] words = { "quick", "brown", "hungry", "wild", "silent", "huge", "private",
            "abstract", "static", "final" };

      wordList = new JList(words);
      wordList.setVisibleRowCount(4);
      JScrollPane scrollPane = new JScrollPane(wordList);

      listPanel = new JPanel();
      listPanel.add(scrollPane);
      wordList.addListSelectionListener(new ListSelectionListener()
         {
            public void valueChanged(ListSelectionEvent event)
            {
               Object[] values = wordList.getSelectedValues();

               StringBuilder text = new StringBuilder(prefix);
               for (int i = 0; i < values.length; i++)
               {
                  String word = (String) values[i];
                  text.append(word);
                  text.append(" ");
               }
               text.append(suffix);

               label.setText(text.toString());
            }
         });

      buttonPanel = new JPanel();
      group = new ButtonGroup();
      makeButton("Vertical", JList.VERTICAL);
      makeButton("Vertical Wrap", JList.VERTICAL_WRAP);
      makeButton("Horizontal Wrap", JList.HORIZONTAL_WRAP);

      add(listPanel, BorderLayout.NORTH);
      label = new JLabel(prefix + suffix);
      add(label, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.SOUTH);
   }

   /**
    * Makes a radio button to set the layout orientation.
    * @param label the button label
    * @param orientation the orientation for the list
    */
   private void makeButton(String label, final int orientation)
   {
      JRadioButton button = new JRadioButton(label);
      buttonPanel.add(button);
      if (group.getButtonCount() == 0) button.setSelected(true);
      group.add(button);
      button.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               wordList.setLayoutOrientation(orientation);
               listPanel.revalidate();
            }
         });
   }

   private static final int DEFAULT_WIDTH = 400;
   private static final int DEFAULT_HEIGHT = 300;
   private JPanel listPanel;
   private JList wordList;
   private JLabel label;
   private JPanel buttonPanel;
   private ButtonGroup group;
   private String prefix = "The ";
   private String suffix = "fox jumps over the lazy dog.";
}

   
  








Related examples in the same category

1.Use JList component to display custom objects with ListCellRendererUse JList component to display custom objects with ListCellRenderer
2.An example of JList with a DefaultListModelAn example of JList with a DefaultListModel
3.Create JList from array of string valueCreate JList from array of string value
4.A graphical list selection monitorA graphical list selection monitor
5.Test of the DragGesture classes and JList to see if we can recognize a simple drag gestureTest of the DragGesture classes and JList to see if we can recognize a simple drag gesture
6.Dual JList with buttons in betweenDual JList with buttons in between
7.extends ListCellRenderer to display iconsextends ListCellRenderer to display icons
8.Add JList to Scroll paneAdd JList to Scroll pane
9.Dual Sample: JList and ComboBoxDual Sample: JList and ComboBox
10.JList selection changed listenerJList selection changed listener
11.Triple List from same data arrayTriple List from same data array
12.List with and without ScrollPane List with and without ScrollPane
13.Set visible row count and fixed cell height and widthSet visible row count and fixed cell height and width
14.List: Shared Data SampleList: Shared Data Sample
15.List Data Event DemoList Data Event Demo
16.How to use the list componentHow to use the list component
17.Create list from list modelCreate list from list model
18.How to create list cell rendererHow to create list cell renderer
19.React to list selection actionReact to list selection action
20.Construct the list componentConstruct the list component
21.Tab list rendererTab list renderer
22.List with textfield inputList with textfield input
23.Sharing a Model between a JList and JComboBoxSharing a Model between a JList and JComboBox
24.Demonstrate Swing ScrollingListDemonstrate Swing ScrollingList
25.Demonstrate Swing JList ListModelDemonstrate Swing JList ListModel
26.Weak ListModel
27.ListModel DemoListModel Demo
28.ModifyModelSample: ListModel DemoModifyModelSample: ListModel Demo
29.ArrayList with a ListModel for ease of use
30.Drag and Drop:JList and ListDrag and Drop:JList and List
31.List selection event
32.JList is a component that displays a list of objects: It allows the user to select one or more items.JList is a component that displays a list of objects: It allows the user to select one or more items.
33.A JTextArea is a multi-line text area that displays plain text.
34.JTextPane component is an advanced component for working with text.
35.Model for a JButton: manage only the state of the button
36.A default button model
37.JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.
38.A single-selection JList.
39.Listening for Changes to the Items in a JList Component
40.Listening for Changes to the Selection in a JList Component
41.Detecting Double and Triple Clicks on an Item in a JList Component
42.Arranging Items in a JList Component
43.changes the layout orientation so that its items are displayed top-to-bottom and left-to-right.
44.Make the number of visible rows dependent on the height of the list, the visibleRowCount property must be set to 0:
45.Setting the Selection Mode of a JList Component
46.The selected items must be in a contiguous range
47.Multiple ranges of selected items are allowed
48.Setting the Selected Items in a JList Component
49.import javax.swing.JList;
50.Select all the items
51.Clear all selections
52.Select the first item
53.Add another selection - the third item
54.Deselect the first item
55.Select a single item
56.Getting the Selected Items in a JList Component
57.Get the index of the last selected item
58.Determine if the third item is selected
59.Determine if there are any selected items
60.Return the selected item objects:
61.Adding and Removing an Item in a JList Component
62.Append an item
63.Insert an item at the beginning
64.Create a list that allows adds and removes
65.Set method replaces an item
66.Methods are used to remove items
67.Getting the Items in a JList Component
68.Methods are used to find an item:
69.These methods can be used to find the range of visible items:
70.Get index of first visible item
71.Get index of last visible item
72.Setting a Tool Tip for an Item in a JList Component
73.Setting the Dimensions of an Item in a JList Component
74.It is also possible to set the item dimensions using a sample value:
75.Creating a JList Component
76.The items can be arbitrary objects. The toString() method of the objects is displayed in the list component.
77.Determining the Selected JRadioButton in a Button Group
78.A spinner that rolls from the end of a list to beginning
79.This program demonstrates the use of cell renderers in a list box
80.This program demonstrates a list that dynamically computes list entriesThis program demonstrates a list that dynamically computes list entries