java - 如何将 url 图像添加到 JButton

标签 java swing jbutton

编辑 enter image description here

enter image description here

我使用下面的代码将背景图像添加到 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 , 并传递一个 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 block 中(并将您的按钮使用语句也放在那里)。要缩放它,您还需要一些 extra calls .此外,您可以通过 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 是这里的图像尺寸,只需将它们更改为您的图像所需的尺寸即可。

关于java - 如何将 url 图像添加到 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42582121/

相关文章:

java - GUI 测试 Java Swing 应用程序

Java - JProgressBar 不会更改值,JLabel 不会更改文本

java - 为什么这条线没有适当的抗锯齿渲染?

java - 如何实现 Jbutton 和事件监听器来关闭应用程序?

java - 在 JButton 的右上角画一些东西

java - apache Spark - 无法连接到远程 Spark 独立系统

java - 在运行时设置xmx

java - Android studio v0.3.2、gradle、google maps v2.0 没有找到类“com.google.android.gms.maps.MapFragment

java - MockMvc JsonPath 结果匹配器不匹配单个值

java - 从 ActionListener 获取按钮名称?