2013-05-16 57 views
1

我需要創建一個新方法來檢查組合框中所選項目的值。 該組合框從數據庫填充。檢查JComboBox值

這是怎麼弄的選擇項:

combo.addActionListener(new ActionListener(){ 
public void actionPerformed(ActionEvent e) { 

    String x=(String) combo.getSelectedItem(); 

字符串「X」保存選定項的值,因爲我需要在我的其他查詢中使用的「x」。

ResultSet st = stt.executeQuery("Select Name from Table where Number="+x+""); 

使用該查詢,我可以填充JList

問題是,當我在組合框中選擇另一個項目時,列表不會更新。 所以我需要創建另一個語句來檢查組合框的值?如果是,如何?

+1

爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 –

+0

sry:p im new here ^^ – StReeTzZz

+0

有沒有必要道歉。但是請使用正確的拼寫來表達「你」,「你的」和「請」(即使在評論中)。這使人們更容易理解和幫助。在你再次道歉之前,我寧願聽到「將來會試着照顧它」,而不是「對不起」,因爲第一個更有用。 –

回答

2

讓你的JList使用ListModel,也實現ActionListener。將這個專門的監聽器添加到組合中。每次組合更改時,您的ListModel的動作偵聽器都會被調用。在收聽者中,您可以更新ListModel

附錄:這是基本的方法。

enter image description here

/** 
* @see http://stackoverflow.com/a/16587357/230513 
*/ 
public class ListListenerTest { 

    private static final String[] items = new String[]{"1", "2", "3"}; 
    private JComboBox combo = new JComboBox(items); 
    private JList list = new JList(new MyModel(combo)); 

    private static class MyModel extends DefaultListModel implements ActionListener { 

     private JComboBox combo; 

     public MyModel(JComboBox combo) { 
      this.combo = combo; 
      addElement(combo.getSelectedItem()); 
      combo.addActionListener(this); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      set(0, combo.getSelectedItem()); 
      System.out.println("Combo changed."); 
     } 
    } 

    private void display() { 
     JFrame f = new JFrame("ListListenerTest"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setLayout(new GridLayout(1, 0)); 
     f.add(combo); 
     f.add(list); 
     f.pack(); 
     f.setLocationRelativeTo(null); 
     f.setVisible(true); 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new ListListenerTest().display(); 
      } 
     }); 
    } 
}