Con la tecnología de Blogger.

lunes, enero 18, 2016

Tag: , , ,

GALERÍA O VISOR DE IMÁGENES EN JAVA NETBEANS

El programa es básicamente un visor de imágenes como el que viene por defecto en Microsoft Windows 7, aún esta es desarrollo así que aquí les presento un avance, espero que les sirva.

/*
 * 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 galeria;

import com.sun.glass.events.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author WillVP(WM)
 */
public class ventana extends javax.swing.JFrame implements MouseListener {

    File archivo[] = null;
    String urls[] = null;
    String extensiones[] = {"jpg", "png", "jpeg", "gif"};
    JLabel lblControl[] = new JLabel[3];
    int ancho = 0, alto = 0;
    boolean estado = false;
    int i = 0, x = 0, y = 0;
    ImageIcon icons[] = new ImageIcon[8];
    JFileChooser jfc;
    int seleccion;

    public ventana() {
        initComponents();
        this.setTitle("WillVP(WM) - Pictures v1.0");
        this.setLocationRelativeTo(null);
        CargarBtn();
        EstadosBtn(false);
        repaint();
//        AbrirImagen();
        this.lblControl[0].addMouseListener(this);
        this.lblControl[1].addMouseListener(this);
        this.lblControl[2].addMouseListener(this);
    }

    void CargarBtn() {
        ancho = pnFoto.getWidth();
        alto = pnFoto.getHeight();
        for (int j = 0; j < icons.length; j++) {
            icons[j] = new ImageIcon(getClass().getResource("/Iconos/" + j + ".png"));
        }
        for (int j = 0; j < lblControl.length; j++) {
            lblControl[j] = new JLabel();
            lblControl[j].setIcon(icons[j]);
            lblControl[j].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        }
        PosicionBtn();
    }

    void PosicionBtn() {
        y = this.getHeight() - 62;
        x = (this.getWidth() / 2);
        lblControl[0].setBounds((x - 50), (y - 47), 35, 25);
        lblControl[1].setBounds((x - 18), (y - 60), 50, 50);
        lblControl[2].setBounds((x + 30), (y - 47), 35, 25);
        pnFoto.add(this.lblControl[0]);
        pnFoto.add(this.lblControl[1]);
        pnFoto.add(this.lblControl[2]);
    }

    void EstadosBtn(boolean valor) {
        for (int j = 0; j < lblControl.length; j++) {
            lblControl[j].setVisible(valor);
        }
    }

