Self created JToggleButton: change icons
-
21-06-2021 - |
Question
I have written a class that extends JToggleButton.
Everything works fine, except that I can't change the icons of the button.
Here is my code of the class:
package be.blauweregen.lichtsturing;
import javax.swing.*;
import java.awt.*;
class MyToggleButton extends JToggleButton {
private static final long serialVersionUID = 1L;
String s;
public MyToggleButton(String str) {
super(str);
s = str;
}
public MyToggleButton(String str, Boolean sel) {
super(str, sel);
s = str;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.isSelected() && this.isEnabled()) { // manueel en aan
int w = getWidth();
int h = getHeight();
g.setColor(Color.green); // selected color
g.fillRect(0, 0, w, h);
g.setColor(Color.black); // selected foreground color
g.drawString(s, (w - g.getFontMetrics().stringWidth(s)) / 2 + 1,
(h + g.getFontMetrics().getAscent()) / 2 - 1);
setFont(new Font("Tahoma", Font.BOLD, 11));
} else if (this.isSelected() && !this.isEnabled()) { // automatisch en
// aan
int w = getWidth();
int h = getHeight();
g.setColor(Color.green); // selected color
g.fillRect(0, 0, w, h);
g.setColor(Color.black); // selected foreground color
g.drawString(s, (w - g.getFontMetrics().stringWidth(s)) / 2 + 1,
(h + g.getFontMetrics().getAscent()) / 2 - 1);
setFont(new Font("Tahoma", Font.PLAIN, 11));
} else if (!this.isSelected() && this.isEnabled()) { // manueel en uit
int w = getWidth();
int h = getHeight();
g.setColor(Color.red); // selected color
g.fillRect(0, 0, w, h);
g.setColor(Color.black); // selected foreground color
g.drawString(s, (w - g.getFontMetrics().stringWidth(s)) / 2 + 1,
(h + g.getFontMetrics().getAscent()) / 2 - 1);
setFont(new Font("Tahoma", Font.BOLD, 11));
} else if (!this.isSelected() && !this.isEnabled()) { // automatisch en
// uit
int w = getWidth();
int h = getHeight();
g.setColor(Color.red); // selected color
g.fillRect(0, 0, w, h);
g.setColor(Color.black); // selected foreground color
g.drawString(s, (w - g.getFontMetrics().stringWidth(s)) / 2 + 1,
(h + g.getFontMetrics().getAscent()) / 2 - 1);
setFont(new Font("Tahoma", Font.PLAIN, 11));
}
}
}
I use the code in this way in my program:
btnGangSanitair = new MyToggleButton("Gang sanitair");
btnGangSanitair.setSelectedIcon(new ImageIcon("Z:\\Development\\Java\\BlauweRegen\\famfamfam_silk_icons_v013\\icons\\application_edit.png"));
btnGangSanitair.setIcon(new ImageIcon(Client.class.getResource("/be.blauweregen.icons/arrow_refresh.png")));
What am I doing wrong?
The icons don't appear in the program.
Solution
Don't recreate and reload
ImageIcon
s on runtime, load allImageIcon
s as local variables once and only one time,Use
setBackground()
instead ofpaintComponent()
OTHER TIPS
In addition to mKorbel's comments, all your wonderful custom painting is over painting what the super call did, thus painting over your icon
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow