JList Java Swing Component Demo

11/12/2011 code-examplejavajava-swing

# Summary

This is an example displaying the usage of JList Swing Component Demo

Here we made a list with 3 Strings and added a display button which shows which of the list value is selected. We also made use of new Dialog box i.e. ConfirmDialogBox and also we made use of JApplet this time & not a JFrame. So inorder to initialise all the components we made use of its init() method which is called first when its loaded

# Code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swingdemo;

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

/**
 *
 * @author Rohan
 */
public class JListDemo extends JApplet implements ActionListener {

    JTextField jtf;
    JList l;
    JButton b1;

    public void init() {
        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());
        l = new JList(new Object[]{"Sausages", "Mushroom", "Tomato Slice"});
        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        JScrollPane sp = new JScrollPane(l, v, h);
        cp.add(sp, BorderLayout.CENTER);
        b1 = new JButton("Display");
        b1.addActionListener(this);
        cp.add(b1, BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("Display".equals(e.getActionCommand())) {
            StringBuffer sb = new StringBuffer();
            Object[] t = l.getSelectedValues();
            for (int i = 0; i < t.length; i++) {
                sb.append(t[i]).append("\n");
            }
            JOptionPane.showConfirmDialog(this, sb);
        }
    }
}
1
2
3
4
5
6
7
8
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
35
36
37
38
39
40
41
42
43
44
45