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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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); } } } } |