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
| public class Exemple2 extends JPanel {
private static final String[] COLORS = {"rouge","vert","orange","rose","gris","bleu"};
int c=-1;
public Exemple2() {
super(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
ButtonGroup buttonGroup = new ButtonGroup();
for(int i=0; i<COLORS.length; i++) {
JRadioButton button = new JRadioButton(COLORS[i]);
button.setActionCommand(String.valueOf(i));
buttonGroup.add(button);
panel.add(button);
}
add(panel);
JButton valider = new JButton("Valider");
valider.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( buttonGroup.getSelection()!=null ) {
c = Integer.parseInt(buttonGroup.getSelection().getActionCommand());
}
SwingUtilities.getWindowAncestor(Exemple2.this).dispose(); // on ferme la fenêtre
}
});
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(valider);
add(buttonPanel, BorderLayout.SOUTH);
}
public int getCouleurChoisie() {
return c;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Exemple 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Choisir couleur");
JPanel panel = new JPanel(new GridBagLayout()); // ça c'est juste pour centrer
panel.add(button);
frame.add(panel);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int choixCouleur = choisirCouleur(frame);
if ( choixCouleur==-1 ) {
JOptionPane.showMessageDialog(frame, "Vous n'avez pas choisi de couleur !");
}
else {
JOptionPane.showMessageDialog(frame, "Vous avez choisi la couleur " + COLORS[choixCouleur]);
}
}
});
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected static int choisirCouleur(JFrame owner) {
JDialog dialog = new JDialog(owner, true); // un dialogue modal, donc qui va bloquer l'exécution tant qu'on le ferme pas
Exemple2 exemple2 = new Exemple2();
dialog.add(exemple2);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true); // ici le code est bloqué tant que le dialogue est visible, donc la ligne suivant sera exécuté après cette fermeture
return exemple2.getCouleurChoisie(); // on retourne la couleur choisie au code appelant (exécuté par l'action listener du bouton de la fenêtre principale)
}
} |
Partager