Menampilkan gambar pada Java dengan BlueJ

Untuk mempercantik dan mempermudah user dalam menjalankan software kita, maka kita memerlukan adanay GUI.

Kali ini kita akan membuat sebuah contoh penggunaan GUI dengan program ImageViewer atau penampil gambar sederhana. Class yang dibutuhkan dan relasinya adalah sebagai berikut:


Class ImageViewer merupakan sebuah main class dan hanya mengundang method – method class lain, dengan source code:

1.  /**

2.    * ImageViewer is the main class of the image viewer application.

3.    *  

4.    * To start the application, create an object of this class.

5.    *  

6.    * @author Aufi Fillah

7.    * @version 1.0

8.    */

9.   

10. import java.awt.*;

11. import java.awt.event.*;

12. import java.awt.image.*;

13. import javax.swing.*;

14. import java.io.File;

15.  

16. public class ImageViewer

17. {

18.    // static fields:

19.    private static final String VERSION = "Version 1.0";

20.    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));

21.    // fields:

22.    private JFrame frame;

23.    private ImagePanel imagePanel;

24.    private JLabel filenameLabel;

25.    private JLabel statusLabel;

26.    private OFImage currentImage;

27.    /**

28.     * Create an ImageViewer show it on screen.

29.     */

30.    public ImageViewer()

31.    {

32.      currentImage = null;

33.      makeFrame();

34.    }

35.    /**

36.     * Open function: open a file chooser to select a new image file.

37.     */

38.    private void openFile()

39.    {

40.      int returnVal = fileChooser.showOpenDialog(frame);

41.      if(returnVal != JFileChooser.APPROVE_OPTION) {

42.        return; // cancelled

43.      }

44.      File selectedFile = fileChooser.getSelectedFile();

45.      currentImage = ImageFileManager.loadImage(selectedFile);

46.      if(currentImage == null) {  // image file was not a valid image

47.        JOptionPane.showMessageDialog(frame,

48.            "The file was not in a recognized image file format.",

49.            "Image Load Error",

50.            JOptionPane.ERROR_MESSAGE);

51.        return;

52.      }

53.      imagePanel.setImage(currentImage);

54.      showFilename(selectedFile.getPath());

55.      showStatus("File loaded.");

56.      frame.pack();

57.    }

58.    /**

59.     * Close function: close the current image.

60.     */

61.    private void close()

62.    {

63.      currentImage = null;

64.      imagePanel.clearImage();

65.      showFilename(null);

66.    }

67.    /**

68.     * Quit function: quit the application.

69.     */

70.    private void quit()

71.    {

72.      System.exit(0);

73.    }

74.    /**

75.     * 'Darker' function: make the picture darker.

76.     */

77.    private void makeDarker()

78.    {

79.      if(currentImage != null) {

80.        currentImage.darker();

81.        frame.repaint();

82.        showStatus("Applied: darker");

83.      }

84.      else {

85.        showStatus("No image loaded.");

86.      }

87.    }

88.    /**

89.     * 'Lighter' function: make the picture lighter

90.     */

91.    private void makeLighter()

92.    {

93.      if(currentImage != null) {

94.        currentImage.lighter();

95.        frame.repaint();

96.        showStatus("Applied: lighter");

97.      }

98.      else {

99.        showStatus("No image loaded.");

100.       }

101.     }

102.     /**

103.      * 'threshold' function: apply the threshold filter

104.      */

105.     private void threshold()

106.     {

107.       if(currentImage != null) {

108.         currentImage.threshold();

109.         frame.repaint();

110.         showStatus("Applied: threshold");

111.       }

112.       else {

113.         showStatus("No image loaded.");

114.       }

115.     }

116.     /**

117.      * 'Lighter' function: make the picture lighter

118.      */

119.     private void showAbout()

120.     {

121.       JOptionPane.showMessageDialog(frame,  

122.             "ImageViewer\n" + VERSION,

123.             "About ImageViewer",  

124.             JOptionPane.INFORMATION_MESSAGE);

125.     }

126.     // ---- support methods ----

127.     /**

128.      * Display a file name on the appropriate label.

129.      * @param filename The file name to be displayed.

130.      */

