java - JButton 不在 GUI 中显示图标图像

标签 java swing user-interface icons jbutton

我正在尝试使用 GUI 显示 .png 图片。但是我在显示图片时遇到了问题。 我认为我已经隔离了我在说明中搞砸的地方,但似乎找不到可行的解决方案。

我在指示中被告知...

  • 将标题设置为实验室按钮
  • 创建两个 Icon 类型的局部变量:image1 和 image2。 使用基于 Image1 和 Image2 的新 ImageIcon 初始化它们 - 如下所示: Icon image1 = new ImageIcon(getClass().getResource("Image1.png"));
  • 使用基于 Image3 的新 ImageIcon 初始化字段 clickImage
  • 使用接受 image1 作为唯一参数的新 JButton 初始化字段 imgButton
  • 调用 imgButton 上的 setRolloverIcon 方法并将 image2 作为滚动图标传递
  • 将 imgButton 添加到此(ImageButton,它是一个 JFrame)

看来我需要创建一个方法来初始化 imgButton。但是如果我那样做,我不需要为每个图标图像创建一个新变量吗?比如

imgButton = new JButton(image1);
final JButton imgButton2 = new JButton(image2);
final JButton imgButton3 = new JButton(image3);

如果我能得到任何帮助,我将不胜感激。谢谢。

package ImageButton.Downloads;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class ImageButton extends JFrame
{


    private final JButton imgButton;
    private final Icon clickImage;

    public ImageButton() 
    {


        JFrame frame = new JFrame();
        frame.setTitle("Lab Button");

        Icon image1 = new ImageIcon(getClass().getResource("Image1.png"));
        Icon image2 = new ImageIcon(getClass().getResource("Image2.png"));
        clickImage = new ImageIcon(getClass().getResource("Image3.gif"));

        imgButton = new JButton(image1);

        imgButton.setRolloverIcon(image2);



    }


}

package ImageButton.Downloads;


import javax.swing.JFrame;

public class ImageButtonApp 
{

    public ImageButtonApp() 
    {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) 
    {
        ImageButton imageButton = new ImageButton();

        imageButton.setSize(660, 660);
        imageButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        imageButton.setVisible(true);


    }

}

最佳答案

您正在创建两个 JFrames,显示其中的一个,但将您的JButton 添加到一个 其中。换句话说,您的代码会忽略此建议:

Add the imgButton to this (ImageButton, which is a JFrame)

解决方案:只使用一个 JFrame,按照您的说明添加您的类,将您的 JButton 添加到它或添加到添加到 JFrame 的 JPanel,并显示它。

具体来说,改变这个:

JFrame frame = new JFrame(); // extra JFrame that's never used!
frame.setTitle("Lab Button");

为此:

super("Lab Button");

并在构造函数的末尾添加一个 add(imgButton);

关于java - JButton 不在 GUI 中显示图标图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29309992/

相关文章:

python - 文本框不会自动删除自身

android - 是否可以将 ConstraintLayout 放在 ScrollView 中?

java - Spring 批处理 : Stop the batch job if no items are written

java - org.w3c.dom.Node.insertBefore : NullPointerException, 错误?

java - 避免重新分配参数

java - JTextField 上的输入 validator 返回不正确

java - 如何从 JPanel 加载/保存图像

Java:从 Graphics 中获取图像并将其转换为临时 BufferedImage

java - 当只使用一个单元格时,如何在 Miglayout 中强制每行 4 个单元格且宽度相等?

java - gwt bootstrap 中带有切换按钮的水平控制组