2017-04-04 55 views
-1

我想回來一個數組的每個第二個元素(所以在這種情況下2.和4.)。JComboBox ActionListener不起作用

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 


public class tester2 extends JFrame{ 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 

    JFrame f = new JFrame(); 
    String [] corps = {"IBM", "Apple", "Oracle", "Google"}; 
    JComboBox <String> cb = new JComboBox <>(); 

    JLabel l1 = new JLabel(); 

    public tester2() { 
     f.setSize(500, 300); 
     f.setLayout(new BorderLayout()); 
     f.setVisible(true); 
     f.setTitle("Tester 2"); 
     f.setLocationRelativeTo(null); 

     f.add(cb, BorderLayout.NORTH); 
     f.add(l1); 

     // Combo 
     cb.removeAllItems(); 
     cb.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       for (int i = 1; i < corps.length; i=+2) { 
        String tempRes = corps[i]; 
        System.out.println(tempRes); 
        cb.addItem(tempRes); 
       } 

      } 
     }); 


    } 


    public static void main(String[] args) { 
     new tester2(); 
    } 
} 

更多細節,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多詳情,更多的細節,更細節,更多細節。

感謝

+0

在0無法啓動循環在1 – XtremeBaumer

+0

*「我想拿回數組中的每個第二部件(所以在這種情況下,2和4)。」 *我想一飛排出冰淇淋的小馬。現在我們都討論了我們想要的。你有**問題**我們可以**回答**? –

+0

爲什麼這段代碼沒有得到任何結果?例如System.out.println(tempRes); - >不打印任何東西 – fucorogu

回答

1

你看不到任何東西,因爲ActionEventJComboBox當選擇一個項目僅觸發。

由於您的組合框爲空,因此不會發生這種情況。

您可以設置一個默認值,以便您的ActionListener被調用。

此外,將removeAllItems()放在actionPerformed方法中可能更好,以便在填充組合框之前清除組合框。

最後一個注意事項:從i = +2i += 2的變化,因爲i = +2意味着i=2,並且進入索引2的無限循環。

// Combo 
    cb.addItem("--filler--"); 

    cb.addActionListener(new ActionListener() { 

     public void actionPerformed(final ActionEvent e) { 

      cb.removeAllItems(); 

      for (int i = 1; i < corps.length; i += 2) { 
       String tempRes = corps[i]; 
       System.out.println(tempRes); 
       cb.addItem(tempRes); 
      } 

     } 
    }); 
+0

有趣。你試過了嗎?這不會爲我填充組合框。 – fucorogu

+0

@fucorogu:當然,但你必須選擇「填充」項來觸發這個動作。另請參閱上次編輯。 – Berger

+0

謝謝:)我還在學習。 – fucorogu

相關問題