我有 2 个 jlist 和 1 个 jbutton。我想要做的是,当用户选择一个 jlist 中的某些项目,然后单击按钮,一些元素会根据选择出现在另一个 jlist 上。我的问题是 && 条件,因为程序首先识别 ||并忽略它。因此,当用户选择“a”和“c”时,添加所有元素的第三个元素不对应。我该如何解决这个问题?
这是我的代码:
public class test extends JPanel implements ActionListener {
static JFrame frame = new JFrame("");
public test() {
String[] feedStrings = { "a", "b", "c", "d" }
final JList feedList = new JList(feedStrings);
feedList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
final DefaultListModel model = new DefaultListModel();
final JList prodList = new JList(model);
prodList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JButton arrow = new JButton("button");
arrow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
feedList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e)
{
List<String> templist = new ArrayList<String>();
templist = feedList.getSelectedValuesList();
if (templist.contains("a")|| templist.contains("b"){
model.removeAllElements();
model.addElement("x");
model.addElement("y");
model.addElement("z");
}else if(templist.contains("c") ||templist.contains("d") ) {
model.removeAllElements();
model.addElement("t");
model.addElement("g");
model.addElement("h");
model.addElement("k");
}else if(templist.contains("a") && templist.contains("c") {
model.removeAllElements();
model.addElement("t");
model.addElement("g");
model.addElement("h");
model.addElement("k");
model.addElement("x");
model.addElement("y");
model.addElement("z");
}
});
}
});
JPanel flow = new JPanel(new FlowLayout());
flow.add(feedList);
flow.add(arrow);
flow.add(prodList);
frame.add(flow);
}
private static void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JFrame.setDefaultLookAndFeelDecorated(true);
//Add content to the window.
frame.add(new test());
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.TRUE);
try {
createAndShowGUI();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
最佳答案
您必须将 else if
设为 if
循环。如果您在代码中同时使用 if
和 else if
,则代码只会在第一个条件变为 true 时执行,并且不会检查其他 else if
循环。在您的情况下,当您选择 'a' 和 'c' 时,仅执行第一个 if
条件,其余的 else if
循环将被忽略
关于java - ListSelectionListener 无法识别 if 条件中的联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455071/