2013-08-31

Java Display Google Maps

This time i want share tips simplest maps showing in java swing,To display of maps in swing this we can use ireport that provides a facility map,Netbeans as Editor and Mysql as a data storage. view video tutorials on youtube

Start it,Here is the steps..

1. to do is make table at mysql to store Id,Location_Name,Latitude and Longitude.

- Login to Mysql Database

- Create new database or Entered one database in mysql (in this example i use the database 'test')
         USE test;

- Create new Table and named 'locations'
        CREATE TABLE `locations` (
        `Id` int(11) NOT NULL AUTO_INCREMENT,
        `Location_Name` varchar(200) DEFAULT NULL,
       `Latitude` float(10,5) NOT NULL,
   `Longitude` float(10,5) NOT NULL,
        PRIMARY KEY (`Id`));

- Insert row data into table 'locations'
        INSERT INTO locations VALUES
(null,'Cirebon city square','-6.70949','108.55924'),
(null,'The heritage of "Sunan Gunungjati" Cirebon','-6.67388','108.54136'),
(null,'The great mosque "Sang Cipta Rasa" Cirebon','-6.72552','108.56992');




2. Connect ireport with a database mysql and designing map with ireport






3. Create a new project MapsOnSwing on netbeans ide , in this example I'm using netbeans 7.3.
- Add the required libraries to the project lib:
  mysql-connector-java-5.1.25-bin.jar or another version
  jasperreports-4.5.0.jar or another version , adapt with the version of ireport
  groovy-all-1.5.5.jar
  commons-logging-1.1.jar
  commons-digester-1.7.jar
  commons-collections-3.2.1.jar
  commons-beanutils-1.8.2.jar




4. After the project is created, then the package will be formed mapsonswing , in this package there is already a class MapsOnSwing.java


public class MapsOnSwing {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
}
}



5.  In mapsonswing package create new class MainFrame extend to JFrame,MainFrame design like the picture below :

Add desktoppane, combobox to zoom location,ComboBox Id_Location and Button to show Map

Add item to ComboBox Zoom : 15 , 16 , 17 , 18
Add item to ComboBox Id_Location : 1 , 2 , 3 or it could also take id_location from table location
Add Button to show Map



6.  Edit mapsonswing.java like this

public class MapsOnSwing {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
int w = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int h = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
MainFrame mainFrame = new MainFrame();
mainFrame.setSize(w, h);
mainFrame.setVisible(true);
}
});
}
}



7. In mapsonswing package create new Class IFrame extends JInternalFrame, add two parameter in constructor IFrame (int zoom,int id).

package mapsonswing;
import com.mysql.jdbc.Connection;
import java.awt.BorderLayout;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.swing.JRViewer;
/**
*
* @author User
*/
public class IFrame extends javax.swing.JInternalFrame {
/**
* Creates new form IFrame
*/
public IFrame(int zoom,int id) {
initComponents();
try{
String user = "root";
String pass = "";
Class.forName("com.mysql.jdbc.Driver");
Connection con = con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test",user,pass);
HashMap hm = new HashMap();
hm.put("zoom", zoom);
hm.put("id", id);
InputStream is=(InputStream) this.getClass().getClassLoader().getResourceAsStream("mapsonswing/Maps.jrxml");
JasperDesign design = JRXmlLoader.load(is);
JasperReport jcm = JasperCompileManager.compileReport(design);
JasperPrint jp = JasperFillManager.fillReport(jcm, hm,con);
JRViewer jr = new JRViewer(jp);
this.setLayout(new BorderLayout());
this.add(jr);
this.revalidate();
is.close();
con.close();
}catch(ClassNotFoundException ce){
System.out.println(ce);
}catch(SQLException se){
System.out.println(se);
}catch(IOException e){
System.out.println(e);
} catch (JRException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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">
private void initComponents() {
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Maps On Swing");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 750, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}



8. Make command buttons, when in clicks will feature internalframe that contains map

private void showButtonActionPerformed(java.awt.event.ActionEvent evt) {
int zoom;
if(cbzoom.getSelectedIndex()==0){
zoom = 15;
}else{
zoom = Integer.parseInt(cbzoom.getSelectedItem().toString().trim());
}
int id;
if(cbid.getSelectedIndex()==0){
id = 1;
}else{
id = Integer.parseInt(cbid.getSelectedItem().toString().trim());
}
dpane.removeAll();
IFrame iframe = new IFrame(zoom,id);
iframe.setSize(dpane.getWidth(), dpane.getHeight());
dpane.add(iframe);
iframe.setVisible(true);
}

9.Build and run project , the result will be like this


finished , see the video on youtube

2013-08-16

Java Restore Mysql Database

This time I want to share how to restore a mysql database from a backup file using java.
About how backups mysql database you can see here
Swing components needed are a JFrame, JPanel,JTextfield and JButton
We also need a JFilechooser to seek the path of a file that will be on make a URL,Class Process to call mysql And one more components JOptionpane as a sign that the process of restore a database mysql has been completed

The process is we search for a location file backups by using JFileChooser that will produce the path a file and will be used as a Url, then the Url will be set to JTextField.
then call restoreMysql() method that will run Class Process with parameter mysql path and file bacukup
This is an example code..

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


public class RestoreMysql extends JFrame{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    JPanel pnl;
    JTextField tf;
    JButton bopen;
    JButton brestore;
   
    public RestoreMysql(){
       
        pnl = new JPanel();
        pnl.setLayout(new FlowLayout());
        this.getContentPane().add(pnl);
       
        tf = new JTextField(null,25);
        pnl.add(tf);
       
        bopen = new JButton("Open");
        pnl.add(bopen);
        bopen.addActionListener(new ActionListener(){

            @SuppressWarnings("deprecation")
            @Override
            public void actionPerformed(ActionEvent ae) {
                JFileChooser jfc = new JFileChooser();
                int i = jfc.showOpenDialog(pnl);
                if(i==JFileChooser.APPROVE_OPTION){
                    URL url;
                    try {
                        url = jfc.getSelectedFile().toURL();
                        String file = url.toString().replaceAll("file:/", "").trim();
                        tf.setText(file);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                   
                }
               
            }
           
        });
       
        brestore = new JButton("Restore");
        pnl.add(brestore);
        brestore.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                restoreMysql(tf.getText());
            }
           
        });
       
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(500, 150);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
   
    private void restoreMysql(String file) {
        String user = "root";
        String pass = "";
       
        try{
            String[] executeCmd = new String[]{"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysql","-hlocalhost","-port3306", "--user=" + user, "--password=" + pass, "-e", "source "+file};
            Process p = Runtime.getRuntime().exec(executeCmd);
           
            int in = p.waitFor();
            JOptionPane.showMessageDialog(this, "Restore finis..");
        } catch (InterruptedException ex) {
            System.out.println(ex);
            JOptionPane.showMessageDialog(this, ex);
        }catch(IOException e){
            System.out.println(e);
            JOptionPane.showMessageDialog(this,e);
        }
    }
   
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new RestoreMysql();
            }
        });
    }

}

hopefully helpful...