- Java code
import java.awt.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.event.ListSelectionEvent;public class FontsListJFrame extends JFrame implements ListSelectionListener{ private JList list; private JTextArea text; public FontsListJFrame() { super("系统字体预览"); Dimension dim = getToolkit().getScreenSize(); //获得屏幕分辨率 this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2);//窗口居中 this.setDefaultCloseOperation(EXIT_ON_CLOSE); GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontsName=ge.getAvailableFontFamilyNames(); //获得系统字体 this.list = new JList(fontsName); this.getContentPane().add(new JScrollPane(this.list)); this.list.addListSelectionListener(this); //注册选择事件监听器 this.list.setCellRenderer(new CheckBoxListCellRenderer()); //设置自定义的单元渲染器 this.text = new JTextArea("Welcome 欢迎"); this.getContentPane().add(this.text,"South"); this.setVisible(true); } class CheckBoxListCellRenderer extends JCheckBox implements ListCellRenderer //列表框单元渲染器 { //必须是内部类 public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) { setText(value.toString()); setFont(new Font(value.toString(),Font.BOLD,16)); //以当前字符串作为字体名设置字体 setBackground(isSelected ? Color.lightGray : Color.white); //选中数据项背景浅灰色 setForeground(isSelected ? Color.red : Color.black); //选中数据项红色显示 setSelected(isSelected); //当前数据项选中状态 return this; } } public void valueChanged(ListSelectionEvent e) //在列表框中选择数据项时触发 { //一次选择,执行两次该事件??为什么 String selected = (String)list.getSelectedValue();// System.out.println(selected); this.text.setFont(new Font(selected,Font.BOLD,56)); } public static void main(String[] args) { new FontsListJFrame(); }}
------解决方案--------------------
- Java code
this.list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //设置为单选 //////////////////////////////// if (e.getValueIsAdjusting()) { String selected = (String) list.getSelectedValue();// System.out.println(selected); this.text.setFont(new Font(selected, Font.BOLD, 56)); }