如何在具有图像库的Java中创建自定义JButton? [英] How to create a custom JButton in java with an image base?

查看:69
本文介绍了如何在具有图像库的Java中创建自定义JButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了该线程(在Java中创建自定义按钮)通过扩展JButton类在Java中创建自定义按钮的方法,但是此线程上的所有解决方案都使用在Java中绘制的图形.

I recently read this thread (Creating a custom button in Java) on creating custom buttons in java by extending the JButton class, however all the solutions on this thread use graphics drawn in java.

我想基于在Photoshop中绘制的按钮图像来设置按钮.因此,我尝试将在该线程中读取的内容应用于此结果:

I wanted to have my button based on a button image I had drawn in photoshop. So I tried to apply what I read in that thread with this result:

import javax.swing.*;
import java.awt.*;

public class nextButton extends JButton {
    @Override
        protected void paintComponent(Graphics g) {
        Image image = new ImageIcon("nextButton.png").getImage();
        g.drawImage(image,0,0,this);
}

    @Override
    public Dimension getPreferredSize() {
        Dimension size = super.getPreferredSize();
        size.setSize(75, 150);
        return size;
    }
}

当我运行将这个按钮添加到JPanel的主程序时,它不会显示.我认为这可能是以下几种原因之一:

When I run the main program having added this button to a JPanel it doesn't display. I am assuming it could be one of several reasons:

a)JButton的大小与图像不匹配? b)我没有正确加载图像.在我的讲师给我的笔记中,他只用"imageName.png"写了显示图像代码,没有文件路径,所以我不知道这是否是正确的方法,或者程序如何知道如何加载图像. c)到目前为止我还不了解的其他东西.

a) The size of the JButton doesn't match the image? b) I haven't loaded the image properly. In the notes my lecturer gave me he writes out the display image code with just "imageName.png" with no file path so I have no idea if this is the correct way to do it, or how the program will know to load the image. c) Something else which is beyond my knowledge so far.

如果有人知道如何解决这个问题,我将非常感激.

If anyone knows how to solve this I'd be very grateful.

非常感谢!

推荐答案

我也早些时候问过这个问题.我发现效果最好的解决方案实际上是在执行此操作,而不是进行绘制.

I asked this question earlier as well. The solution I found worked best was actually doing this, instead of drawing.

ImageIcon icon = new ImageIcon("pathOfImageHere.png");
JButton button = new JButton(icon);

因此将按钮设置为图像.现在,我选择要做的是使按钮不可见并删除所有边框.所以我接下来做了这个:

So that sets the button to the image. Now what I chose to do was make the button invisible and remove all the borders. So I did this next:

button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);

这篇关于如何在具有图像库的Java中创建自定义JButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