|
A Color-Rendered List A Font List A Font-Rendered List
| |
Here's an example of how you might wish to use a list:
package swingExamples;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListColorSelector1 extends JFrame
{
public JListColorSelector1()
{
setTitle("JListColorSelector1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
getContentPane().add( new JListPanel() );
}
private static Color[] COLORS =
{
Color.BLACK, Color.BLUE,
Color.CYAN, Color.DARK_GRAY,
Color.GRAY, Color.GREEN,
Color.LIGHT_GRAY, Color.MAGENTA,
Color.ORANGE, Color.PINK,
Color.RED, Color.WHITE,
Color.YELLOW
};
//// Inner classes ////
class JListPanel extends JPanel
implements ListSelectionListener
{
JListPanel()
{
setLayout( new BorderLayout() );
JPanel listPanel = new JPanel();
m_list.setSelectedIndex(0);
m_list.addListSelectionListener(this);
listPanel.add( new JScrollPane(m_list) );
add(listPanel, BorderLayout.WEST);
add(m_colorPanel, BorderLayout.CENTER);
Color color = (Color) m_list.getSelectedValue();
m_colorPanel.setBackground(color);
}
public void valueChanged(ListSelectionEvent e)
{
JList source = (JList) e.getSource();
Color color = (Color) source.getSelectedValue();
m_colorPanel.setBackground(color);
m_colorPanel.repaint();
}
private JList m_list = new JList(COLORS);
private JPanel m_colorPanel = new JPanel();
}
/**
* Main entry point for program
*/
public static void main(String[] args)
{
JListColorSelector1 frame =
new JListColorSelector1();
frame.setVisible(true);
}
}
|
which produces the following output:

It works: As you select an item in the list, the background color of the
right-hand side changes to match the selected color.
However, the actual display of the JList leaves something to be
desired. We are adding instances of the Color class to the JList, and the
default display in the JList is generated from the
Color class's toString()
method, which produces an ugly, debug-style output.
|