131.     private void showFilename(String filename)

132.     {

133.       if(filename == null) {

134.         filenameLabel.setText("No file displayed.");

135.       }

136.       else {

137.         filenameLabel.setText("File: " + filename);

138.       }

139.     }

140.     /**

141.      * Display a status message in the frame's status bar.

142.      * @param text The status message to be displayed.

143.      */

144.     private void showStatus(String text)

145.     {

146.       statusLabel.setText(text);

147.     }

148.     // ---- swing stuff to build the frame and all its components ----

149.     /**

150.      * Create the Swing frame and its content.

151.      */

152.     private void makeFrame()

153.     {

154.       frame = new JFrame("ImageViewer");

155.       makeMenuBar(frame);

156.       Container contentPane = frame.getContentPane();

157.       // Specify the layout manager with nice spacing

158.       contentPane.setLayout(new BorderLayout(6, 6));

159.       filenameLabel = new JLabel();

160.       contentPane.add(filenameLabel, BorderLayout.NORTH);

161.       imagePanel = new ImagePanel();

162.       contentPane.add(imagePanel, BorderLayout.CENTER);

163.       statusLabel = new JLabel(VERSION);

164.       contentPane.add(statusLabel, BorderLayout.SOUTH);

165.       // building is done - arrange the components and show    

166.       showFilename(null);

167.       frame.pack();

168.       Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

169.       frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);

170.       frame.setVisible(true);

171.     }

172.     /**

173.      * Create the main frame's menu bar.

174.      * @param frame  The frame that the menu bar should be added to.

175.      */

176.     private void makeMenuBar(JFrame frame)

177.     {

178.       final int SHORTCUT_MASK =

179.         Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

180.       JMenuBar menubar = new JMenuBar();

181.       frame.setJMenuBar(menubar);

182.       JMenu menu;

183.       JMenuItem item;

184.       // create the File menu

185.       menu = new JMenu("File");

186.       menubar.add(menu);

187.       item = new JMenuItem("Open");

188.         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));

189.         item.addActionListener(new ActionListener() {

190.                   public void actionPerformed(ActionEvent e) { openFile(); }

191.                 });

192.       menu.add(item);

193.       item = new JMenuItem("Close");

194.         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));

195.         item.addActionListener(new ActionListener() {

196.                   public void actionPerformed(ActionEvent e) { close(); }

197.                 });

198.       menu.add(item);

199.       menu.addSeparator();

200.       item = new JMenuItem("Quit");

201.         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));

202.         item.addActionListener(new ActionListener() {

203.                   public void actionPerformed(ActionEvent e) { quit(); }

204.                 });

205.       menu.add(item);

206.       // create the Filter menu

207.       menu = new JMenu("Filter");

208.       menubar.add(menu);

209.       item = new JMenuItem("Darker");

210.         item.addActionListener(new ActionListener() {

211.                   public void actionPerformed(ActionEvent e) { makeDarker(); }

212.                 });

213.       menu.add(item);

214.       item = new JMenuItem("Lighter");

215.         item.addActionListener(new ActionListener() {

216.                   public void actionPerformed(ActionEvent e) { makeLighter(); }

217.                 });

218.       menu.add(item);

219.       item = new JMenuItem("Threshold");

220.         item.addActionListener(new ActionListener() {

221.                   public void actionPerformed(ActionEvent e) { threshold(); }

222.                 });

223.       menu.add(item);

224.       // create the Help menu

225.       menu = new JMenu("Help");

226.       menubar.add(menu);

227.       item = new JMenuItem("About ImageViewer...");

228.         item.addActionListener(new ActionListener() {

229.                   public void actionPerformed(ActionEvent e) { showAbout(); }

230.                 });

231.       menu.add(item);

232.     }

233.   }

 

Lalu ada class OFImage yang berguna untuk mendefinisikan sebuah image dalam format Object First (OF), source code:

1.  /**

2.   * class untuk mendefinisikan image

3.   *

4.   * @author Aufi Fillah

5.   * @version 1.0

6.   */

7.   

8.  import java.awt.*;

9.  import java.awt.image.*;

10. import javax.swing.*;

11.  

