代码如下:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class LongListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
JFrame frame = new LongListFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class LongListFrame extends JFrame {
private static final long serialVersionUID = -7328141781184742262L;
public LongListFrame() {
setTitle("LongListTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
wordList = new JList<String>(new WordListModel(3));
wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
wordList.setPrototypeCellValue("www");
JScrollPane scrollPane = new JScrollPane(wordList);
JPanel panel = new JPanel();
panel.add(scrollPane);
wordList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
// TODO Auto-generated method stub
StringBuilder word = (StringBuilder) wordList
.getSelectedValue();
setSubject(word.toString());
}
});
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.NORTH);
label = new JLabel(prefix + suffix);
contentPane.add(label, BorderLayout.CENTER);
setSubject("fox");
}
public void setSubject(String word) {
StringBuilder text = new StringBuilder(prefix);
text.append(word);
text.append(suffix);
label.setText(text.toString());
}
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 300;
private final JList<String> wordList;
private final JLabel label;
private final String prefix = "The quick brom";
private final String suffix = "jumps over the lazy dog";
}
class WordListModel extends AbstractListModel {
private static final long serialVersionUID = -3265497892938027332L;
public WordListModel(int n) {
length = n;
}
@Override
public Object getElementAt(int n) {
// TODO Auto-generated method stub
StringBuilder r = new StringBuilder();
for (int i = 0; i < length; i++) {
// 任意选取29个英文中的一个
char c = (char) (FIRST + n % (LAST - FIRST) + 1);
r.insert(0, c);
n = n / (LAST - FIRST + 1);
}
return r;
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return (int) Math.pow(LAST - FIRST + 1, length);
}
private int length;
public static final char FIRST = 'a';
public static final char LAST = 'z';
}
编译前IDE提示:
运行程序,点击列表项,出现如下异常:
求解释