JList Component: A list is a component that displays a list of items and also allows the user to select one or more items from the list. Java provides the JList component for creating lists. Figure 13-4 shows an example. The JList component in the figure shows a list of names. At runtime, the user may select an item in the list, which causes the item to appear highlighted. In the figure, the first name is selected. Task 1: Let us now build a GUI with a JList. Let us say we want to show a list of countries. As with other Swing components, the data for a JList is define by an array of String. 1. Developing A Simple JList a. Use this array to define the List ContryName= { "USA", "India" , "Vietnam", "Canada", "Denmark","France", "Great Britain" ,"Japan"}; Set the selection mode to single selection c. Create the text field. Make the text field uneditable. b.
//import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
/** * JList basic tutorial and example * * @author wwww.codejava.net */
public class JListTask1_Student_Version extends JFrame {
//define a Jlist Component
// Define a String array that use to create the list
private JPanel ContryPanel;
// To hold components private JPanel selectedcontryPanel; // To hold components
// define a TextFiles to show the result
private JLabel label; // A message
/** Constructor */
public JListTask1_Student_Version(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JList Task1");
setSize(200, 200);
setLayout(new BorderLayout());
// Build the month and selectedMonth panels. // Add the panels to the content pane. //
add(new JScrollPane(countryList)); setLocationRelativeTo(null);
setVisible(true); }
public void buildcontryPanel() {
// Create a panel to hold the list.
ContryPanel = new JPanel();
//create the list // Set the selection mode to single selection. // Register the list selection listener. // Add the list to the panel. //
add(new JScrollPane(countryList)); }
/** The private void buildSelectedContryPanel method adds an uneditable text field to a panel. */
private void buildSelectedContryPanel() {
// Create a panel to hold the text field. selectedcontryPanel = new JPanel();
// Create the label.
label = new JLabel("You selected: ");
// Create the text field.
// Make the text field uneditable.
// Add the label and text field to the panel.
selectedcontryPanel.add(label); }
/** Private inner class that handles the event when the user selects an item from the list. */
public static void main(String[] args) {
new JListTask1_Instructor_Solution(); } }
Step by step
Solved in 3 steps with 1 images