Java 图像无法在Jbutton上显示
我不知道哪里出了问题,我尝试了所有可能的方法让图像显示在JButton上,但无法理解为什么getResource类会带来空指针。 我还反复检查了我使用的路径,但我提供的路径是正确的 请帮忙Java 图像无法在Jbutton上显示,java,swing,Java,Swing,我不知道哪里出了问题,我尝试了所有可能的方法让图像显示在JButton上,但无法理解为什么getResource类会带来空指针。 我还反复检查了我使用的路径,但我提供的路径是正确的 请帮忙 public class Media extends JPanel { //Declares our media player component private JPanel video_pnl; private JButton play_btn; private JLabel loc_lbl; priv
public class Media extends JPanel {
//Declares our media player component
private JPanel video_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
public Media(ArrayList<String> file_location) {
this.file_location = file_location;
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
play_btn = new JButton("Play");
ImageIcon img = new ImageIcon(this.getClass().getResource("a.png"));
play_btn.setIcon(img);
video_pnl.add(loc_lbl);
video_pnl.add(play_btn);
add(video_pnl);
increment++;
}
}
public static void main(String[] args) {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
file_location.add("A");
file_location.add("B");
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media mediaplayer = new Media(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
公共类媒体扩展JPanel{
//声明我们的媒体播放器组件
私人JPanel video_pnl;
私人按钮播放;
私人JLabel loc_lbl;
私有整数增量;
ArrayList文件的位置;
公共媒体(ArrayList文件位置){
this.file\u location=文件位置;
增量=0;
while(增量
您需要指定文件的路径。当您试图以steam的形式获取资源时,您所要做的就是添加两个字母表,从而产生
NullPointerException
。如果图像的名称确实是A
和B
,请指定扩展名 我测试了你的代码,效果很好。您的图像很可能位于错误的位置
如果只使用图像文件名作为路径,即“a.png”
,则图像需要与调用它的类位于同一个包中。比如说
ProjectRoot
src
some.package
Media.java
a.png
生成后,映像将被复制到类路径中,与
媒体位于同一个包中。类
能否显示您的目录结构?
ProjectRoot
src
some.package
Media.java
a.png