DefaultListCellRendererを使用してJlistにJcheckboxを作成しました。ボタンをクリックするとすべてのチェックボックスの選択を解除する方法。私は別のクラスのメソッドを実行したlist.clearSelection()を使用しましたが、私の場合は動作しません。私はチェックボックスを使ってリストを作成するために次のコードを使用しました。私はDefaultlistCellRendererを使ってJlistにJcheckboxを作成しました。ボタンをクリックするとすべてのチェックボックスの選択を解除する方法
// ListSelectionListener implementation
public void valueChanged (ListSelectionEvent lse) {
if (! lse.getValueIsAdjusting()) {
removeListSelectionListener (this);
// remember everything selected as a result of this action
@SuppressWarnings("rawtypes")
HashSet newSelections = new HashSet();
int size = getModel().getSize();
for (int i=0; i<size; i++) {
if (getSelectionModel().isSelectedIndex(i)) {
newSelections.add (new Integer(i));
}
}
// turn on everything that was previously selected
Iterator it = selectionCache.iterator();
while (it.hasNext()) {
int index = ((Integer) it.next()).intValue();
getSelectionModel().addSelectionInterval(index, index);
}
// add or remove the delta
it = newSelections.iterator();
while (it.hasNext()) {
Integer nextInt = (Integer) it.next();
int index = nextInt.intValue();
if (selectionCache.contains (nextInt)){
getSelectionModel().removeSelectionInterval (index, index);
System.out.println("selection removed "+(index+1));}
else{
System.out.println("selection added "+(index+1));
getSelectionModel().addSelectionInterval (index, index);}
}
// save selections for next time
selectionCache.clear();
for (int i=0; i<size; i++) {
if (getSelectionModel().isSelectedIndex(i)) {
selectionCache.add (new Integer(i));
}
}
addListSelectionListener (this);
}
}
//チェックボックス付きリストです。
class CheckBoxListCellRenderer extends JComponent
implements ListCellRenderer {
DefaultListCellRenderer defaultComp;
public JCheckBox checkbox;
JLabel label=new JLabel(" ");
public CheckBoxListCellRenderer() {
setLayout (new BorderLayout());
defaultComp = new DefaultListCellRenderer();
add(label,BorderLayout.WEST);
checkbox = new JCheckBox();
// add(i,BorderLayout.EAST);
add (checkbox, BorderLayout.EAST);
add (defaultComp, BorderLayout.CENTER);
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus){
defaultComp.getListCellRendererComponent (list, value, index,
isSelected, cellHasFocus);
// defaultComp.setAlignmentX(10);
label.setText(" "+Integer.toString(index+1)+" ");
// defaultComp.setText(" "+Integer.toString(index+1)+" ");
/*
checkbox.setSelected (isSelected);
checkbox.setForeground (isSelected ?
listSelectionForeground :
listForeground);
checkbox.setBackground (isSelected ?
listSelectionBackground :
listBackground);
*/
checkbox.setSelected (isSelected);
return this;
}
}
我々は動的にするJListの項目を追加しています。チェックボックスはリスト内の項目とともに動的に追加されます。どのようにして配列を使用することができますか? –
動的に取得したテキストを使用してJCheckBoxの配列を作成できます。すべてが可能です。 –