su.fmi.photoshareclient.ui.PhotoViewDialog.java Source code

Java tutorial

Introduction

Here is the source code for su.fmi.photoshareclient.ui.PhotoViewDialog.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package su.fmi.photoshareclient.ui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.apache.commons.io.FilenameUtils;
import su.fmi.photoshareclient.helpers.Pagination;
import su.fmi.photoshareclient.helpers.images.ImageLabel;
import su.fmi.photoshareclient.remote.ImageHandler;

/**
 *
 * @author Merx3
 */
public class PhotoViewDialog extends javax.swing.JDialog {

    public PhotoViewDialog(java.awt.Frame parent, boolean modal, ImageLabel image) {
        this(parent, modal);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(0, 0, (int) (screenSize.width * 0.9), (int) (screenSize.height * 0.9));

        this.imageLabel = new ImageLabel(image.getImage(), image.getImageId(), image.getFileName());
        jPanel1.add(this.imageLabel);
        jPanel1.revalidate();
        jPanel1.repaint();
    }

    /**
     * Creates new form PhotoViewDialog
     */
    public PhotoViewDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        SaveImageButton = new javax.swing.JButton();
        DeleteImageButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("View Image");

        jPanel1.setLayout(new java.awt.GridLayout(1, 1));

        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        SaveImageButton.setText("Save as...");
        SaveImageButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SaveImageButtonMouseClicked(evt);
            }
        });
        jPanel2.add(SaveImageButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 100, -1));

        DeleteImageButton.setText("Delete");
        DeleteImageButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                DeleteImageButtonMouseClicked(evt);
            }
        });
        jPanel2.add(DeleteImageButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 0, 90, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void SaveImageButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveImageButtonMouseClicked
        JFileChooser fileChooser = new JFileChooser() {
            // A warning for overweiting existing files
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?", "Existing file",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                    case JOptionPane.YES_OPTION:
                        super.approveSelection();
                        return;
                    case JOptionPane.NO_OPTION:
                        return;
                    case JOptionPane.CLOSED_OPTION:
                        return;
                    case JOptionPane.CANCEL_OPTION:
                        cancelSelection();
                        return;
                    }
                }
                super.approveSelection();
            }
        };
        fileChooser.setDialogTitle("Save image as...");
        File rootVolume = File.listRoots()[0];
        fileChooser.setSelectedFile(new File(rootVolume.getAbsolutePath(), this.imageLabel.getFileName()));

        int userSelection = fileChooser.showSaveDialog(this);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            try {
                File fileToSave = fileChooser.getSelectedFile();
                BufferedImage bi = (BufferedImage) this.imageLabel.getImage();
                String ext = FilenameUtils.getExtension(fileToSave.getAbsolutePath());
                ImageIO.write(bi, ext, fileToSave);
            } catch (IOException ex) {
                Logger.getLogger(PhotoViewDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_SaveImageButtonMouseClicked

    private void DeleteImageButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DeleteImageButtonMouseClicked
        int result = JOptionPane.showConfirmDialog(this,
                "Are you sure you want to delete image " + this.imageLabel.getFileName() + "?", "Delete image",
                JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            ImageHandler.deleteImage(this.imageLabel.getFileName());
            Pagination.removeImage(this.imageLabel.getFileName());
            ((PhotoViewerGUI) this.getParent()).refreshPage();
            setVisible(false);
            dispose();
        }
    }//GEN-LAST:event_DeleteImageButtonMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PhotoViewDialog.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PhotoViewDialog.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PhotoViewDialog.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PhotoViewDialog.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PhotoViewDialog dialog = new PhotoViewDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DeleteImageButton;
    private javax.swing.JButton SaveImageButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables

    private ImageLabel imageLabel;
}