2014-05-10 63 views
1

我想在Java中創建圖形用戶界面,是由一個JComboBox,JList的和的。JList的內容取決於所選擇的JComboBox將改變做出

的替代品是從JComboBox中{A,B,C}中選擇。 根據所做的選擇(A,B或C)在JList中顯示不同的列表。

例如: 如果我在JComboBox中選擇A,JList的將顯示以下字符串:A1,A2,A3,A4

如果我在JComboBox中選擇B,JList的將顯示以下字符串:B1, B2,B3,B4

,如果我在JComboBox中選擇C,JList中會顯示以下字符串:C1,C2,C3,C4

我怎麼能這樣做?

謝謝

+0

你有什麼這麼遠嗎? –

回答

2

您將ActionListener添加到組合框。然後,當選擇一個項目時,用新的ListModel更新JList。

下面是兩個組合框的例子,但這個概念將是一個組合框和一個JList相同。

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 

public class ComboBoxTwo extends JPanel implements ActionListener 
{ 
    private JComboBox<String> mainComboBox; 
    private JComboBox<String> subComboBox; 
    private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>(); 

    public ComboBoxTwo() 
    { 
     String[] items = { "Select Item", "Color", "Shape", "Fruit" }; 
     mainComboBox = new JComboBox<String>(items); 
     mainComboBox.addActionListener(this); 

     // prevent action events from being fired when the up/down arrow keys are used 
     mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); 
     add(mainComboBox); 

     // Create sub combo box with multiple models 

     subComboBox = new JComboBox<String>(); 
     subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4 
     add(subComboBox); 

     String[] subItems1 = { "Select Color", "Red", "Blue", "Green" }; 
     subItems.put(items[1], subItems1); 

     String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" }; 
     subItems.put(items[2], subItems2); 

     String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" }; 
     subItems.put(items[3], subItems3); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     String item = (String)mainComboBox.getSelectedItem(); 
     Object o = subItems.get(item); 

     if (o == null) 
     { 
      subComboBox.setModel(new DefaultComboBoxModel()); 
     } 
     else 
     { 
      subComboBox.setModel(new DefaultComboBoxModel((String[])o)); 
     } 
    } 

    private static void createAndShowUI() 
    { 
     JFrame frame = new JFrame("SSCCE"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new ComboBoxTwo()); 
     frame.setLocationByPlatform(true); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       createAndShowUI(); 
      } 
     }); 
    } 
}