miércoles, 28 de mayo de 2014

Reproductor de Audio en Java

Reproductor de Audio basico en Java con opciones de Play, Pausa y Stop.
Primero descargar e instalar Java Media Framework API (JMF) del siguiente enlace. http://www.oracle.com/technetwork/java/javase/download-142937.html


import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.Time;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Delfi
 */
public class Reproductor extends javax.swing.JFrame {
   
    Player audioPlayer = null;
    String audioPath = " ";  
    /**
     * Creates new form Reproductor
     */
    public Reproductor() {
        initComponents();
        this.setLocationRelativeTo(null);
        jlabelEstado.setText(" ");
        dirArchivo.setText(" ");
    }  

    /**
     * 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")
    //                         
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnPlay = new javax.swing.JButton();
        btnPause = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        jlabelEstado = new javax.swing.JLabel();
        dirArchivo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuAbrir = new javax.swing.JMenuItem();
        jMenuSalir = new javax.swing.JMenuItem();
        jMenuAbout = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Reproductor de Audio - Java Tips - http://javacodebasics.blogspot.mx");
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/music.png")).getImage());
        setResizable(false);

        btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/play.png"))); // NOI18N
        btnPlay.setText("Play");
        btnPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayActionPerformed(evt);
            }
        });

        btnPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/pause.png"))); // NOI18N
        btnPause.setText("Pause");
        btnPause.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPauseActionPerformed(evt);
            }
        });

        btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/stop.png"))); // NOI18N
        btnStop.setText("Stop");
        btnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopActionPerformed(evt);
            }
        });

        jlabelEstado.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlabelEstado.setText("Reproductor");

        dirArchivo.setText(" ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jlabelEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(dirArchivo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPlay)
                    .addComponent(btnPause)
                    .addComponent(btnStop))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlabelEstado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dirArchivo)
                .addGap(3, 3, 3))
        );

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/archivo.png"))); // NOI18N
        jMenu1.setText("Archivo");

        jMenuAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/abrir.png"))); // NOI18N
        jMenuAbrir.setText("Abrir archivo de audio");
        jMenuAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuAbrirActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuAbrir);

        jMenuSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/salir.png"))); // NOI18N
        jMenuSalir.setText("Salir");
        jMenuSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuSalirActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuSalir);

        jMenuBar1.add(jMenu1);

        jMenuAbout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/about.png"))); // NOI18N
        jMenuAbout.setText("About");
        jMenuAbout.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuAboutMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenuAbout);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }//                       

    private void btnPauseActionPerformed(java.awt.event.ActionEvent evt) {                                        
        audioPlayer.stop();
        jlabelEstado.setText("Pausa");
    }                                      

    private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {                                      
        if(file.equals(""))
        {
            JOptionPane.showMessageDialog(null, "Cargue una Pista de Audio", "Error al Reproducir", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource("/imagenes/verificar.png")));
        }
        else
        {
            audioPlayer.start();
            jlabelEstado.setText("Reproduciendo");
        }
    }                                      

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {                                      
        audioPlayer.stop();
        audioPlayer.setMediaTime(new Time(0.0));
        jlabelEstado.setText("");
    }                                      

    String file="";
    public String abrirAudio()
    {    
        JFileChooser se = new JFileChooser();
       
        se.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Music"));
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos de Imagen", "mp3", "wav");
        se.setFileFilter(filtro);
        se.setFileSelectionMode(JFileChooser.FILES_ONLY);
       
        int estado = se.showOpenDialog(null);
        if(estado == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                String pathArchivo = se.getSelectedFile().getPath();
                URL url = se.getSelectedFile().toURL();  
                this.file= se.getSelectedFile().getName();
                audioPlayer = Manager.createRealizedPlayer( url );
                dirArchivo.setText(pathArchivo);
            } catch (MalformedURLException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoPlayerException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (CannotRealizeException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
        return "Java Tips - " + this.file;
    }
   
    private void jMenuAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                          
      this.setTitle(abrirAudio());
    }                                        

    private void jMenuSalirActionPerformed(java.awt.event.ActionEvent evt) {                                          
        this.dispose();
    }                                        

    private void jMenuAboutMouseClicked(java.awt.event.MouseEvent evt) {                                      
        About a = new About();
        a.setVisible(true);
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //
        /* 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(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Reproductor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                    
    private javax.swing.JButton btnPause;
    private javax.swing.JButton btnPlay;
    private javax.swing.JButton btnStop;
    private javax.swing.JLabel dirArchivo;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenuAbout;
    private javax.swing.JMenuItem jMenuAbrir;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuSalir;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel jlabelEstado;
    // End of variables declaration                  
}



Descargar Archivo Netbeans:

martes, 15 de abril de 2014

Customize JOptionPane Dialog

import javax.swing.*;

public class Test
{
    public static void main(String[] args)
    {
        final ImageIcon icon = new ImageIcon("C:\\Users\\Delfi\\Desktop\\ejemplo.jpg");
        JOptionPane.showMessageDialog(null, "Blah blah blah", "About", JOptionPane.INFORMATION_MESSAGE, icon);
    }
}
or
String mensaje = "Java Tips"

JOptionPane.showMessageDialog(null, mensaje, "http://javacodebasics.blogspot.com/", 
JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource("/Imagenes/dataOk.png")));

Add & remove ImageIcon to JLabel

Java adding ImageIcon to JLabel

ImageIcon image;
image = new ImageIcon(C:/Users/Delfi/Desktop/data4.png);
jlabel1.setIcon(image);

How to use getClass().getResource() method

ImageIcon image;
image = new ImageIcon(getClass().getResource("/Imagenes/data4.png"));
jlabel1.setIcon(image);

Remove an icon on a JLabel

jlabel1.setIcon(null) 
in the event handler that handles the button click, if you're using Swing.

lunes, 14 de abril de 2014

Page redirect after certain time - PHP

header( "refresh:5;url=displaydata.php" );
this is the php way to set header witch will redirect you to displaydata.php in 5 seconds

or

header('Refresh: 10; URL=http://javacodebasics.blogspot.com/');
Where 10 is in seconds.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

Using sleep and header
<?php
sleep(2);
header('Location: http://javacodebasics.blogspot.com');
?>

The argument to sleep is seconds, the argument to usleep is microseconds. Other than that, I think they're identical.

Using <meta> tag
<meta http-equiv="refresh" content="2;url = http://javacodebasics.blogspot.com/">

Labels alineadas y formateadas HTML + CSS

En ocasiones, es más útil mostrar todos los campos del formulario con su <label> alineada a la izquierda y el campo del formulario a la derecha de cada <label>, como muestra la siguiente imagen:

Mostrando las etiquetas label alineadas con los campos del formulario

Para mostrar un formulario tal y como aparece en la imagen anterior no es necesario crear una tabla y controlar la anchura de sus columnas para conseguir una alineación perfecta. Sin embargo, sí que es necesario añadir un nuevo elemento (por ejemplo un <div>) que encierre a cada uno de los campos del formulario (<label> y <input>).

El código HTML del formulario anterior se añaden los elementos <div>:

<form>
  <fieldset>
  <legend>Alta en el servicio</legend>

  <div>
    <label for="nombre">Nombre</label>
    <input type="text" id="nombre" />
  </div>

  <div>
    <label for="apellidos">Apellidos</label>
    <input type="text" id="apellidos" size="35" />
  </div>
  ...
</fieldset>
</form>

Y en el código CSS se añaden las reglas necesarias para alinear los campos del formulario:

div {
  margin: .4em 0;
}
div label {
  width: 25%;
  float: left;
}

get the text of the selected option in PHP - MySQL

Example

<select name="pais">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
</select>

< ?
$pais = strip_tags($_POST['pais']);
? >

HTML + CSS

Basic Example

<html>
<head>
  <title>Página con estilo</title>
  <style type="text/css">
  body {
    font-family: Georgia, "Times New Roman",
          Times, serif;
    color: purple;
    background-color: #d8da3d }
  h1 {
    font-family: Helvetica, Geneva, Arial,
          SunSans-Regular, sans-serif }
  </style>
</head>

<body>
[etc.]

or

<html>
<head>
    <title>Example form</title>
    <style type="text/css">
    .container {
        width: 500px;
        clear: both;
    }
    .container input {
        width: 100%;
        clear: both;
    }

    </style>
</head>
<body>
<div class="container">
<form>
 <label>First Name</label>
 <input type="text" name="first"><br />
 <label>Last Name</label>
 <input type="text" name="last"><br />
 <label>Email</label>
 <input type="text" name="email"><br />
</form>
</div>
</body>
</html>


Reset MySQL Autoincrement Column

Directly Reset Autoincrement Value
Alter table syntax provides a way to reset autoincrement column. Take a look at following example.

ALTER TABLE `table_name` AUTO_INCREMENT=1

Example

ALTER TABLE `id_estudiantes` AUTO_INCREMENT=1

Entradas populares