12. public class OFImage extends BufferedImage

13. {

14.     /**

15.      * membuat OFImage yg dikopy dari BufferedImage

16.      */

17.     public OFImage(BufferedImage image)

18.     {

19.         super(image.getColorModel(), image.copyData(null), image.isAlphaPremultiplied(), null);

20.     }

21.    

22.     /**

23.      * membuat OFImage dengan ukuran sepsifik

24.      */

25.     public OFImage(int width, int height)

26.     {

27.         super(width, height, TYPE_INT_RGB);

28.     }

29.    

30.     /**

31.      * set pixel yg diberikan menjadi specified color

32.      */

33.     public void setPixel(int x, int y, Color col)

34.     {

35.         int pixel = col.getRGB();

36.         setRGB(x, y, pixel);

37.     }

38.    

39.     /**

40.      * get isi color pada sebuah posisi pixel secara spesifik

41.      */

42.     public Color getPixel(int x, int y)

43.     {

44.         int pixel = getRGB(x, y);

45.         return new Color(pixel);

46.     }

47.    

48.     /**

49.      * membuat image darker

50.      */

51.     public void darker()

52.     {

53.         int height = getHeight();

54.         int width = getWidth();

55.         for(int y=0; y<height; y++)

56.         {

57.             for(int x=0; x<width; x++)

58.             {

59.                 setPixel(x, y, getPixel(x, y).darker());

60.             }

61.         }

62.     }

63.    

64.     /**

65.      * membuat image lighter

66.      */

67.     public void lighter()

68.     {

69.         int height = getHeight();

70.         int width = getWidth();

71.         for(int y=0; y<height; y++)

72.         {

73.             for(int x=0; x<width; x++)

74.             {

75.                 setPixel(x, y, getPixel(x, y).brighter());

76.             }

77.         }

78.     }

79.    

80.     /**

81.      * threshold

82.      */

83.     public void threshold()

84.     {

85.         int height = getHeight();

86.         int width = getWidth();

87.         for(int y=0; y<height; y++)

88.         {

89.             for(int x=0; x<width; x++)

90.             {

91.                 Color pixel = getPixel(x, y);

92.                 int brightness = (pixel.getRed() + pixel.getBlue() + pixel.getGreen())/3;

93.                 if(brightness <= 85)

94.                 {

95.                     setPixel(x, y, Color.BLACK);

96.                 }

97.                 else if(brightness <= 170)

98.                 {

99.                     setPixel(x, y, Color.GRAY);

100.                 }

101.                 else

102.                 {

103.                     setPixel(x, y, Color.WHITE);

104.                 }

105.             }

106.         }

107.     }

108. }

 

Selain itu ada class ImageFileManager yang berguna untuk load dan save image, source code nya:

1.  /**  

2.    * Load dan save image

3.    *  

4.    * @author Aufi Fillah

5.    * @version 1.0

6.    */

7.   

8.   import java.awt.image.*;  

9.   import javax.imageio.*;  

10.  import javax.swing.*;  

11.  import java.io.*;  

12.  

13.  public class ImageFileManager  

14.  {  

15.    // A constant for the image format that this writer uses for writing.  

16.    // Available formats are "jpg" and "png".  

17.    private static final String IMAGE_FORMAT = "jpg";  

18.    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));  

19.    /**  

20.     * Open a file chooser and let the user select an image file in the file  

21.     * system. Then read an image file from disk and return it as an image. This method  

22.     * can read JPG and PNG file formats. In case of any problem (e.g the file does  

23.     * not exist, is in an undecodable format, or any other read error) this method  

24.     * returns null.  

25.     *  

26.     * @return    The image object or null is it was not a valid image file.  

27.     */  

28.    public static OFImage getImage()  

29.    {  

30.      int returnVal = fileChooser.showOpenDialog(null);  

31.      if(returnVal != JFileChooser.APPROVE_OPTION) {  

32.        return null; // cancelled  

33.      }  

34.      File selectedFile = fileChooser.getSelectedFile();  

35.      return loadImage(selectedFile);  

36.    }  

