如何将 url 图像添加到 JButton

How to Add a url Image to a JButton

编辑

我使用下面的代码将背景图片添加到 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);
    }
}

只需使用the JButton Icon constructor, and pass it an ImageIcon.

例如而不是

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

JButton button = new JButton(new ImageIcon(new URL("http://i68.tinypic.com/2itmno6.jpg")));

由于 URL 构造函数抛出 MalformedURLException,您还需要将其包装在 try-catch 块中(并将您的按钮使用语句也放在那里)。要缩放它,您还需要一些 extra calls. Additionally, you can remove the visible parts of the button completely, by removing border and content。由于按钮后面有一个 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 是这里的图片尺寸,只需将它们更改为您的图片所需的尺寸即可。

更简单:使用 icon

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