我写了一个扩展JToggleButton的类。自创JToggleButton:更改图标
一切工作正常,除了我不能更改按钮的图标。
这里是我的类代码:
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));
}
}
}
我使用的代码以这种方式在我的计划:
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")));
我在做什么错?
图标没有出现在程序中。
为了更好地提供帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-07-18 13:25:56