Skip to main content

Java ImageViewer

Postingan ini membahas sebuah aplikasi yang disebut ImageViewer. Sesuai dengan namanya, aplikasi ImageViewer ini digunakan untuk membuka dan melihat file gambar. Aplikasi ini bisa menampilkan gambar dalam format JPEG dan PNG. Aplikasi ini cukup menarik untuk dibuat.

Aplikasi ImageViewer ini dibuat menggunakan bahasa pemrograman Java dan menggunakan IDE BlueJ. Dalam aplikasi ini, Graphical User Interface atau GUI digunakan untuk membuat tampilan yang terdiri dari windows, menu, tombol, dan komponen grafis lainnya. Komponen ini membuat aplikasi lebih terlihat seperti aplikasi-aplikasi "biasa" yang digunakan oleh orang-orang.

AWT dan Swing

Java memiliki beberapa libary GUI. Yang tertua disebut AWT (Abstract Window Toolkit). Selanjutnya, sebuah libary GUI yang lebih ditingkatkan, yang disebut Swing, ditambahkan ke Java.

Swing memakai beberapa kelas AWT dan mengganti beberapa kelas AWT dengan versinya, dan menambahkan banyak kelas. Versi Swing telah diidentifikasi dengan penambahan huruf J di awal nama kelas.

ImageViewer terdiri dari kelas-kelas sebagai berikut:

  • ImageViewer
  • ImagePanel
  • ImageFileManager
  • OFImage

Berikut ini adalah gambar diagram kelas dari ImageViewer.


The ImageViewer Class

Kelas ImageViewer adalah kelas utama dari aplikasai image viewer. Kelas ini membangun dan menampilkan GUI aplikasi dan menginisialisasi semua komponen-komponen lainnya.

Implementation of The ImageViewer Class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * ImageViewer is the main class of the image viewer application. It builds and
 * displays the application GUI and initialises all other components.
 * 
 * To start the application, create an object of this class.
 * 
 * @author Ramadhan Arif Hardijansyah.
 * @version 0.4
 */
public class ImageViewer
{
    private JFrame frame;
    private ImagePanel imagePanel;
    
    /**
     * Create an ImageViewer show it on screen.
     */
    public ImageViewer()
    {
        makeFrame();
    }


    // ---- implementation of menu functions ----
    
    /**
     * Open function: open a file chooser to select a new image file.
     */
    private void openFile()
    {
        OFImage image = ImageFileManager.getImage();
        imagePanel.setImage(image);
        frame.pack();
    }
    
    /**
     * Quit function: quit the application.
     */
    private void quit()
    {
        System.exit(0);
    }
    
    // ---- swing stuff to build the frame and all its components ----
    
    /**
     * Create the Swing frame and its content.
     */
    private void makeFrame()
    {
        frame = new JFrame("ImageViewer");
        makeMenuBar(frame);
        
        Container contentPane = frame.getContentPane();
        
        imagePanel = new ImagePanel();
        contentPane.add(imagePanel);

        // building is done - arrange the components and show        
        frame.pack();
        frame.setVisible(true);
    }
    
    /**
     * Create the main frame's menu bar.
     * @param frame   The frame that the menu bar should be added to.
     */
    private void makeMenuBar(JFrame frame)
    {
        final int SHORTCUT_MASK =
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();


        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);
        
        // create the File menu
        JMenu fileMenu = new JMenu("File");
        menubar.add(fileMenu);
        
        JMenuItem openItem = new JMenuItem("Open");
            openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));
            openItem.addActionListener(e -> openFile());
        fileMenu.add(openItem);

        JMenuItem quitItem = new JMenuItem("Quit");
            quitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
            quitItem.addActionListener(e -> quit());
        fileMenu.add(quitItem);

    }
}

The ImagePanel Class

