Explain JFileChooser and Image Icon

1. JFileChooser

What it is:

JFileChooser is a Swing component that displays a dialog box for the user to select files or directories from the file system.

Features:

  • Allows opening and saving files.
  • Can be configured to select files, directories, or both.

Common Methods:

  • showOpenDialog(Component parent) – Opens a file chooser dialog for selecting a file.
  • showSaveDialog(Component parent) – Opens a dialog to specify where to save a file.
  • getSelectedFile() – Returns the selected file as a File object.

Example:

import javax.swing.*;
import java.io.File;

public class FileChooserExample {
    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser();
        int result = chooser.showOpenDialog(null);

        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = chooser.getSelectedFile();
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        }
    }
}

2. ImageIcon

What it is:

ImageIcon is a Swing class used to load and display images in components like JLabel, JButton, etc.

Features:

  • Supports image formats such as .jpg, .png, .gif.
  • Used to enhance GUI with icons or pictures.

Common Usage:

ImageIcon icon = new ImageIcon("image.png");
JLabel label = new JLabel(icon);

Example:

import javax.swing.*;

public class ImageIconExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("ImageIcon Demo");
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ImageIcon icon = new ImageIcon("example.jpg");
        JLabel label = new JLabel(icon);

        frame.add(label);
        frame.setVisible(true);
    }
}

Summary:

ComponentDescriptionCommon Use
JFileChooserDialog to select/open/save filesFile input/output in GUI apps
ImageIconLoads and displays images in GUIAdding icons to GUI components

Leave a Reply

Your email address will not be published. Required fields are marked *