好了朋友们。这里是新手。刚刚创建了这个东西,用户从“家庭列表”中选择一种食物,然后单击“>>”按钮将其添加到左侧的“购物清单”列表中,反之亦然。它运行良好,尽管当用户在选择按钮后单击按钮时它开始变得有点狡猾。它再次打印出整个列表,并且它也显示为一个数组。我只想将选定的值添加到 JList 中。继承人的代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.*;
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){
shoppingfoodlist.addElement(homefoodlist);
homefoodlist.remove(homelist.getSelectedIndex());
}else{
JOptionPane.showMessageDialog(null, "Select a food from either list");
}
}
if(e.getSource() == rtol){
if(shoppinglist.isSelectionEmpty() == false){
homefoodlist.addElement(shoppingfoodlist);
shoppingfoodlist.remove(shoppinglist.getSelectedIndex());
}else{
JOptionPane.showMessageDialog(null, "Select a food from either list");
}
}
}
}
}