Initiation au swing
Incrémentation avec un bouton
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* A very simple Swing example.
*/
public class SwingExample {
/**
* The number of times the user has clicked the button.
*/
private long clickCount;
/**
* The main method: starting point of this application.
*
* @param arguments the unused command-line arguments.
*/
public static void main(final String[] arguments) {
new SwingExample().run();
}
/**
* Schedule a job for the event-dispatching thread: create and show this
* application's GUI.
*/
private void run() {
SwingUtilities.invokeLater(this::createAndShowGui);
}
/**
* Create the simple GUI for this application and make it visible.
*/
private void createAndShowGui() {
// Create the frame and make sure the application exits when the user closes
// the frame.
JFrame mainFrame = new JFrame("Counter");
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Add a simple button and label.
JPanel panel = new JPanel();
JButton button = new JButton("Click me!");
JLabel label = new JLabel("Click count: " + clickCount);
panel.add(button);
panel.add(label);
mainFrame.getContentPane().add(panel);
// Add an action listener to the button to increment the count displayed by
// the label.
button.addActionListener(actionEvent -> {
clickCount++;
label.setText("Click count: " + clickCount);
});
// Size the frame.
mainFrame.setBounds(80, 60, 400, 300);
//Center on screen
mainFrame.setLocationRelativeTo(null);
//Display frame
mainFrame.setVisible(true);
}
}
Résultat
Comme le bouton intitulé “Cliquez-moi!” est enfoncé, le nombre de clics augmentera d’un :
[![Programme en cours][1]][1]
[1] : http://i.stack.imgur.com/rH2OG.png
“Bonjour le monde!” sur le titre de la fenêtre avec compatibilité
En utilisant java.lang.Runnable
nous faisons notre “Hello World!” exemple disponible pour les utilisateurs Java avec des versions remontant jusqu’à la version 1.2 :
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Main {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
JFrame frame = new JFrame("Hello World!");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
}
});
}
}
“Bonjour le monde!” sur le titre de la fenêtre avec lambda
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Hello World!");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
});
}
}
Dans la méthode main
:
Sur la première ligne, SwingUtilities.invokeLater
est appelé et une expression lambda avec un bloc de code () -> {...}
lui est transmise. Cela exécute l’expression lambda transmise sur l’EDT, qui est l’abréviation de Event Dispatch Thread, au lieu du thread principal. Cela est nécessaire, car à l’intérieur du bloc de code de l’expression lambda, des composants Swing vont être créés et mis à jour.
Dans le bloc de code de l’expression lambda :
Sur la première ligne, une nouvelle instance de JFrame
appelée frame
est créée en utilisant new JFrame("Hello World!")
. Cela crée une instance de fenêtre avec “Hello World!” sur son titre. Ensuite, sur la deuxième ligne, le cadre
est configuré sur EXIT_ON_CLOSE
. Sinon, la fenêtre sera simplement fermée, mais l’exécution du programme restera active. La troisième ligne configure l’instance frame
pour avoir une largeur de 200 pixels et une hauteur de 100 pixels à l’aide de la méthode setSize
. Jusqu’à présent, l’exécution ne montrera rien du tout. Ce n’est qu’après avoir appelé setVisible(true)
sur la quatrième ligne que l’instance frame
est configurée pour apparaître à l’écran.