你可以讓他們共享相同的模型,可能是因爲DefaultComboBoxModel它實現的ListModel,因此應爲兩個工作JComboBox和JList。例如:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ShareComboModel {
private static final int TIMER_DELAY = 2000;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGui();
}
});
}
private static void createGui() {
String[] data = {"Fe", "Fi", "Fo", "Fum"};
final DefaultComboBoxModel model = new DefaultComboBoxModel(data);
JComboBox combobox = new JComboBox(model);
JList jlist = new JList(model);
new Timer(TIMER_DELAY, new ActionListener() {
private int count = 0;
public void actionPerformed(ActionEvent e) {
model.addElement("count: " + count);
count++;
}
}).start();
JPanel comboPanel = new JPanel();
comboPanel.add(combobox);
JPanel listPanel = new JPanel();
listPanel.add(new JScrollPane(jlist));
JPanel panel = new JPanel(new GridLayout(1, 0));
panel.add(comboPanel);
panel.add(listPanel);
panel.setPreferredSize(new Dimension(400, 200));
JFrame frame = new JFrame("App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
我不敢相信即使淘汰了API,我也沒有想到。它工作完美。非常感謝你的幫助! – 2011-02-09 08:51:49