Java JButton不是';t在GUI中显示图标图像
我正在尝试使用GUI显示.png图片。但是我在图片显示方面遇到了问题。 我想我已经隔离了我在指令中弄乱的地方,但似乎找不到有效的解决方案 在我的指示中我被告知Java JButton不是';t在GUI中显示图标图像,java,swing,user-interface,icons,jbutton,Java,Swing,User Interface,Icons,Jbutton,我正在尝试使用GUI显示.png图片。但是我在图片显示方面遇到了问题。 我想我已经隔离了我在指令中弄乱的地方,但似乎找不到有效的解决方案 在我的指示中我被告知 将标题设置为“实验室”按钮 创建两个Icon类型的局部变量:image1和image2。 使用基于Image1和Image2的新ImageIcon初始化它们-如下所示: Icon image1=新的ImageIcon(getClass().getResource(“image1.png”) 使用基于Image3的新ImageIcon初始
- 将标题设置为“实验室”按钮
- 创建两个Icon类型的局部变量:image1和image2。 使用基于Image1和Image2的新ImageIcon初始化它们-如下所示: Icon image1=新的ImageIcon(getClass().getResource(“image1.png”)李>
- 使用基于Image3的新ImageIcon初始化字段clickImage
- 使用接受image1作为唯一参数的新JButton初始化字段imgButton
- 在imgButton上调用方法setRolloverIcon,并将image2作为滚动图标传递
- 将imgButton添加到此(ImageButton,它是JFrame)
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添加到其中一个。换句话说,您的代码忽略此rec: 将imgButton添加到此(ImageButton,它是JFrame) 解决方案:只使用一个JFrame,按照说明将类添加到它或添加到JFrame的JPanel中,并显示它 具体来说,改变这一点:
JFrame frame = new JFrame(); // extra JFrame that's never used!
frame.setTitle("Lab Button");
为此:
super("Lab Button");
并添加一个add(imgButton)代码>位于构造函数的末尾