Comment changer l’apparence des Applications Swing?
Le Java Swing nous permet de personnaliser l’interface graphique en changeant l’apparence (L&F). Look définit l’apparence générale des composants et Feel définit leur comportement. Les L&F sont des sous-classes de la classe LookAndFeel et chaque L&F est identifié par son nom de classe complet. Par défaut, le L&F est réglé sur Metal.
Pour définir le L&F, nous pouvons appeler la méthode setLookAndFeel() de la classe UIManager. L’appel à setLookAndFeel doit être effectué avant l’instanciation d’une classe Java Swing, sinon le Swing L&F par défaut sera chargé.
Exemple:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestLF extends JFrame implements ActionListener
{
private JRadioButton w, ml, mf;
private ButtonGroup groupBtn;
public TestLF()
{
setTitle("Changer l'apparence de mon application Swing");
w = new JRadioButton("Windows");
w.addActionListener(this);
ml = new JRadioButton("Metal");
ml.addActionListener(this);
mf = new JRadioButton("Motif");
mf.addActionListener(this);
groupBtn = new ButtonGroup();
groupBtn.add(w);
groupBtn.add(ml);
groupBtn.add(mf);
setLayout(new FlowLayout());
add(w);
add(ml);
add(mf);
setSize(250, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent actionevent)
{
String LookAndFeel;
if(actionevent.getSource() == w)
LookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
else if(actionevent.getSource() == mf)
LookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
else
LookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";
try {
UIManager.setLookAndFeel(LookAndFeel);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.out.println("Erreur lors de la définition du LookAndFeel..." + e);
}
}
public static void main(String args[])
{
new TestLF();
}
}
Sortie: Windows

Sortie: Metal

Sortie: Motif


