1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package fr.unice.polytech.mediamanager.view;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
public class CheckCombo implements ActionListener
{
private String[] ids;
private Boolean[] values;
public CheckCombo(String[] ids,
Boolean[] values) {
this.ids = ids;
this.values = values;
}
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));
}
/**
* Prépare le contenu de la liste déroulante en fonction de la liste donnée en paramètre
* @param ids la liste à ajouter
* @param values les valeurs de cochage initial
* @return
*/
public JPanel getContent()
{
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);
String[] ids = { "north", "west", "south", "east" };
Boolean[] values = {Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE };
f.getContentPane().add(new CheckCombo(ids, values).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;
}
} |
Partager