Java Swing How to - Display an image in a label at runtime








Question

We would like to know how to display an image in a label at runtime.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.net.URL;
// w ww .j av a  2 s  . com
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class Main {
  JFrame frame = new JFrame();
  JFileChooser fileChooser;
  JLabel iconLabel;

  private final class SelectImageAction extends AbstractAction {
    private SelectImageAction(final String name) {
      super(name);
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
      int option = fileChooser.showOpenDialog(frame);
      if (option != JFileChooser.APPROVE_OPTION) {
        return;
      }
      final File selectedFile = fileChooser.getSelectedFile();

      URL url = null;
      try {
        url = selectedFile.toURI().toURL();
      } catch (Exception e1) {
        System.out.println(e1);
      }

      ImageIcon icon = new ImageIcon(url);
      iconLabel.setIcon(icon);
    }
  }

  public Main() {

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    iconLabel = new JLabel("Please select an image.");
    iconLabel.setHorizontalAlignment(SwingConstants.CENTER);

    fileChooser = new JFileChooser();

    frame.add(iconLabel, BorderLayout.CENTER);
    frame.add(new JButton(new SelectImageAction("Select Image...")),
        BorderLayout.SOUTH);
    frame.setBounds(16, 16, 640, 480);
    frame.setVisible(true);
  }

  public static void main(final String[] args) throws Exception {
    new Main();
  }
}