java - 无法将 ImageIcon 添加到 JFrame
问题描述
我一直在尝试向 a 添加图像,JFrame
但似乎无法完成。
我查看了在线教程和其他类似问题,但似乎没有任何效果。
ImageIcon wiz = new ImageIcon("wizard.png");
ImageIcon assassin = new ImageIcon("assassin.png");
JFrame frame = new JFrame("Select");
frame.setBounds(50, 50,1000, 1000);
JButton w = new JButton("Wizard");
JButton a = new JButton("Assasin");
JFrame f = new JFrame("Image");
JLabel img1 = new JLabel(wiz);
frame.setLayout(null);
f.setLayout(null);
f.setIconImage(wiz.getImage());
w.setBounds(30,380,100,60);
frame.add(w);
a.setBounds(200, 380, 100, 60);
frame.add(a);
f.setVisible(true);
frame.setVisible(true);
解决方案
我认为您程序中的主要问题是您尝试使用和在组件上对组件(例如JLabel
)进行绝对定位。setLayout(null)
setBounds()
在 Swing 中,放置组件的正确方法是使用布局管理器。有关如何使用布局管理器的详细信息,请参阅本教程: https ://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
作为一个示例程序,我已经在下面的程序中成功地设置了图像(作为JFrame
' 图标和内部JFrame
' 内容区域)。试试看。
这是我的示例的屏幕截图JFrame
。
import javax.swing.*;
public class FrameWithIcon
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Since I'm not setting a layout manager to contentPane, it's default (BorderLayout) is used
//This sets the image in JFrame's content area
f.getContentPane().add(new JLabel(new ImageIcon("star.png")));
//This sets JFrame's icon (shown in top left corner of JFrame)
f.setIconImage(new ImageIcon("star.png").getImage());
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
推荐阅读
- c# - 数据块中的异常处理
- linux - ubuntu 听不到 0.0.0.0
- android - 使用 Any 或 Generic 为函数定义多数据类型?
- android - 安卓模拟器。它可能完全删除 com.google.android.googlequicksearchbox?
- react-native - stopRecorder() 不起作用 - react-native-audio-recorder-player
- testing - Chef InSpec 检查 http 请求是否失败 [成功]
- c# - 纹理不可见的 3D 对象
- c# - 如何使用凭证,例如:login.cs 中的员工社会保险号以另一种形式反映,例如:expense.cs(无需手动输入))
- ios - 如何在 App Store 中获得 macOS 游戏的“控制器支持”和“玩家数量”徽章
- azure-functions - SCM_DO_BUILD_DURING_DEPLOYMENT 由 Azure Cli 显式设置为 false