Kelas ImagePanel mengimplementasikan komponen Swing yang dibuat khusus untuk menampilkan OFImage. Komponen Swing yang dibuat khusus bisa dengan mudah dibuat dengan menulis subkelas dari komponen yang telah dibuat. Dengan demikian, hal itu bisa dimasukkan ke dalam Swing container dan ditampilkan pada GUI kita seperti komponen Swing lainnya. Kelas ini dibangun sebagai subkelas dari JComponent dengan penambahan fungsionalitas atas pengaturan sebuah OFImage yang akan ditampilkan pada permukaan komponen ini.

Implementation of The ImagePanel Class

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;

/**
 * An ImagePanel is a Swing component that can display an OFImage.
 * It is constructed as a subclass of JComponent with the added functionality
 * of setting an OFImage that will be displayed on the surface of this
 * component.
 * 
 * @author Ramadhan Arif Hardijansyah.
 * @version 1.0
 */
public class ImagePanel extends JComponent
{
    // The current width and height of this panel
    private int width, height;

    // An internal image buffer that is used for painting. For
    // actual display, this image buffer is then copied to screen.
    private OFImage panelImage;

    /**
     * Create a new, empty ImagePanel.
     */
    public ImagePanel()
    {
        width = 360;    // arbitrary size for empty panel
        height = 240;
        panelImage = null;
    }

    /**
     * Set the image that this panel should show.
     * 
     * @param image  The image to be displayed.
     */
    public void setImage(OFImage image)
    {
        if(image != null) {
            width = image.getWidth();
            height = image.getHeight();
            panelImage = image;
            repaint();
        }
    }
    
    /**
     * Clear the image on this panel.
     */
    public void clearImage()
    {
        Graphics imageGraphics = panelImage.getGraphics();
        imageGraphics.setColor(Color.LIGHT_GRAY);
        imageGraphics.fillRect(0, 0, width, height);
        repaint();
    }
    
    // The following methods are redefinitions of methods
    // inherited from superclasses.
    
    /**
     * Tell the layout manager how big we would like to be.
     * (This method gets called by layout managers for placing
     * the components.)
     * 
     * @return The preferred dimension for this component.
     */
    public Dimension getPreferredSize()
    {
        return new Dimension(width, height);
    }
    
    /**
     * This component needs to be redisplayed. Copy the internal image 
     * to screen. (This method gets called by the Swing screen painter 
     * every time it want this component displayed.)
     * 
     * @param g The graphics context that can be used to draw on this component.
     */
    public void paintComponent(Graphics g)
    {
        Dimension size = getSize();
        g.clearRect(0, 0, size.width, size.height);
        if(panelImage != null) {
            g.drawImage(panelImage, 0, 0, null);
        }
    }
}

The ImageFileManager Class

Kelas ImageFileManager adalah sebuah kelas utilitas kecil dengan method static untuk memuat dan menyimpan gambar. Kelas ini bisa menawarkan method untuk membuka sebuah dialog file-chooser untuk membiarkan pengguna memilih sebuah gambar yang ingin dibuka.

File pada disk bisa dalam bentuk format gambar JPG atau PNG. Untuk file yang ditulis dengan kelas ini, formatnya ditentukan dengan constant IMAGE_FORMAT.

Implementation of The ImageFileManager Class

import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;

/**
 * ImageFileManager is a small utility class with static methods to load
 * and save images.
 * 
 * The files on disk can be in JPG or PNG image format. For files written
 * by this class, the format is determined by the constant IMAGE_FORMAT.
 * 
 * @author Ramadhan Arif Hardijansyah.
 * @version 1.0
 */
public class ImageFileManager
{
    // A constant for the image format that this writer uses for writing.
    // Available formats are "jpg" and "png".
    private static final String IMAGE_FORMAT = "jpg";
    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
    
