这是我第一次创建Gui,我对如何创建交互感到困惑。
我正在尝试在组合框位于单个上时实现单一选择模式,而在组合框位于多个上时实现多个选择模式。我将它们放在多行注释中。
有什么想法吗?
//互动
///当选择“ Single”时,JList更改,因此仅一项 可以选择。
///当选择“多个”时,JList更改,因此可以 被选中
///当选择一个或多个国家时,JLabel 进行更改以反映新选择
public class GuiTest {
public static String[] Countries = {"Africa", "Haiti", "USA", "Poland", "Russia", "Canada", "Mexico", "Cuba"};
public static String[] Selection = {"Single", "Multiple"};
JPanel p = new JPanel();
JButton b = new JButton("Testing");
JComboBox jc = new JComboBox(Selection);
JList jl = new JList(Countries);
private static void constructGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("Countries Selection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add a JLabel that says Welcome
JLabel label = new JLabel("Selected Items:");
frame.add(label);
frame.pack();
JComboBox jc = new JComboBox(Selection);
frame.add(jc);
frame.pack();
frame.setVisible(true);
JList jl = new JList(Countries);
frame.add(jl);
frame.pack();
JComponent panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Choose Selection Mode:"));
panel.add(jc);
frame.add(panel, BorderLayout.NORTH);
frame.add(jl, BorderLayout.WEST);
frame.add(label, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
constructGUI();
}
});
}
}
答案 0 :(得分:0)
您应该开始将模式添加到组合框:
comboBoxCategoria.addItem("Single",0);
comboBoxCategoria.addItem("Multiple",1);
然后将ActionListener添加到您的ComboBox中以修改列表选择模式
jc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(jc.getSelectedItem().equals("Single")){
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}else{//must equals
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
}
});
最后在列表上添加一个MouseListener,以检测列表选择的更改,并更改JLabel以反映新的选择
jl.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
编辑:您还应该添加KeyListener来更新标签,因为可以通过箭头键更改选择
jl.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
答案 1 :(得分:0)
会是这样的:
jc.addActionListener((evt) -> {
if ("Single".equals(jc.getSelectedItem())) {
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int[] sel = jl.getSelectedIndices();
if (sel != null && sel.length > 1) {
jl.setSelectedIndex(sel[0]);
}
} else {
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
});
jl.addListSelectionListener((evt) -> {
StringBuilder buf = new StringBuilder();
for (Object o: jl.getSelectedValuesList()) {
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(o);
}
label.setText(buf.toString());
});
jc.setSelectedItem("Single");