2013-10-22 2 views
0

좋습니다. 여기 뉴비 야. 사용자가 '홈 목록'에서 음식을 선택하고 '>>'버튼을 클릭하여 '쇼핑 목록'인 왼쪽의 목록에 추가하거나 그 반대의 경우에이 항목을 만들었습니다. 사용자가 버튼을 클릭 한 후 버튼을 클릭하면 약간의 변화가 시작 되기는하지만 잘 작동합니다. 전체 목록을 다시 인쇄하고 배열로 나타납니다. JList에 선택한 값을 추가하기 만하면됩니다. Heres는 코드 :배열 출력 방법을 수정하는 방법

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"); 
         } 
       } 
      } 
     } 

} 
+1

선택한 요소 대신 전체 목록을 소개 할 가능성이 있습니까? 'shoppingfoodlist.addElement (homefoodlist);' – iberbeu

답변

0

는 iberbeu가 지적한 것처럼 나는 당신이 다른 한쪽에서 불과 선택한 항목을 이동하고 싶었 생각하고, 여러 선택을 할 수 있기 때문에 당신이 반복하고 선택한 모든 항목을 추가해야합니다

//ActionListener 
private class TheHandler implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     //The HomeList to the ShoppingList 
     if(e.getSource() == ltor){ 
      if(homelist.isSelectionEmpty()){ 
       JOptionPane.showMessageDialog(null, "Select a food from either list"); 
      }else{ 
       for(int i : homelist.getSelectedIndices()){ 
        shoppingFoodList.addElement(homeFoodList.get(i)); 
        homeFoodList.remove(i); 
       } 
      } 


     } 
     if(e.getSource() == rtol){ 
      if(shoppingList.isSelectionEmpty()){ 
       JOptionPane.showMessageDialog(null, "Select a food from either list"); 
      }else{ 
       for(int i: shoppingList.getSelectedIndices()){ 
        homeFoodList.addElement(shoppingFoodList.get(i)); 
        shoppingFoodList.remove(i); 
       } 
      } 
     } 
    } 
} 

그것에, 나는 수도 경우 동안, 나는 당신에게 몇 가지 제안주고 싶습니다 자바의 명명 규칙에 따라 클래스가 낙타 맡았다해야

  • 을 : 홈페이지, TheHandler 등 및 변수 낮은 낙타 케이스 : shoppingFoodList, homeFoodList 등 자세히 읽을 수 있습니다. here
  • 누구나 자신 만의 방식을 가지고 있기 때문에 debatable입니다. 하지만 코드를 좀 더 읽기 쉽도록 만들려면 절대적으로 필요한 경우 (다른 분기가 필요하지 않은 경우처럼) 조건을 무효화해야합니다. 그렇지 않으면 그냥 if에 가장 단순한 조건을 넣고 흐름과 함께 나와 같은 논리를 설명하십시오. 당신이 작동하도록 코드를 일단
  • , 당신은 if blocks 일반적인처럼 물건을 리팩토링 시작하고 >><<가 수행 한 작업 모두에 대해 중복하지만 난 지금이 ​​될 수
  • 을 너무 많은 정보를 추측 할 수 대화 메시지와 함께 위의 않았다

행운 프로

에 newb에서 레벨 업
0

당신

shoppingfoodlist.addElement(homefoodlist); 
homefoodlist.remove(homelist.getSelectedIndex()); 

로 : 또한

List selectedValues = homelist.getSelectedValuesList(); 
for (Object object : selectedValues) { 
    shoppingfoodlist.add(0,object); 
    homefoodlist.remove(homelist.getSelectedIndex()); 
} 

그리고 두 번째 부분 :

homefoodlist.addElement(shoppingfoodlist); 
shoppingfoodlist.remove(shoppinglist.getSelectedIndex()); 

로 :

List selectedValues = shoppinglist.getSelectedValuesList(); 
for (Object object : selectedValues) { 
    homefoodlist.add(0,object); 
    shoppingfoodlist.remove(shoppinglist.getSelectedIndex()); 
} 

당신이 할 수있는 ActionListener 코드 다음 당신을 교체해야 너는 2 개의 장소에있는 변화를해야 한 ㄴ다는 것을 본다 .

ltor.addActionListener(new CustomActionListener(homelist,shoppinglist)); 
rtol.addActionListener(new CustomActionListener(shoppinglist,homelist)); 

코드는 깨끗하고 있습니다 다음과 같이

class CustomActionListener implements ActionListener{ 
    JList source; 
    JList sink; 
    CustomActionListener(JList source, JList sink){ 
     this.source = source; 
     this.sink = sink; 
    } 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     // TODO Auto-generated method stub 
     if(!source.isSelectionEmpty()){ 
      List selectedValues = source.getSelectedValuesList(); 
      for (Object object : selectedValues) { 
       DefaultListModel sinkModel = (DefaultListModel) this.sink.getModel(); 
       sinkModel.add(0, object); 
       DefaultListModel sourceModel = (DefaultListModel) this.source.getModel(); 
       sourceModel.remove(source.getSelectedIndex()); 
      }  
     } 
    } 

} 

그럼 당신은 사용할 수 있습니다 :이 같은 조건 논리와 중복 사용 방법을 제거하는 리스너 코드 비트를 리팩토링하는 것이 좋습니다 당신의 ActionListener에 2 개의 장소 (ltor)와 2 번째의 if (rtol)를 유지할 필요는 없습니다.

관련 문제