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
| import java.awt.Desktop;
import java.awt.FlowLayout;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Exemple extends JPanel {
private static final String FIELD_COULEUR = "couleur";
private final Map<String, JComboBox<Value>> params = new HashMap<>();
public Exemple() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
ajouteCombo(FIELD_COULEUR,"Couleur :", new Value("rouge","Rouge"), new Value("bleu","Bleu"), new Value("jaune","Jaune"));
JButton button = new JButton("Afficher");
button.addActionListener(e->showImage());
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(button);
add(buttonPanel);
}
private void showImage() {
StringBuilder fichier = new StringBuilder("image");
fichier.append('_');
fichier.append(getSelectedValue(FIELD_COULEUR));
fichier.append(".jpg");
showImage(new File(fichier.toString()));
}
private void showImage(File file) {
if ( file.exists() ) {
try {
Desktop.getDesktop().browse(file.getAbsoluteFile().toURI());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getSelectedValue(String field) {
JComboBox<Value> combo = params.get(field);
return ((Value)combo.getSelectedItem()).getValue();
}
private void ajouteCombo(String id, String label, Value...values) {
JComboBox<Value> combo = new JComboBox<>(values);
combo.setEditable(false);
params.put(id, combo);
JPanel panel = new JPanel();
panel.add(new JLabel(label, JLabel.RIGHT));
panel.add(combo);
add(panel);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Exemple");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Exemple());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class Value {
private final String value;
private final String label;
public Value(String value, String label) {
this.value=value;
this.label=label;
}
public String getValue() {
return value;
}
public String getLabel() {
return label;
}
@Override
public String toString() {
return label;
}
}
} |
Partager