Listing 9.1 JList Used to Create a Leap Year List (TJList1.java)
// Demonstrates how to use the ListModel and JList component
/*
*
*/
import javax.swing.*;
import java.awt.*;
public class TJList1 extends JApplet {
// 1. Define the data members.
JList list = null;
MyListModel model = null;
JScrollPane scrollPane = null;
Container container = null;
public void init() {
// 2. Get a handle to the applet's content pane and
// set the grid layout.
container = this.getContentPane();
container.setLayout(new GridLayout(1,1));
// 3. Create objects of type JList, MyListModel,
// and JScrollPane and add them hierarchically
// to the applet as shown.
model = new MyListModel();
list = new JList(model);
scrollPane = new JScrollPane(list);
container.add(scrollPane);
}
}
// 4. Custom list data model that generates leap years.
class MyListModel extends AbstractListModel {
int startYear = 1900;
int endYear = 2000;
int leapYear;
// 5. Returns each list element (leap year).
public Object getElementAt(int index) {
index = index + 1; // index starts from 0;
// so make it 1.
if ((startYear+index)%4 == 0)
return "Year "+(startYear+index);
else
return null;
}
// 6. Returns the total count of data; that is,
// total number of years in the present case.
public int getSize() {
return (endYear-startYear);
}
}
Listing 9.2 JList Creates List Cells with Icons (TJList2.java)
/*
*
*/
import javax.swing.*;
import java.awt.*;
public class TJList2 extends JApplet {
// 1. Labels for the list items.
String[] ComputerComps = {"Monitor", "Key Board", "Mouse",
"Joy Stick", "Modem", "CD ROM",
"RAM Chip", "Diskette"};
// 2. Create icons for selections and make an array.
Icon icon1 = new ImageIcon("monitor.gif");
Icon icon2 = new ImageIcon("keyboard.gif");
Icon icon3 = new ImageIcon("mouse.gif");
Icon icon4 = new ImageIcon("joystick.gif");
Icon icon5 = new ImageIcon("modem.gif");
Icon icon6 = new ImageIcon("cdrom.gif");
Icon icon7 = new ImageIcon("ramchip.gif");
Icon icon8 = new ImageIcon("diskett.gif");
Icon[] icons = {icon1, icon2, icon3, icon4,
icon5, icon6, icon7, icon8};
public void init() {
// 3. Create a list object to display the computer
// components.
JList list = new JList(ComputerComps);
// 4. Render the list cells with icons.
list.setCellRenderer(new MyCellRenderer(icons));
// 5. Add the list to the applet's content pane
// through a scrollpane.
getContentPane().add(new JScrollPane(list));
}
}
// 6. Class that renders the list cells with icons.
class MyCellRenderer extends JLabel implements ListCellRenderer {
Icon[] icons;
public MyCellRenderer (Icon[] icons) {
this.icons = icons;
setOpaque(true);
}
// 7. Method that must be implemented from the interface
// ListCellRenderer.
public Component getListCellRendererComponent (
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
// 8. Set the text for the label.
if (value != null) {
String text = value.toString();
setText(text);
}
// 9. Set the icon for each selection cell
// indicated by the index.
setIcon(icons[index]);
// 10. What happens when a selection is made.
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
// NOTE: This step is very important; otherwise, the
// selection colors don't render as expected!
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
// 11. Finally, return this rubber stamp component.
return this;
}
}
Listing 9.3 List Item Selection (TJList3.java)
// Demonstrates the item-selection from a list widget
/*
*
*/
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class TJList3 extends JApplet {
// 1. Declare the required references.
JList list = null;
JLabel label = null;
Container c = null;
// 2. Create the arrays for the list selections.
String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
int[] holidays = {0, 6}; //Indices for sunday&saturday
public void init() {
// 3. Get the handle on the applet's content pane.
c = this.getContentPane();
// 4. Create a list object.
list = new JList(weekdays);
Font f1 = new Font("SansSerif", Font.BOLD, 16);
list.setFont(f1);
list.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectedIndices(holidays);
list.addSelectionInterval(2, 4);
list.setSelectionBackground(Color.blue);
list.setSelectionForeground(Color.white);
// 5. Registering a listener class.
ListSelectionListener l = new MyListener();
list.addListSelectionListener(l);
// 6. Add the list to a scroll pane and finally to the applet.
JScrollPane sp = new JScrollPane(list);
c.add(sp);
// 7. Create a label object.
label = new JLabel("Reselect using mouse?", JLabel.CENTER);
Font f2 = new Font("Serif", Font.BOLD, 26);
label.setFont(f2);
label.setOpaque(true);
label.setBackground(Color.lightGray);
label.setForeground(Color.black);
c.add(label, BorderLayout.SOUTH);
}
// 8. JList selection event listener class.
class MyListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent evt) {
label.setText((String) list.getSelectedValue());
}
}
}
Listing 9.4 Using Double Mouse Clicks to Select List Components (TJList4.java)
// Demonstrates the List component and double mouse clicks
/*
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class TJList4 extends JApplet {
// 1. Data members.
JList prodList = null;
JList cartList = null;
String[] products = {
"Internet Access PlusPack2.0",
"Java Developer's Companion CD",
"Java IDL", "Java OS",
"Java Solutions Guide", "Java Studio",
"Java Web Server", "Java WorkShop",
"JavaScope", "JavaSTAR" };
Container container = null;
GridBagLayout gridbag = null;
GridBagConstraints c = null;
Vector vector = new Vector();
JScrollPane scrollPane2 = null;
int index;
JButton button1, button2;
public void init() {
// 2. Prepare the JApplet layout.
container = this.getContentPane();
gridbag = new GridBagLayout();
c = new GridBagConstraints();
container.setLayout(gridbag);
// 3. Necessary labels.
c.fill = GridBagConstraints.BOTH;
c.gridx = 0; c.gridy = 0;
c.gridwidth = 2; c.gridheight = 1;
c.weightx = 0; c.weighty = 0;
setLabel("Java Products");
c.gridx = 2;
setLabel("Shopping Cart");
// 4. Create a list of Java products.
c.gridx = 0; c.gridy = 1;
c.weightx = 1; c.weighty = 1;
prodList = new JList(products);
MyMouseListener mListener = new MyMouseListener();
prodList.addMouseListener(mListener);
JScrollPane scrollPane1 = new JScrollPane(prodList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
gridbag.setConstraints(scrollPane1, c);
container.add(scrollPane1);
// 5. Create another list object called cartList.
c.gridx = 2;
cartList = new JList();
scrollPane2 = new JScrollPane(cartList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
gridbag.setConstraints(scrollPane2, c);
container.add(scrollPane2);
// 6. Another label indicating what to do.
c.gridx = 0; c.gridy = 2;
c.weightx = 0; c.weighty = 0;
setLabel("Double click to choose");
// 7. Add a button to delete items.
c.gridx = 2; c.gridwidth = 1;
c.fill = GridBagConstraints.NONE;
button1 = new JButton("Delete Item");
ButtonListener bl = new ButtonListener();
button1.addActionListener(bl);
gridbag.setConstraints(button1, c);
container.add(button1);
// 8. A Button to order items.
c.gridx = 3;
c.ipadx = 10;
button2 = new JButton("Order Now");
gridbag.setConstraints(button2, c);
container.add(button2);
container.validate();
}
// 9. Supporting method for labels.
public void setLabel(String text) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
gridbag.setConstraints(label, c);
container.add(label);
}
// 10. Listener class that recognizes multiple mouse clicks.
class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
if (me.getClickCount() == 2) {
index = prodList.locationToIndex(me.getPoint());
prodList.setSelectedIndex(index);
prodList.setSelectionBackground(Color.blue);
prodList.setSelectionForeground(Color.white);
vector.addElement(products[index]);
cartList.setListData(vector);
cartList.repaint();
scrollPane2.repaint();
}
}
}
// 11. Button listener to delete items from the shopping cart.
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object srcButton = (JButton) ae.getSource();
if (srcButton == button1 && !cartList.isSelectionEmpty()) {
index = cartList.getSelectedIndex();
vector.remove(index);
cartList.repaint();
}
}
}
}
Listing 9.5 JComboBox Using the Custom Model (TJComboBox1.java)
/*
*
*/
import javax.swing.*;
import javax.swing.event.*;
public class TJComboBox1 extends JApplet {
public void init() {
// 1. Create a combo box with the custom model.
JComboBox cbox = new JComboBox(new MyComboBoxModel());
// 2. Set the number of rows to be visible.
cbox.setMaximumRowCount(5);
// 3. Add the combo box object to the applet's content pane.
getContentPane().add(cbox);
}
}
// 4. Custom data model for the combo box.
class MyComboBoxModel extends AbstractListModel
implements ComboBoxModel {
String[] ComputerComps = {"Monitor", "Key Board", "Mouse",
"Joy Stick", "Modem", "CD ROM",
"RAM Chip", "Diskette"};
String selection = null;
// Methods implemented from the class AbstractListModel
public Object getElementAt(int index) {
return ComputerComps[index];
}
public int getSize() {
return ComputerComps.length;
}
public void setSelectedItem(Object anItem) {
selection = (String) anItem; // to select and register an
} // item from the pull-down list
// Methods implemented from the interface ComboBoxModel
public Object getSelectedItem() {
return selection; // to add the selection to the combo box
}
}
Listing 9.6 JComboBox Items Rendered with Icons and Labels (TJComboBox2.java)
/*
*
*/
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class TJComboBox2 extends JApplet {
// 1. Labels for the combo box pull-down list.
String[] ComputerComps = {"Monitor", "Key Board", "Mouse",
"Joy Stick", "Modem", "CD ROM",
"RAM Chip", "Diskette"};
// 2. Create icons for selections and make an array.
Icon icon1 = new ImageIcon("monitor.gif");
Icon icon2 = new ImageIcon("keyboard.gif");
Icon icon3 = new ImageIcon("mouse.gif");
Icon icon4 = new ImageIcon("joystick.gif");
Icon icon5 = new ImageIcon("modem.gif");
Icon icon6 = new ImageIcon("cdrom.gif");
Icon icon7 = new ImageIcon("ramchip.gif");
Icon icon8 = new ImageIcon("diskett.gif");
Icon[] icons = {icon1, icon2, icon3, icon4,
icon5, icon6, icon7, icon8};
public void init() {
// 3. Create a combo box with the custom model.
JComboBox cbox = new JComboBox(ComputerComps);
cbox.setRenderer(new MyCellRenderer(icons));
// 4. Set the number of rows to be visible.
cbox.setMaximumRowCount(5);
// 5. Add the combo box object to the applet's content pane.
getContentPane().add(cbox);
}
}
// 6. Class that renders the list cells with icons.
class MyCellRenderer extends JLabel implements ListCellRenderer {
Icon[] icons;
public MyCellRenderer (Icon[] icons) {
this.icons = icons;
setOpaque(true);
}
// 7. Method that must be implemented from the interface.
public Component getListCellRendererComponent (
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
// 8. Set the text for the label.
if (value != null) {
String text = value.toString();
setText(text);
}
// 9. Set the icon for each selection cell indicated
// by the index.
if ((index != -1) && (index < icons.length)) {
setIcon(icons[index]);
}
// 10. What happens when a selection is made.
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
// NOTE: This step is very important; otherwise, the
// selection colors don't render as expected!
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
// 11. Finally, return this rubber stamp.
return this;
}
}
Listing 9.7 Editable JComboBox (TJComboBox3.java)
// Demonstrates editable combo boxes
/*
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TJComboBox3 extends JApplet {
// 1. Declare the references.
JComboBox cbox = null;
Container c = null;
// 2. Define an array of sites to be shown in the
// combo box pull-down list, by default.
String[] defaultSites = {
"http://www.sun.com", "http://www.iisc.ernet.in",
"http://www.hp.com", "http://www.ibm.com",
"http://www.yahoo.com", "http://www.news.com"};
String defaultEdit = "http://www.javasoft.com";
public void init() {
// 3. Get a handle on the applet's content pane.
// and prepare the container with grid layout
c = this.getContentPane();
c.setLayout(new GridLayout(1,2));
// 4. Create the combo box with the list of default sites.
cbox = new JComboBox(defaultSites);
cbox.setOpaque(true);
// 5. Make the combo box editable.
cbox.setEditable(true);
// 6. Configure the combo box editor.
cbox.configureEditor(cbox.getEditor(), defaultEdit);
// 7. Rows to be visible without scrollbars.
cbox.setMaximumRowCount(5);
// 8. Set the combo box editor colors and font.
ComboBoxEditor cboxEditor = cbox.getEditor();
Component editorComp = cboxEditor.getEditorComponent();
editorComp.setBackground(Color.white);
editorComp.setForeground(Color.blue);
Font f1 = new Font("Dialog", Font.PLAIN, 16);
editorComp.setFont(f1);
// 9. Font for the combo box popup list.
cbox.setFont(f1);
// 10. Register the action listener.
cbox.addActionListener(new CboxListener());
// 11. A label to indicate what to do.
JLabel label = new JLabel("Enter a web site URL:",
JLabel.CENTER);
label.setFont(new Font("SansSerif", Font.BOLD, 18));
// 12. Finally...
c.add(label);
c.add(cbox);
}
class CboxListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// Helpful flag
boolean isItemPresent = false;
// 13. Check if the item already exists in the pop-up list.
for (int i=0; i