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
| public class Panneau extends JPanel {
private final Map<String,Boolean> displayables;
public Panneau(String...displayables) {
this.displayables=new LinkedHashMap<>(); // LinkedHashMap pour conserver l'ordre
for(String displayable : displayables) {
this.displayables.put(displayable, false); // à l'initialisation rien n'est affiché
}
}
public void setDisplayed(String string, boolean selected) {
if ( SwingUtilities.isEventDispatchThread() ) {
if ( displayables.containsKey(string) ) {
if ( displayables.put(string, selected)!=selected ) { // on active/désactive et si ça a changé, alors on redessine
repaint();
}
}
else {
throw new RuntimeException(string+" doesn't exist");
}
}
else {
throw new RuntimeException("Must be invoked on Event Dispatch Thread");
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y=20;
for(Map.Entry<String, Boolean> displayable : displayables.entrySet()) { // on parcourt l'ensemble des trucs à afficher
if ( displayable.getValue() ) { // si c'est activé
g.drawString(displayable.getKey(), 0, y); // on dessine
y+=20;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] strings = {"Machin","Truc","Bidule"};
Panneau panneau = new Panneau(strings);
frame.add(panneau);
JPanel checkboxPanel = new JPanel();
for(String string : strings) {
JCheckBox box = new JCheckBox(string);
box.addActionListener(e-> panneau.setDisplayed(string, box.isSelected()));
checkboxPanel.add(box);
}
frame.add(checkboxPanel, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager