gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:09:06 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com