2010-11-18 22 views

回答

1

以下的作品選擇了第一個以外的項目。但是,如果使用鍵盤更改選擇,則始終從第一個開始,因爲這是所選的那個。

import java.awt.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import javax.swing.plaf.basic.*; 

public class ComboBoxSelect extends JFrame 
{ 
    public ComboBoxSelect() 
    { 
     String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" }; 
     JComboBox comboBox = new JComboBox(items); 
     add(comboBox); 

     comboBox.addPopupMenuListener(new PopupMenuListener() 
     { 
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) 
      { 
       JComboBox comboBox = (JComboBox)e.getSource(); 
       BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0); 
       JList list = popup.getList(); 
       list.setSelectedIndex(2); 
      } 

      public void popupMenuCanceled(PopupMenuEvent e) {} 
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {} 

     }); 
    } 

    public static void main(String[] args) 
    { 
     ComboBoxSelect frame = new ComboBoxSelect(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

}

+0

這是完美的!謝謝!! – blow 2010-11-18 23:28:36

0

這寫提供了你可以如何修改的JComboBox指導:

雖然它的自動完成功能編寫,自定義機制,突出而不選擇將是非常相似(也許更容易)。

+0

該解決方案使用setSelectedItem在彈出highligth項目。 – blow 2010-11-18 23:17:08