import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class FontCellRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean cellHasFocus) {
return new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Font font = (Font) value;
String text = font.getFamily();
FontMetrics fm = g.getFontMetrics(font);
g.setColor(isSelected ? list.getSelectionBackground() : list
.getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(isSelected ? list.getSelectionForeground() : list
.getForeground());
g.setFont(font);
g.drawString(text, 0, fm.getAscent());
}
public Dimension getPreferredSize() {
Font font = (Font) value;
String text = font.getFamily();
Graphics g = getGraphics();
FontMetrics fm = g.getFontMetrics(font);
return new Dimension(fm.stringWidth(text), fm.getHeight());
}
};
}
public static void main(String[] args) {
JFrame frame = new ListRenderingFrame();
frame.show();
}
}
class ListRenderingFrame extends JFrame implements ListSelectionListener {
JLabel label = new JLabel("The quick brown fox jumps over the lazy dog");
public ListRenderingFrame() {
setTitle("ListRendering");
setSize(400, 300);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Vector fonts = new Vector();
fonts.add(new Font("Serif", Font.PLAIN, 8));
fonts.add(new Font("SansSerif", Font.BOLD, 12));
fonts.add(new Font("Monospaced", Font.PLAIN, 16));
fonts.add(new Font("Dialog", Font.ITALIC, 12));
fonts.add(new Font("DialogInput", Font.PLAIN, 12));
JList fontList = new JList(fonts);
fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontList.setCellRenderer(new FontCellRenderer());
JScrollPane scrollPane = new JScrollPane(fontList);
JPanel p = new JPanel();
p.add(scrollPane);
fontList.addListSelectionListener(this);
getContentPane().add(p, "Center");
getContentPane().add(label, "South");
}
public void valueChanged(ListSelectionEvent evt) {
JList source = (JList) evt.getSource();
Font font = (Font) source.getSelectedValue();
label.setFont(font);
}
}