Java 如何将url图像添加到JButton

Java 如何将url图像添加到JButton,java,swing,jbutton,Java,Swing,Jbutton,编辑 我使用下面的代码将背景图像添加到JPanel,问题是我无法找到将图像添加到JButton的方法。。有什么想法吗 public void displayGUI() { JFrame frame = new JFrame("Painting Example"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(4

编辑

我使用下面的代码将背景图像添加到
JPanel
,问题是我无法找到将图像添加到
JButton
的方法。。有什么想法吗

    public void displayGUI() {
    JFrame frame = new JFrame("Painting Example");


    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(440, 385);
    JPanel panel = new JPanel();
    frame.add(panel);

    JButton button = new JButton("want picture here");
    panel.add(button);


    button.addActionListener(new Action7());
}

class Custom4 extends JPanel {

    public BufferedImage image;

    public Custom4() {
        try {

            image = ImageIO.read(new URL("http://i68.tinypic.com/2itmno6.jpg"));

        } catch (IOException ioe) {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    public Dimension getPreferredSize() {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    public void paintComponent(Graphics x) {
        super.paintComponent(x);
        x.drawImage(image, 0, 0, this);
    }
}
只需使用,并传递一次

例如,代替

JButton button = new JButton("want picture here");

由于URL构造函数抛出了一个
MalformedURLException
,您还需要将其包装在一个try-catch块中(并将您的按钮使用语句也放在其中)。要扩展它,还需要一些。此外,您可以通过以下方式完全删除按钮的可见部分。由于按钮后面有一个
JPanel
,因此还需要将其设置为透明。完整代码如下:

try {
    JButton button = new JButton(new ImageIcon(((new ImageIcon(
        new URL("http://i68.tinypic.com/2itmno6.jpg"))
        .getImage()
        .getScaledInstance(64, 64, java.awt.Image.SCALE_SMOOTH)))));
    button.setBorder(BorderFactory.createEmptyBorder());
    button.setContentAreaFilled(false);
    panel.setOpaque(false);
    panel.add(button);

    button.addActionListener(new Action7());
} 
catch (MalformedURLException e) {
    // exception handler code here
    // ...
}
64x64是此处的图像尺寸,只需将其更改为图像所需的尺寸。

只需使用,并传递一个

例如,代替

JButton button = new JButton("want picture here");

由于URL构造函数抛出了一个
MalformedURLException
,您还需要将其包装在一个try-catch块中(并将您的按钮使用语句也放在其中)。要扩展它,还需要一些。此外,您可以通过以下方式完全删除按钮的可见部分。由于按钮后面有一个
JPanel
,因此还需要将其设置为透明。完整代码如下:

try {
    JButton button = new JButton(new ImageIcon(((new ImageIcon(
        new URL("http://i68.tinypic.com/2itmno6.jpg"))
        .getImage()
        .getScaledInstance(64, 64, java.awt.Image.SCALE_SMOOTH)))));
    button.setBorder(BorderFactory.createEmptyBorder());
    button.setContentAreaFilled(false);
    panel.setOpaque(false);
    panel.add(button);

    button.addActionListener(new Action7());
} 
catch (MalformedURLException e) {
    // exception handler code here
    // ...
}

64x64是此处的图像尺寸,只需将其更改为图像所需的尺寸。

更简单:使用


它要简单得多:使用

BufferedImage img = ImageIO.read(new URL(url));
JButton button = new JButton(new ImageIcon(img));