帮忙看下实现菱形按钮的代码错误?
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestButton extends JButton {
JFrame f;
JButton0 b0;
Image img;
JButton b;
ImageIcon ii;
public TestButton() {
init();
}
public void init() {
img = Toolkit.getDefaultToolkit().getImage(
TestButton.class.getResource( "1.jpg "));
ii = new ImageIcon(img);
f = new JFrame( "test ");
b0 = new JButton0( "OK ", img);
f.add(b0);
b0.setBounds(100, 100, 100, 100);
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(f, "hehe! ");
}
});
f.setLayout(new FlowLayout());
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[]) {
new TestButton();
}
}
class JButton0 extends JButton {
Image img;
String text;
public JButton0() {
this.setSize(100, 100);
}
public JButton0(Image img) {
this.img = img;
}
public JButton0(Icon icon) {
this.setIcon(icon);
}
public JButton0(String text) {
this.text = text;
}
public JButton0(String text, Image img) {
this.text = text;
this.img = img;
}
public void paint(Graphics g) {
int[] x = { 0, 50, 100, 50 };
int[] y = { 50, 0, 50, 100 };
g.drawPolygon(x, y, 4);
g.setColor(Color.blue);
g.fillPolygon(x, y, 4);
if (img != null) {
g.drawImage(img, 25, 25, this.getHeight() / 2, this.getWidth() / 2,
this);
}
g.setColor(Color.RED);
g.drawString(text, 43, 55);
}
}
在eclipse
运行错误提示
Uncaught error fetching image:
java.lang.NullPointerException at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:97)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:106)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
高手们帮忙改下??谢谢各位?
------解决方案--------------------img = Toolkit.getDefaultToolkit().getImage(