如何将URL图像添加到JButton

1 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(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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Riv*_*ver 6

只要使用JButton Icon构造函数,并把它传递的ImageIcon.

而不是

JButton button = new JButton("want picture here");
Run Code Online (Sandbox Code Playgroud)

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

由于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
    // ...
}
Run Code Online (Sandbox Code Playgroud)

64x64是此处的图像尺寸,只需将它们更改为图像所需的尺寸即可.