2011-02-06 15 views
2

JCheckBoxコンポーネントをJComboBoxesに追加できますか?もしそうなら、どうですか?JCheckBoxコンポーネントをJComboBoxに追加できますか?

+0

使用 'CellRenderer'こちらをご確認ください

....私はGoogleでこのことを再確認できた場合を見てみましょう。 –

+0

JCheckBoxをJComboBoxに追加するとどういう意味ですか?達成したいのは何ですか? –

+0

私はJComboBoxを持っています。つまり、そのJComboBoxリストからいくつかの項目を選択する必要がある項目のリストです。 –

答えて

3

JComboBoxesをJComboBoxesにジミーする方法はありますが、JComboBoxesはセルエディタを使用せず、レンダラーのみを使用するため、JTableで使用するほど簡単ではありません。 JComboCheckBox
、ここを::これを行うにはCheck Boxes in a Combobox

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

public class CheckCombo implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     JComboBox cb = (JComboBox)e.getSource(); 
     CheckComboStore store = (CheckComboStore)cb.getSelectedItem(); 
     CheckComboRenderer ccr = (CheckComboRenderer)cb.getRenderer(); 
     ccr.checkBox.setSelected((store.state = !store.state)); 
    } 

    private JPanel getContent() 
    { 
     String[] ids = { "north", "west", "south", "east" }; 
     Boolean[] values = 
     { 
      Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE 
     }; 
     CheckComboStore[] stores = new CheckComboStore[ids.length]; 
     for(int j = 0; j < ids.length; j++) 
      stores[j] = new CheckComboStore(ids[j], values[j]); 
     JComboBox combo = new JComboBox(stores); 
     combo.setRenderer(new CheckComboRenderer()); 
     combo.addActionListener(this); 
     JPanel panel = new JPanel(); 
     panel.add(combo); 
     return panel; 
    } 

    public static void main(String[] args) 
    { 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.getContentPane().add(new CheckCombo().getContent()); 
     f.setSize(300,160); 
     f.setLocation(200,200); 
     f.setVisible(true); 
    } 
} 

/** adapted from comment section of ListCellRenderer api */ 
class CheckComboRenderer implements ListCellRenderer 
{ 
    JCheckBox checkBox; 

    public CheckComboRenderer() 
    { 
     checkBox = new JCheckBox(); 
    } 
    public Component getListCellRendererComponent(JList list, 
                Object value, 
                int index, 
                boolean isSelected, 
                boolean cellHasFocus) 
    { 
     CheckComboStore store = (CheckComboStore)value; 
     checkBox.setText(store.id); 
     checkBox.setSelected(((Boolean)store.state).booleanValue()); 
     checkBox.setBackground(isSelected ? Color.red : Color.white); 
     checkBox.setForeground(isSelected ? Color.white : Color.black); 
     return checkBox; 
    } 
} 

class CheckComboStore 
{ 
    String id; 
    Boolean state; 

    public CheckComboStore(String id, Boolean state) 
    { 
     this.id = id; 
     this.state = state; 
    } 
} 
+0

誰もが望んでいるとは思いません。リスト内でキーボードを使って移動してください – kleopatra

関連する問題