public class ListComboBox extends JFrame {
private String MIS = "MULTIPLE_INTERVAL_SELECTION";
private String SIS = "SINGLE_INTERVAL_SELECTION";
private String SS = "SINGLE_SELECTION";
final int COUNTRIES = 9;
private String[] countries = {"Canada", "China", "Denmark",
"France", "Germany", "India", "Norway", "United Kingdom",
"United States of America"};
private JList<String> jlst = new JList<String>(countries);
private JLabel comboLabel = new JLabel("Choose Selection Mode: ");
private JComboBox jcbo = new JComboBox();
//to hold country labels
private JLabel countryLabel = new JLabel();
public static void main(String[] args) {
ListComboBox frame = new ListComboBox();
frame.setSize(400, 200);
frame.setTitle("Exercise 17.14");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public ListComboBox() {
//Adding selection option to combobox
jcbo.addItem(MIS);
jcbo.addItem(SIS);
jcbo.addItem(SS);
// Register listener combobox
jcbo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem() == MIS) {
jlst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
if (e.getItem() == SIS) {
jlst.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
}
if (e.getItem() == SS) {
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
}
});
//Combobox panel
JPanel combopanel = new JPanel(new FlowLayout());
combopanel.add(comboLabel);
combopanel.add(jcbo);
add(combopanel, BorderLayout.NORTH);
//List panel
JScrollPane listpanel = new JScrollPane(jlst);
add(listpanel, BorderLayout.CENTER);
//Bottom label panel
final JPanel labelpanel = new JPanel();
labelpanel.add(countryLabel);
add(labelpanel, BorderLayout.SOUTH);
//List listener
jlst.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
StringBuilder sb = new StringBuilder(64);
int[] indices = jlst.getSelectedIndices();
int i;
for (i = 0; i < indices.length; i++) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(countries[indices[i]]);
}
countryLabel.setText(sb.toString());
}
});
}
}
好日子,我需要你的幫助。JAVA在JLabel中顯示JList項目
我需要做的代碼是:將列表中的所選國家名稱與滾動條一起添加到列表下方的標籤中,將它們從列表中取消選中時將其刪除。
列表選擇模式可以在JComboBox上切換。 一切工作正常,但我無法弄清楚國家名稱正確出現在標籤內的方式。
有關我如何完成該任務的任何提示?
謝謝!
已更新!
用於'StringBuilder' +1 – tenorsax
謝謝!它解決了我的問題! – Still
@直到我很高興它的幫助,我只後悔你不能接受這兩個答案:( – MadProgrammer