2015-03-24 100 views
0

我只是做了一個小程序,客戶選擇從JList中 和3種顏色一些我需要如何將這些顏色添加到客戶對象添加選擇JList組件到對象

我有構造這樣

public Customer (String cc1, String cc2, String cc3){ 
    this.colour1 = cc1; 
    this.colour2 = cc2; 
    this.colour3 = cc3; 

而且簡單的代碼,我寫了這是

public class Test2 extends JApplet { 
Container container; 
JButton b1; 
JPanel panel; 
JTextArea area; 
String[] colours = {"Yellow", "Orange", "Red", "Purple", 
     "Blue", "Green", "Brown", "Black", "White"}; 
JList list, selectList; 
String cc1, cc2, cc3; //Chosen colour 

public void init() { 
    container = getContentPane(); 
    panel = new JPanel(new FlowLayout()); 
    area = new JTextArea(); 
    b1 = new JButton("Submit"); 
    list = new JList(colours); 
    selectList = new JList(); 
    list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
    list.setVisibleRowCount(5); 

    panel.add(new JScrollPane(list)); 
    panel.add(b1); 
    panel.add(new JScrollPane(selectList)); 
    panel.add(area); 
    container.add(panel); 

    b1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      for(int i = 0; i < colours.length; i++) { 
       Object selected[] = list.getSelectedValues(); 
       selectList.setListData(selected); 
      } 
     } 
    }); 
} 

}

如何讓這個人選擇了這樣一種顏色變爲Customer對象 謝謝

回答

0

如果Customer已經存在,那麼你就需要某種形式的二傳手,否則只需要創建一個新的Customer對象

你想從列表中取選定的值,並將它們添加到String陣列,你可以控制的,但你只想加起來最多3項

b1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     Object[] values = list.getSelectedValues(); 
     String[] colors = new String[3]; 
     for (int index = 0; index < Math.min(3, values.length); index++) { 
      colors[index] = values[index].toString(); 
     } 
     Customer customer = new Customer(colors[0], colors[1], colors[2]); 
    } 
}); 

還是什麼simular

+0

我打算爲循環創建新的客戶對象。 – 2015-03-24 23:18:34

+0

什麼循環?對於每個選定的項目?每個客戶都得到相同的顏色嗎? – MadProgrammer 2015-03-24 23:19:39

+0

「For loop」抱歉... – 2015-03-24 23:20:44