    /**
     * Open a file chooser and let the user select an image file in the file
     * system. Then read an image file from disk and return it as an image. This method
     * can read JPG and PNG file formats. In case of any problem (e.g the file does
     * not exist, is in an undecodable format, or any other read error) this method
     * returns null.
     * 
     * @return       The image object or null is it was not a valid image file.
     */
    public static OFImage getImage()
    {
        int returnVal = fileChooser.showOpenDialog(null);

        if(returnVal != JFileChooser.APPROVE_OPTION) {
            return null;  // cancelled
        }
        File selectedFile = fileChooser.getSelectedFile();
        return loadImage(selectedFile);
    }

    /**
     * Read an image file from disk and return it as a BufferedImage. This method
     * can read JPG and PNG file formats. In case of any problem (e.g the file does
     * not exist, is in an undecodable format, or any other read error) this method
     * returns null.
     * 
     * @param imageFile  The image file to be loaded.
     * @return           The image object or null if it was not a valid image file.
     */
    public static OFImage loadImage(File imageFile)
    {
        try {
            BufferedImage image = ImageIO.read(imageFile);
            if(image == null || (image.getWidth(null) < 0)) {
                // we could not load the image - probably invalid file format
                return null;
            }
            return new OFImage(image);
        }
        catch(IOException exc) {
            return null;
        }
    }

    /**
     * Write an image file to disk. The file format is JPG. In case of any problem
     * the method just silently returns.
     * 
     * @param image  The image to be saved.
     * @param file   The file to save to.
     */
    public static void saveImage(OFImage image, File file)
    {
        try {
            ImageIO.write(image, IMAGE_FORMAT, file);
        }
        catch(IOException exc) {
            return;
        }
    }
}

The OFImage Class

Kelas OFImage adalah sebuah kelas yang mendefinisikan sebuah gambar dalam format OF (Object First). Kelas ini diimplementasikan sebagai sebuah subkelas dari kelas standar Java BufferedImage (dari package java.awt.image).

Method terpenting dari OFImage bagi kita adalah getPixel dan setPixel untuk membaca dan memodifikasi pixel-pixel tunggal, serta getHeight dan getWidth untuk menemukan ukuran gambar.

Implementation of The OFImage Class

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

/**
 * OFImage is a class that defines an image in OF (Objects First) format.
 * 
 * @author Ramadhan Arif Hardijansyah.
 * @version 1.0
 */
public class OFImage extends BufferedImage
{
    /**
     * Create an OFImage copied from a BufferedImage.
     * @param image The image to copy.
     */
    public OFImage(BufferedImage image)
    {
         super(image.getColorModel(), image.copyData(null), 
               image.isAlphaPremultiplied(), null);
    }

    /**
     * Create an OFImage with specified size and unspecified content.
     * @param width The width of the image.
     * @param height The height of the image.
     */
    public OFImage(int width, int height)
    {
        super(width, height, TYPE_INT_RGB);
    }

    /**
     * Set a given pixel of this image to a specified color. The
     * color is represented as an (r,g,b) value.
     * @param x The x position of the pixel.
     * @param y The y position of the pixel.
     * @param col The color of the pixel.
     */
    public void setPixel(int x, int y, Color col)
    {
        int pixel = col.getRGB();
        setRGB(x, y, pixel);
    }
    
    /**
     * Get the color value at a specified pixel position.
     * @param x The x position of the pixel.
     * @param y The y position of the pixel.
     * @return The color of the pixel at the given position.
     */
    public Color getPixel(int x, int y)
    {
        int pixel = getRGB(x, y);
        return new Color(pixel);
    }
}

Berikut ini adalah langkah-langkah untuk mencoba ImageViewer.

1. Buat objek dari kelas ImageViewer.

2. Jika sebuah jendela kosong baru berjudul "ImageViewer" sudah muncul, maka aplikasi ImageViewer sudah berhasil dijalankan.

3. Untuk mencoba membuka file gambar, klik File pada menubar, lalu klik Open. Anda juga bisa menggunakan shortcut Ctrl+O.

