Bonjour à toutes et à tous,
j'ai créé un bouton et je voudrais qu'il s'affiche avec l'image que je lui donne qui est un rectangle bleu ciel. A l'exécution du code, il n'y a pas d'erreur, ni d'exception levée. Néanmoins mon bouton s'affiche en noir.
Je ne comprends pas.
Merci pour votre aide.
Voici le code
Le main
La classe Fenetre
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11 import javax.swing.JButton; import javax.swing.JFrame; public class BoutonInteragir extends JFrame{ public static void main(String[] args) { Fenetre fen = new Fenetre(); } }
La classe Bouton
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Fenetre extends JFrame { private JPanel container = new JPanel(); private JButton bouton = new Bouton("mon bouton"); public Fenetre(){ this.setTitle("Animation"); this.setSize(300,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); container.setBackground(Color.GREEN); container.setLayout(new BorderLayout()); container.add(bouton, BorderLayout.SOUTH); this.setContentPane(container); this.setVisible(true); } }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.io.File; import java.io.IOException; import javax.swing.JButton; import javax.imageio.ImageIO; public class Bouton extends JButton { private String name; private Image img; public Bouton(String str){ super(str); this.name = str; try {img = ImageIO.read(new File("C:\\Users\\moi\\Documents\\NetBeansProjects\\Boutoninteragir\\src\\bleu.jpg")); } catch (IOException e) { e.printStackTrace();} } public void paintComponent(Graphics g){ Graphics2D g2d = (Graphics2D)g; g2d.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); // J'indique maintenant que ce qui va être écrit sur mon //bouton sera de couleur rouge g2d.setColor(Color.RED); //j'écris sur mon bouton g2d.drawString(this.name, this.getWidth() / 2 - (this.getWidth() / 2 /4), (this.getHeight() / 2) + 5); } }
Partager