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)高手们帮忙改下??谢谢各位?

解决方案 »

  1.   

    img = Toolkit.getDefaultToolkit().getImage(
    TestButton.class.getResource("1.jpg")); // 没读出图片来
    或者用
    ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("1.jpg"));
      

  2.   

    img = Toolkit.getDefaultToolkit().getImage(
    TestButton.class.getResource("1.jpg")); // 没读出图片来
    或者用
    ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("1.jpg"));
    ----------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------
    谢谢1楼的,改了下,现在没有错误了,但是出来的FRAME是空白的没有按钮,怎么把按钮显示出来啊。
      

  3.   

    我找出来问题了,
    f.setLayout(new FlowLayout());错了,已经设置过位置了。
    应该是f.setLayout(null);