2012-04-03 19 views
3

我需要創建一個多選的組合框,如何實現?如何使用多選選項創建Combobox?

+1

這裏是你的答案:http://stackoverflow.com/ a/2860376/32090 – 2012-04-03 11:08:51

+1

我建議使用[JList](http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html)。 – flash 2012-04-03 11:10:05

+1

@Andrew Thompson:不錯的建議:) – manhnt 2012-04-26 02:14:08

回答

2

沒有與創建自定義組合框彈出內容(如多選帶有一個列表)的幾個基本問​​題:
默認UI顯示JList中使用的內容,從而改變這種行爲,你將不得不改變整個ComboBoxUI
2.您不能簡單地將默認組合框列表更改爲多選列表,因爲只有一個值在最後被「選中」,並且列表中有默認的滾動選擇鼠標監聽器,這將使您無法選擇更多比一個元素

所以我建議你給我們使用簡單的JList代替組合框,或者使用一些擴展組件庫(如JideSoft) - 它們具有此組件以及更多使用Swing功能無法快速創建的組件。

+0

好點,非常感謝。 – manhnt 2012-04-03 16:05:27

+0

它只是我已經試圖改變組合框彈出成樹狀,我失敗了 - 這一嘗試花了差不多一天。所以這就是爲什麼我建議使用JList或作爲一個選項 - JButton彈出包含任何組件/編輯器你喜歡。 – 2012-04-03 23:35:18

6

我知道,這個問題已很舊,但對於那些,誰仍在尋找這個問題的解決方案,請嘗試以下代碼:

public class ComboSelections { 

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, UnsupportedLookAndFeelException { 

UIManager.setLookAndFeel((LookAndFeel) Class.forName("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel").newInstance()); 

final JPopupMenu menu = new JPopupMenu(); 
JMenuItem one = new JCheckBoxMenuItem("One"); 
JMenuItem two = new JCheckBoxMenuItem("Two"); 
JMenuItem three = new JCheckBoxMenuItem("Three"); 
JMenuItem four = new JCheckBoxMenuItem("Four"); 
menu.add(one); 
menu.add(two); 
menu.add(three); 
menu.add(four); 


final JButton button = new JButton("Click me"); 
button.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (!menu.isVisible()) { 
      Point p = button.getLocationOnScreen(); 
      menu.setInvoker(button); 
      menu.setLocation((int) p.getX(), 
        (int) p.getY() + button.getHeight()); 
      menu.setVisible(true); 
     } else { 
      menu.setVisible(false); 
     } 

    } 
}); 

one.addActionListener(new OpenAction(menu, button)); 
two.addActionListener(new OpenAction(menu, button)); 
three.addActionListener(new OpenAction(menu, button)); 
four.addActionListener(new OpenAction(menu, button)); 

JFrame frame = new JFrame(); 
JPanel panel = new JPanel(); 
panel.add(button); 
frame.getContentPane().add(panel); 
frame.pack(); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.setVisible(true); 
} 

private static class OpenAction implements ActionListener { 

    private JPopupMenu menu; 
    private JButton button; 

    private OpenAction(JPopupMenu menu, JButton button) { 
     this.menu = menu; 
     this.button = button; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     menu.show(button, 0, button.getHeight()); 
    } 
} 
} 
+0

不錯的解決問題的方法) – Denis 2016-01-19 09:03:30

相關問題