37.    /**  

38.     * Read an image file from disk and return it as a BufferedImage. This method  

39.     * can read JPG and PNG file formats. In case of any problem (e.g the file does  

40.     * not exist, is in an undecodable format, or any other read error) this method  

41.     * returns null.  

42.     *  

43.     * @param imageFile The image file to be loaded.  

44.     * @return      The image object or null is it was not a valid image file.  

45.     */  

46.    public static OFImage loadImage(File imageFile)  

47.    {  

48.      try {  

49.        BufferedImage image = ImageIO.read(imageFile);  

50.        if(image == null || (image.getWidth(null) < 0)) {  

51.          // we could not load the image - probably invalid file format  

52.          return null;  

53.        }  

54.        return new OFImage(image);  

55.      }  

56.      catch(IOException exc) {  

57.        return null;  

58.      }  

59.    }  

60.    /**  

61.     * Write an image file to disk. The file format is JPG. In case of any problem  

62.     * the method just silently returns.  

63.     *  

64.     * @param image The image to be saved.  

65.     * @param file  The file to save to.  

66.     */  

67.    public static void saveImage(OFImage image, File file)  

68.    {  

69.      try {  

70.        ImageIO.write(image, IMAGE_FORMAT, file);  

71.      }  

72.      catch(IOException exc) {  

73.        return;  

74.      }  

75.    }  

76.  }

 

Lalu yang terakhir class ImagePanel yang berfungsi untuk tempat untuk mendisplay OFImage, source code:

1.  /**

2.   * Sebuah Swing komponen untuk mendisplay OFImage

3.   *

4.   * @author Aufi Fillah

5.   * @version 1.0

6.   */

7.   

8.  import java.awt.*;

9.  import javax.swing.*;

10. import java.awt.image.*;

11.  

12. public class ImagePanel extends JComponent

13. {

14.     private int width, height;

15.     private OFImage panelImage;

16.    

17.     /**

18.      * Membuat sebuah ImagePanel kosong

19.      */

20.     public ImagePanel()

21.     {

22.         width = 360;

23.         height = 240;

24.         panelImage = null;

25.     }

26.    

27.     /**

28.      * set gambar yang harus ditampilkan panel

29.      */

30.     public void setImage(OFImage image)

31.     {

32.         if(image != null)

33.         {

34.             width = image.getWidth();

35.             height = image.getHeight();

36.             panelImage = image;

37.             repaint();

38.         }

39.     }

40.    

41.     /**

42.      * clear image pada panel

43.      */

44.     public void clearImage()

45.     {

46.         Graphics imageGraphics = panelImage.getGraphics();

47.         imageGraphics.setColor(Color.LIGHT_GRAY);

48.         imageGraphics.fillRect(0,0, width, height);

49.         repaint();

50.     }

51.    

52.     /**

53.      * method untuk menaruh komponen

54.      */

55.     public Dimension getPreferredSize()

56.     {

57.         return new Dimension(width, height);

58.     }

59.    

60.     /**

61.      * komponen perlu di redisplay

62.      */

63.     public void paintComponent(Graphics g)

64.     {

65.         Dimension size = getSize();

66.         g.clearRect(0, 0, size.width, size.height);

67.         if(panelImage != null)

68.         {

69.             g.drawImage(panelImage, 0, 0, null);

70.         }

71.     }

72. }

 

Untuk demonstrasinya, pertama klik kanan pada class ImageViewer dan klik new ImageViewer()


Buat nama object terserah, disini kita memakai nama imageVie1


Klik OK dan muncul halaman seperti ini:


Apabila kita ingin membuka sebuah gambar, klik file lalu open dan pilih gambar yang ingin ditampilkan:



Klik open dan akan jadi seperti ini:



Dalam tab filter, kita dapat mengedit foto menjadi lebih terang dengan klik “lighter”, lebih gelap dengan klik “darker” dan threshold dengan klik “threshold”.

·       Darker:



·       Lighter:


·       Threshold:

 

Dan apabila ingin keluar dari program klik file lalu quit.

Sekian adalah contoh sederhana penggunaan GUI untuk program ImageViewer.

Komentar

Postingan populer dari blog ini

Game Java Rapid Roll

ETS PBO (Bagian 1) - membuat Sistem ATM