Ok guys. a newbie here. Just created this thing where the user selects a food from the 'Home List' and clicks on the '>>' button to add it to the list on the left which is the 'Shopping List' and vice versa. It works well although it starts getting a bit dodgy when the user clicks on the button after selecting it. It prints out the whole list again and also it appears as an array. I just want the selected values be added to the JList. Heres the code:
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");
}
}
}
}
}