Cannot set imageicon to JLabel, always get null

I am new to swing and trying to write a code that have a button on JFrame and click it can open a JFileChooser to choose an image, after user choose, it will display it on thr JFrame, but I keep getting a
`Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
and I found that I cannot set the selected image icon to the JPanel, this drives me crazy, help me please!!!
My code is:
public class ImageLoading extends JFrame{ private static final int FRAME_WIDTH = 500; private static final int FRAME_HEIFHT = 500; private BufferedImage mImage; private JFrame frm; private JPanel panel; private JButton button; String name,name1; public class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ String source=filechoose(); File inputFile = new File(source); System.out.println("File Directory: " + inputFile.toString()); try { mImage = ImageIO.read(inputFile); System.out.println("Buffered Image: " + mImage.toString()); } catch (IOException ex) { System.out.println(ex.getMessage()); } ImageIcon image = new ImageIcon(mImage); System.out.println("Image Icon: " + image.toString() + " ::: " +image.getIconHeight()); JLabel lb = new JLabel(image);// HERE I GET EXCEPTION System.out.println("Image Label: " + lb.toString()); panel.add(lb); panel.revalidate(); panel.repaint(); frm.pack(); } } public void imageLoading(){ frm = new JFrame("image loading test"); frm.setLayout(null); JLabel label2 = new JLabel("Open a picture"); button = new JButton("Open"); panel = new JPanel(); panel.setBounds(10, 10, 400, 400); panel.add(button); panel.add(label2); ImageLoading load = new ImageLoading(); ButtonListener listener = load.new ButtonListener(); button.addActionListener(listener); frm.add(panel); frm.setSize(FRAME_WIDTH,FRAME_HEIFHT); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } public String filechoose(){ JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { name = f.getName().toLowerCase(); return name.endsWith(".gif") || name.endsWith(".jpg") || name.endsWith(".jpeg") || f.isDirectory(); } public String getDescription() { return "Image files"; } }); int r = chooser.showOpenDialog(this); if (r == JFileChooser.APPROVE_OPTION) { name1 = chooser.getSelectedFile().getAbsolutePath(); StringBuffer sb=new StringBuffer(); sb.append(name1); int l=sb.length(); for(int i=0;iSilly question, but does System.out.println("Buffered Image: " + mImage.toString()); get printed out? Possibly there is an exception in the previous line which causes mImage to be null

以上就是Cannot set imageicon to JLabel, always get null的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