♠ Posted by Unknown in Adv Java at 21:42
JList Class
List
boxes are significantly different from JComboBox boxes, and not just in
appearance. While a JcomboBox box drops down when you activate it, a JList
occupies some fixed number of lines on a screen all the time and doesn’t
change. If you want to see the items in a list, you simply call
getSelectedValues(), which produces an array of String of the items that have
been selected.
A
JList allows multiple selection: if you control-click on more than one item
(holding down the “control” key while performing additional mouse clicks) the
original item stays highlighted and you can select as many as you want.
Example:
/ * <APPLET CODE = "JListExample.CLASS"
WIDTH = 500 HEIGHT = 500></APPLET>
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class JListExample extends JApplet implements ActionListener, ListSelectionListener
{
String[] flavors = {
"Chocolate","Strawberry","Vanilla","Mint
Swip"};
DefaultListModel lItems = new
DefaultListModel();
JList lst = new JList(lItems);
JTextArea jtf = new
JTextArea(flavors.length,20);
JButton jb = new JButton("Add
Item");
int count = 0;
public void init()
{
Container contentPane =
getContentPane();
jtf.setEditable(false);
contentPane.setLayout(new
FlowLayout());
Border brd =
BorderFactory.createMatteBorder(1,1,2,2,Color.BLACK);
lst.setBorder(brd);
jtf.setBorder(brd);
for(int i = 0; i < 4; i++)
lItems.addElement(flavors[count++]);
contentPane.add(lst);
contentPane.add(jb);
lst.addListSelectionListener(this);
jb.addActionListener(this);
}
public void
valueChanged(ListSelectionEvent lse)
{
jtf.setText("");
Object [] items =
lst.getSelectedValues();
for(int i = 0; i <
items.length; i++)
jtf.append(items[i]
+ "\n");
}
public void
actionPerformed(ActionEvent ae)
{
if(count < flavors.length)
lItems.add(0,flavors[count++]);
else
jb.setEnabled(false);
}
}
0 comments:
Post a Comment