我基本上做了这个东西,用户突出显示食物列表并按下“>>”按钮,将食物从左侧传输到右侧,反之亦然,使用“<<”按钮。我真正遇到的唯一麻烦就是这样做。我走得足够远,使它出现在指定的列表上,但它只将其中一种食物转移到列表中。例如,如果您选择了“Tuna”和“Mayo”,那么只有“Tuna”会被转移到适当的列表中。继承人的代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.*;
import java.util.List;
import javax.swing.JTextField;
public class MAIN extends JFrame {
Button ltor, rtol;
JList homelist, shoppinglist;
DefaultListModel homefoodlist = new DefaultListModel();
DefaultListModel shoppingfoodlist = new DefaultListModel();
JTextField foodlog;
String[] hfood = { "Tuna", "Mayo", "Ketchup", "Sun Flower Oil", "Buscuits",
"Cookies", "Turkey" };
String[] sfood = { "Chocolate", "bread", "Milk", "Toast", "Beef", "Chicken" };
public static void main(String[] args) {
new MAIN();
}
private MAIN() {
JPanel thepanel = new JPanel();
thehandler handler = new thehandler();
this.setLocationRelativeTo(null);
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setTitle("Shopping List");
this.add(thepanel);
// Creating the Home List(left list)
for (String homefood : hfood) {
homefoodlist.addElement(homefood);
}
homelist = new JList(homefoodlist);
homelist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
thepanel.add(homelist);
// Buttons for moving lists from left to right
ltor = new Button(">>");
thepanel.add(ltor);
ltor.addActionListener(handler);
rtol = new Button("<<");
rtol.addActionListener(handler);
thepanel.add(rtol);
// Creating the Shopping list(right list)
for (String shoppingfood : sfood) {
shoppingfoodlist.addElement(shoppingfood);
}
shoppinglist = new JList(shoppingfoodlist);
shoppinglist
.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
thepanel.add(shoppinglist);
}
// ActionListener
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// The HomeList to the ShoppingList
if (e.getSource() == ltor) {
if (homelist.isSelectionEmpty() == false) {
for(String x : hfood) {
if (x == homelist.getSelectedValue()) {
shoppingfoodlist.addElement(x);
}
}
}
}
}
}
}
编辑 == 刚刚修复它但由于某种原因我不能做相反的事情(例如从购物清单到家庭清单。这是我的动作监听器代码
if (e.getSource() == ltor) {
if (homelist.isSelectionEmpty() == false) {
for (String x : hfood) {
for (String y : homelist.getSelectedValuesList()) {
if (x.equals(y)) {
shoppingfoodlist.addElement(x);
homefoodlist.removeElement(x);
continue;
}
}
}
if (e.getSource() == rtol) {
if (shoppinglist.isSelectionEmpty() == false) {
for (String x : sfood) {
for (String y : shoppinglist
.getSelectedValuesList()) {
if (x.equals(y)) {
homefoodlist.addElement(x);
shoppingfoodlist.removeElement(x);
}
}
}
}
}