This Java program is a simple image viewer application designed for novice Java programmers. The program utilizes the Swing library to create a graphical user interface (GUI) with a JFrame, JPanel, and JButton components. The main functionality of the Java program is to select an image file through a JFileChooser dialog, load the selected image and display it within the JPanel. The JFrame provides the main window, and the myPanel class extends JPanel to handle the painting of the image on the screen.
The application is structured in a way that encourages readability and adherence to basic Swing practices. It is an excellent starting point for those looking to understand how to create a basic GUI application in Java and work with images in the process.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Photo extends JFrame {
private static JFrame frame;
private static Image img;
private static JFileChooser fileChooser;
private static myPanel panel;
public static void main(String st[]) {
frame = new JFrame("FIAZ GUL KHAN JADOON");
Toolkit kk = frame.getToolkit();
Dimension dd = kk.getScreenSize();
dd.width = 800;
dd.height = 570;
frame.setBounds(0, 0, dd.width, dd.height);
frame.getContentPane().setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(frame);
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
String filePath = selectedFile.getPath();
ImageIcon icon = new ImageIcon(filePath);
img = icon.getImage();
panel = new myPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
static class myPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
}
}