    void AbrirCarpeta() {
        jfc = new JFileChooser("C:\\Users\\WILMER\\Pictures\\");
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        seleccion = jfc.showOpenDialog(null);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            String ruta = jfc.getSelectedFile().getPath();
            File carpeta = new File(jfc.getSelectedFile().getPath());
            String listUrl[] = carpeta.list();
            urls = new String[listUrl.length];
            for (int j = 0; j < listUrl.length; j++) {
                urls[j] = ruta + "\\" + listUrl[j];
            }
            pnFoto.setIcon(new ImageIcon(urls[i]));
            repaint();
            this.setTitle(urls[i]);
            EstadosBtn(true);
        }
    }

    void AbrirSeleccion() {
        i = 0;
        jfc = new JFileChooser("C:\\Users\\WILMER\\Pictures\\Camera Roll");
        jfc.setMultiSelectionEnabled(true);
        jfc.setFileFilter(new FileNameExtensionFilter("Archivos .jpg .png .jpeg", extensiones));
        seleccion = jfc.showOpenDialog(jfc);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            archivo = jfc.getSelectedFiles();
            urls = new String[archivo.length];
            for (int j = 0; j < urls.length; j++) {
                urls[j] = archivo[j].getPath();
            }
            pnFoto.setIcon(new ImageIcon(urls[i]));
            repaint();
            this.setTitle(urls[i]);
            EstadosBtn(true);
        }
    }

    void AbrirImagen(){
        urls = new String[1];
        jfc = new JFileChooser("C:\\Users\\WILMER\\Pictures\\Camera Roll");
        jfc.setFileFilter(new FileNameExtensionFilter("Archivos .jpg .png .jpeg .gif", extensiones));
        seleccion = jfc.showOpenDialog(jfc);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            urls[i] = jfc.getSelectedFile().getPath();
            pnFoto.setIcon(new ImageIcon(urls[i]));
            repaint();
            this.setTitle(urls[i]);
            EstadosBtn(true);
        }
    }
    /**
     * 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() {

        pnFoto = new jcMousePanel.jcMousePanel();
        lblDir = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        miCarpeta = new javax.swing.JMenuItem();
        miSeleccion = new javax.swing.JMenuItem();
        miImagen = new javax.swing.JMenuItem();
        miSalir = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        pnFoto.setBackground(new java.awt.Color(0, 0, 0));
        pnFoto.setColor1(new java.awt.Color(0, 0, 0));
        pnFoto.setColor2(new java.awt.Color(51, 51, 51));
        pnFoto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Fondo.png"))); // NOI18N
        pnFoto.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                pnFotoComponentResized(evt);
            }
        });

        lblDir.setFont(new java.awt.Font("Britannic Bold", 2, 12)); // NOI18N
        lblDir.setForeground(new java.awt.Color(255, 255, 255));
        lblDir.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout pnFotoLayout = new javax.swing.GroupLayout(pnFoto);
        pnFoto.setLayout(pnFotoLayout);
        pnFotoLayout.setHorizontalGroup(
            pnFotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnFotoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblDir, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnFotoLayout.setVerticalGroup(
            pnFotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnFotoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblDir, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(323, Short.MAX_VALUE))
        );

        jMenu1.setText("Archivo");

        miCarpeta.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        miCarpeta.setText("Abrir Carpeta");
        miCarpeta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miCarpetaActionPerformed(evt);
            }
        });
        jMenu1.add(miCarpeta);

        miSeleccion.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        miSeleccion.setText("Abrir Selección");
        miSeleccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSeleccionActionPerformed(evt);
            }
        });
        jMenu1.add(miSeleccion);

        miImagen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        miImagen.setText("Abrir Imágen");
        miImagen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miImagenActionPerformed(evt);
            }
        });
        jMenu1.add(miImagen);

        miSalir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        miSalir.setText("Salir");
        miSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSalirActionPerformed(evt);
            }
        });
        jMenu1.add(miSalir);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ayuda");

        jMenuItem1.setText("Acerca De...");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnFoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnFoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

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

    private void miCarpetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miCarpetaActionPerformed
        // TODO add your handling code here:
        AbrirCarpeta();

    }//GEN-LAST:event_miCarpetaActionPerformed

    private void miImagenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miImagenActionPerformed
        // TODO add your handling code here:        
        AbrirImagen();
    }//GEN-LAST:event_miImagenActionPerformed

    private void miSeleccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSeleccionActionPerformed
        // TODO add your handling code here:    
        AbrirSeleccion();
    }//GEN-LAST:event_miSeleccionActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
            if (i > 0) {
                i--;
                pnFoto.setIcon(new ImageIcon(urls[i]));
                repaint();
                this.setTitle(urls[i]);
            } else {
                i = 0;
            }
        } else if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
            if (i < urls.length - 1) {
                i++;
                pnFoto.setIcon(new ImageIcon(urls[i]));
                repaint();
                this.setTitle(urls[i]);
            } else {
                i = urls.length - 1;
            }
        }
        if (evt.getKeyCode() == KeyEvent.VK_END) {
            i = urls.length - 1;
            pnFoto.setIcon(new ImageIcon(urls[i]));
            repaint();
            this.setTitle(urls[i]);
        }
        if (evt.getKeyCode() == KeyEvent.VK_HOME) {
            i = 0;
            pnFoto.setIcon(new ImageIcon(urls[i]));
            repaint();
            this.setTitle(urls[i]);
        }
        if (evt.getKeyCode() == KeyEvent.VK_UP) {
            ancho = ancho + 5;
            alto = alto + 5;

        }
    }//GEN-LAST:event_formKeyPressed

    private void miSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSalirActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_miSalirActionPerformed

    private void pnFotoComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pnFotoComponentResized
        // TODO add your handling code here:
        PosicionBtn();
    }//GEN-LAST:event_pnFotoComponentResized

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        Ayuda a = new Ayuda(this, true);
        a.show();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    /**
     * @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(ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ventana().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JLabel lblDir;
    private javax.swing.JMenuItem miCarpeta;
    private javax.swing.JMenuItem miImagen;
    private javax.swing.JMenuItem miSalir;
    private javax.swing.JMenuItem miSeleccion;
    private jcMousePanel.jcMousePanel pnFoto;
    // End of variables declaration//GEN-END:variables

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == lblControl[1]) {
            if (lblControl[1].getIcon().equals(icons[4])) {
                this.setExtendedState(JFrame.MAXIMIZED_BOTH);
                lblControl[1].setIcon(icons[6]);
                estado = true;
            } else {
                this.setExtendedState(JFrame.NORMAL);
                lblControl[1].setIcon(icons[1]);
                estado = false;
            }
        }
        if (e.getSource() == lblControl[0]) {
            if (i > 0) {
                i--;
                pnFoto.setIcon(new ImageIcon(urls[i]));
                repaint();
//                lblDir.setText(urls[i]);
                this.setTitle(urls[i]);
            } else {
                i = 0;
            }
        }
        if (e.getSource() == lblControl[2]) {
            if (i < urls.length - 1) {
                i++;
                pnFoto.setIcon(new ImageIcon(urls[i]));
                repaint();
//                lblDir.setText(urls[i]);
                this.setTitle(urls[i]);
            } else {
                i = urls.length - 1;
            }
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
//        if(e.getSource() == pnFoto){
//            EstadosBtn(true);
//        }
        for (int j = 0; j < 3; j++) {
            if (e.getSource() == lblControl[j]) {
                lblControl[j].setIcon(icons[j + 3]);
                if (estado) {
                    lblControl[1].setIcon(icons[6]);
                }
            }
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {
//        if(e.getSource() == pnFoto){
//            EstadosBtn(false);
//        }
        for (int j = 0; j < 3; j++) {
            if (e.getSource() == lblControl[j]) {
                lblControl[j].setIcon(icons[j]);
                if (estado) {
                    lblControl[1].setIcon(icons[6]);
                }
            }
        }
    }
}

Paso 1:
Paso 2:

Paso 3:


Para descargar el cógigo completo:

Unknown

Mi Nombre el Will Villanueva Ponce, y estoy realizando blogs con los contenidos o archivos extras que realize durante mis estudios, con el fin de apoyar a aquellos que los necesiten...

1 comentarios:

  1. Muy buenos dias esta muy buena la galeria
    pero sera que me puedes ayudar con una teniendo una base de datos no logro hacer que pase hacia adelante y hacia atras.

    ResponderEliminar

 

Ads