4. Pada jendela baru, pilih sebuah file gambar yang memiliki format JPEG atau PNG. Lalu klik tombol Open.

5. Pada jendela ImageViewer, terlihat file gambar yang kita pilih.

6. Apabila sudah selesai, anda bisa keluar dari aplikasi dengan cara klik File pada menubar, lalu klik Quit. Atau menggunakan shortcut Ctrl+Q.

Sekian post tentang ImageViewer ini. Semoga bermanfaat.

Comments

Popular posts from this blog

Java Exception Handling

Postingan ini membahas sebuah program tambahan tentang exception handling . Disini seolah-olah bertindak sebagai tester. Dan program yang akan dimodifikasi adalah program SimpleCalculator . Program SimpleCalculator adalah sebuah program kalkulator sederhana yang menggunakan switch..case dalam Java. Program bisa melakukan operasi pertambahan, pengurangan, perkalian, dan pembagian. Program SimpleCalculator ini dibuat menggunakan bahasa pemrograman Java dan bisa di-compile menggunakan IDE BlueJ. Dalam aplikasi ini, dicoba untuk ditambahkan catch exception untuk mengetes bagimana pembagian suatu angka dengan angka nol. Dicari modul kelas yang merupakan operasi pembagian dan dimodifikasi agar bisa mengetes operasi pembagian dengan penyebut angka nol. Exception Handling Exception Handling adalah sebuah proses menanggapi terjadinya exception, menangani runtime error seperti ClassNotFound, IO, SQL, Remote , dsb.  Exception adalah suatu kondisi tidak normal yang membutuhkan pemrosesan khu

Website Registrasi Kuliah Tatap Muka

  Postingan berikut menjelaskan dokumentasi proses pembuatan website registrasi kuliah tatap muka. Website di-hosting menggunakan github pages yang dapat meng-host  static webpages . Link Website Catalog Product:  https://dani-ramadhan7.github.io/registrasi/index.html Langkah-Langkah Pembuatan Website Registrasi Kuliah Tatap Muka 1. Ikuti langkah-langkah pada website pembelajaran. Salah satu website yang cukup bagus untuk dipelajari adalah  belajarphp.net/tutorial-validasi-form-menggunakan-html-dan-javascript/ . Coba untuk menulis ulang contoh kode pada modul pembelajaran atau langsung memilih bagian-bagian kode yang diinginkan untuk digunakan. 2. Buat file html baru, buat page html dengan acuan modul pembelajaran. Lakukan modifikasi dan penambahan. HTML JavaScript 3. Untuk desain, digunakan file css sebagaimana yang digunakan pada website, yakni menggunakan  https://stackpath.bootstrapcdn.com/bootstrap/

Website Pendaftaran Siswa Baru

Postingan berikut menjelaskan dokumentasi website Pendaftaran Siswa Baru. Website di-hosting di local PC menggunakan XAMPP serta menggunakan MySQL untuk menangani database dari para pendaftarnya. Halaman Utama Pendaftar dapat melakukan pendaftaran pada menu Daftar Baru atau melihat list pendaftar pada bagian Pendaftar. Formulir Pendaftaran Siswa Baru Disini, siswa dapat mengisikan formulir pendaftaran dan men-submit. Menu Pendaftar Menu Pendaftar isi menyajikan tabel yang berisi siswa yang telah mendaftar. Dapat dilakukan tindakan Edit atau Hapus pada setiap baris. Formulir Edit Siswa Formulir Edit Siswa menyajikan formulir untuk mengedit data siswa yang telah mendaftar. Setelah melakukan edit, dapat menekan tombol Simpan untuk menyimpan data siswa yang telah diperbarui. Source Code Untuk source code dari website Pendaftaran Siswa Baru ini adalah sebagai berikut. Link GitHub Gist:  https://gist.github.com/dani-ramadhan7/7838e42982a0488fcc170