Exemple 2-1: Une simple SwingApplication (Sun Java Tutorial)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingApplication {
private static String labelPrefix = "Number of button clicks: ";
private int numClicks = 0;
public Component createComponents() {
// Define a label widget
final JLabel label = new JLabel(labelPrefix + "0 ");
// Define a press button widget
JButton button = new JButton("I'm a Swing button!");
// ALT-i will trigger it also
button.setMnemonic('i');
// add an actionPerformed method to the buttons Action Listener.
button.addActionListener(new ActionListener() {
// each time the user clicks, the text of the Label gets changed
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
});
label.setLabelFor(button);
// We need a container (panel) to put the label and the button
JPanel pane = new JPanel();
// A Border Factory will create an Empty Border we will use
pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
// We use a simple grid layout
pane.setLayout(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
return pane;
}
public static void main(String[] args) {
//Create the top-level container and add contents to it.
JFrame frame = new JFrame("SwingApplication");
SwingApplication app = new SwingApplication();
// The createComponents method will produce the pane with the 2 widgets
// We then can add it to the contents of our frame
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
//Finish setting up the frame, and show it.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
}
A retenir:
-
Définir un "top-level" container
public class SwingApplication {
...
public static void main(String[] args) {
...
JFrame frame = new JFrame("SwingApplication");
//..create the components to go into the frame...
//...stick them in a container (the content pane of the frame)
frame.getContentPane().add(contents, BorderLayout.CENTER);
// Finish setting up the frame (make sure people can close it), and show it.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
} }
final JLabel label = new JLabel(" ...... ");
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic('i');