Sabtu, 16 Mei 2015

JAVA - How To Populate a LinkedList From MySQL DataBase In Java

JAVA - How To Get Data From MySQL Database To LinkedList In Java

                                                                                                           

java linkedlist with mysql database

In this java Collection Tutorial we will see How To retrieve data from MySQL database
using LinkedList In Java NetBeans .

maybe you need to see:
   - connect java to mysql.
   - using LinkedList.


*Java Courses : Java Complete Course

                            Java Swing Course

Project Source Code:

package javaapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

// create a users class
class Users{
    private int Id;
    private String Fname;
    private String Lname;
    private int Age;
    
    public Users(){}
    public Users(int id, String fname,String lname,int age){
        this.Id = id;
        this.Fname = fname;
        this.Lname = lname;
        this.Age = age;
    }
    
    public int getId(){
        return this.Id;
    }
    
    public String getFname(){
        return this.Fname;
    }
    
       public String getLname(){
        return this.Lname;
    }
       
     public int getAge(){
        return this.Age;
    }
     
     // create a tostring methode to diplay data
     public String ToString(){
         return this.Id+" "+this.Fname+" "+this.Lname+" "+this.Age;
     }
}


public class Work {
   
    // create a methode to get the connection
    public static Connection getConnection(){
        
        Connection con = null;
        
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test_db", "root", "");
        } catch (SQLException ex) {
            Logger.getLogger(Work.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return con;
    }
    
    public static void main(String[] args){

        // create the linkedlist

        LinkedList<String> list = new LinkedList<String>();
        
        Users u;
        
        Connection con = getConnection();
        
        Statement st = null;
        ResultSet rs = null;
        
        try{
            st = con.createStatement();
            rs = st.executeQuery("SELECT * FROM users");
            while(rs.next()){
                Integer id = rs.getInt("id");
                String fname = rs.getString("fname");
                String lname = rs.getString("lname");
                int age = rs.getInt("age");
                
                u = new Users(id, fname,lname,age);
                
                // set data in the linkedlist with our tostring methode
                
                list.add(u.ToString());
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        // display data from the LinkedList
        for(String s : list)
        System.out.println(s);
        
        // now your data are displayed from mysql database using LinkedList 
    }
}

///////////////OUTPUT:

1 Fuser_1 Luser_1 56
2 Fuser_2 Luser_2 26
4 ftest ltest 43
5 DBB BDD 14
6 hgjk sdfr 25
7 some thing 32
8 white black 42
9 AAA1 BBB1 32
10 WOR HOME 54
13 java csharp 66
14 ASP.NET JAVAEE 11
15 FN LN 40
Baca selengkapnya

JAVA - How To Populate a HashMap From MySQL DataBase In Java

JAVA - How To Get Data From MySQL Database To HashMap In Java


java hashmap mysql database

In this java Collection Tutorial we will see How To retrieve data from MySQL database
using HashMap In Java NetBeans .

maybe you need to see:
   - connect java to mysql.
   - using HashMap.





Project Source Code:

package javaapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

// create a users class
class Users{
    private int Id;
    private String Fname;
    private String Lname;
    private int Age;
    
    public Users(){}
    public Users(int id, String fname,String lname,int age){
        this.Id = id;
        this.Fname = fname;
        this.Lname = lname;
        this.Age = age;
    }
    
    public int getId(){
        return this.Id;
    }
    
    public String getFname(){
        return this.Fname;
    }
    
       public String getLname(){
        return this.Lname;
    }
       
     public int getAge(){
        return this.Age;
    }
     
     // create a tostring method to diplay data
     public String ToString(){
         return this.Id+" "+this.Fname+" "+this.Lname+" "+this.Age;
     }
}


public class Work {
   
    // create a method to get the connection
    public static Connection getConnection(){
        
        Connection con = null;
        
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test_db", "root", "");
        } catch (SQLException ex) {
            Logger.getLogger(Work.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return con;
    }
    
    public static void main(String[] args){

        // create the hashmap
        HashMap<Integer,Users> map = new HashMap<Integer,Users>();
        
        Statement st = null;
        ResultSet rs = null;
        Connection con = getConnection();
        Users u;
        
        try{
            st = con.createStatement();
            rs = st.executeQuery("SELECT * FROM users");
            while(rs.next()){
                Integer id = rs.getInt("id");
                String fname = rs.getString("fname");
                String lname = rs.getString("lname");
                int age = rs.getInt("age");
                
                u = new Users(id, fname,lname,age);
                
                // set data in the hashmap
                map.put(id, u);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        // display data from the hashmap
        for(Integer i : map.keySet()){
            Users us = map.get(i);
            System.out.println(us.getId()+" "+us.getFname()+" "+us.getLname()+" "+us.getAge());
        }
        
        // show data from hashmap using our ToString Method
        System.out.println("______With ToString______");
        for(Integer i : map.keySet()){
            Users us = map.get(i);
            System.out.println(us.ToString());
        }
        
        // now your data are displayed from mysql database using hashmap 
    }
}

///////////////OUTPUT:
1 Fuser_1 Luser_1 56
2 Fuser_2 Luser_2 26
4 ftest ltest 43
5 DBB BDD 14
6 hgjk sdfr 25
7 some thing 32
8 white black 42
9 AAA1 BBB1 32
10 WOR HOME 54
13 java csharp 66
14 ASP.NET JAVAEE 11
15 FN LN 40
______With ToString______
1 Fuser_1 Luser_1 56
2 Fuser_2 Luser_2 26
4 ftest ltest 43
5 DBB BDD 14
6 hgjk sdfr 25
7 some thing 32
8 white black 42
9 AAA1 BBB1 32
10 WOR HOME 54
13 java csharp 66
14 ASP.NET JAVAEE 11
15 FN LN 40

Baca selengkapnya

JAVA - How To Use HashMap With Class In Java NetBeans

JAVA Collection - Using HashMap With Class As Value In Java NetBeans

                                                                                                                                                            
using hasmap with your own class in java



In this java Collection Code we will see How To Use HashMap With Our Class As Value In Java NetBeans 



Source Code:

package javaapp;

import java.util.HashMap;

 // Creat a class
   class User{
       private int id;
       private String name;
       
       public User(){}
       
       public User(int _id,String _name){
          this.id = _id;
          this.name =_name;
       }
       
       public int getId(){
           return this.id;
       }
       
       public String getName(){
           return this.name;
       }
       
       public void setId(int id){
           this.id = id;
       }
       
       public void setName(String name){
           this.name = name;
       }
       
// create a tostring methode
       public String ToString(){
           return "ID = "+id+"  NAME = "+name ;
       }
   }

public class Woirk {

    
    public static void main(String[] args){

        HashMap<Integer,User> userList = new HashMap<Integer,User>();

// filling the HashMap with put method
        userList.put(10, new User(1,"omar"));
         userList.put(21, new User(2,"bilal"));
          userList.put(32, new User(3,"kamal"));
           userList.put(43, new User(4,"rachid"));
            userList.put(54, new User(5,"rami"));
             userList.put(65, new User(6,"karim"));
             
// create another hashmap
      HashMap<Integer,User> userList2 = new HashMap<Integer,User>();
        userList2.put(53, new User(62,"khalid"));
          userList2.put(25, new User(18,"mounir"));
          
// replace element in hashmap
        userList.replace(10, new User(100,"tarik"), new User(1,"omar"));

        // insert a map elements in another map
        userList.putAll(userList2);

        printAllData(userList);

        userList.remove(3);
        
        printAllData(userList);
          
        User u = userList.replace(10, new User(8,"morad"));
        
        printAllData(userList);
        
        userList.put(400,null);

/*
       If the specified key is not associated with a value
       or the value is null associates it with the given value                        in this example  the key is 400 and value is null
*/
        userList.putIfAbsent(400, new User(19,"TEXT"));
      
        printAllData(userList);
        
       User us = userList.getOrDefault(400,null);
       System.out.println(us.ToString());
     

      User u1 = userList.get(54);
      User u2 = new User(600, "TheNewUser");
  
    System.out.println("---------------------");
    printAllData(userList);
   userList.remove(54, u1);
       printAllData(userList);
   
    System.out.println("Size: "+userList.size());
    userList.clear();
    System.out.println("The userList is Empty: "+userList.isEmpty());
  }  
    
    // method to print hashmap data
    public static void printAllData(HashMap<Integer,User> list){
      for(Integer i : list.keySet())
        {
          System.out.println(list.get(i).ToString());
        }
      System.out.println("----------------------");
    }
    
 // method to print hashmap keys
    public static void printKeys(HashMap<Integer,User> list){
      for(Integer i : list.keySet())
        {
          System.out.println(i);
        }
      System.out.println("----------------------");
    } 
}

//OUTPUT:

ID = 3  NAME = kamal
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 5  NAME = rami
ID = 18  NAME = mounir
ID = 1  NAME = omar
ID = 4  NAME = rachid
----------------------
ID = 3  NAME = kamal
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 5  NAME = rami
ID = 18  NAME = mounir
ID = 1  NAME = omar
ID = 4  NAME = rachid
----------------------
ID = 3  NAME = kamal
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 5  NAME = rami
ID = 18  NAME = mounir
ID = 8  NAME = morad
ID = 4  NAME = rachid
----------------------
ID = 3  NAME = kamal
ID = 19  NAME = TEXT
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 5  NAME = rami
ID = 18  NAME = mounir
ID = 8  NAME = morad
ID = 4  NAME = rachid
----------------------
ID = 19  NAME = TEXT
---------------------
ID = 3  NAME = kamal
ID = 19  NAME = TEXT
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 5  NAME = rami
ID = 18  NAME = mounir
ID = 8  NAME = morad
ID = 4  NAME = rachid
----------------------
ID = 3  NAME = kamal
ID = 19  NAME = TEXT
ID = 6  NAME = karim
ID = 2  NAME = bilal
ID = 62  NAME = khalid
ID = 18  NAME = mounir
ID = 8  NAME = morad
ID = 4  NAME = rachid
----------------------
Size: 8
The userList is Empty: true

Baca selengkapnya

Jumat, 15 Mei 2015

JAVA - How To Use CardLayout In Java NetBeans

CardLayout Example In Java NetBeans

                                                                                                                                                            

In this java Code we will see How To Use The BorderLayout LayoutManager In Java NetBeans

Source Code:


import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Window {
       static JFrame frame = new JFrame();
       static JPanel PANEL = new JPanel(new BorderLayout());
       static JPanel panelButton = new JPanel();
       static JPanel panelText = new JPanel();
       static JPanel panelLabel = new JPanel();
       static JPanel panelRed = new JPanel();
       static JPanel panelGreen = new JPanel();
       static JPanel panelBlack = new JPanel();
       static JPanel panelWhite = new JPanel();
       static CardLayout card = new CardLayout();
       
    public static void main(String[] args){

        panelText.setName("panelText");
        panelLabel.setName("panelLabel");
        
        JButton buttonText = new JButton("TextField");
        JButton buttonLabel = new JButton("Label");
        JButton buttonFirst = new JButton("First");
        JButton buttonLast = new JButton("Last");
        JButton buttonNext = new JButton("Next");
        JButton buttonPrevious = new JButton("Previous");
        
        JTextField text1 = new JTextField(20);
        JTextField text2 = new JTextField(20);
        JTextField text3 = new JTextField(20);
        
        JLabel label1 = new JLabel("label1");
        JLabel label2 = new JLabel("label2");
        JLabel label3 = new JLabel("label3");
      
        panelButton.add(buttonText);
        panelButton.add(buttonLabel);
        panelButton.add(buttonFirst);
        panelButton.add(buttonLast);
        panelButton.add(buttonNext);
        panelButton.add(buttonPrevious);
        
        panelText.add(text1);
        panelText.add(text2);
        panelText.add(text3);
        
        panelLabel.add(label1);
        panelLabel.add(label2);
        panelLabel.add(label3);
        
        panelRed.setBackground(Color.red);
        panelGreen.setBackground(Color.green);
        panelBlack.setBackground(Color.black);
        panelWhite.setBackground(Color.white);
        
        
        // show the card who contain JTextFields
        buttonText.addActionListener(new ActionListener(){
         
            @Override
            public void actionPerformed(ActionEvent e){
                card.show(PANEL, "panelText");
            }
        });
        
        // show the card who contain JLabels
        buttonLabel.addActionListener(new ActionListener(){
         
            @Override
            public void actionPerformed(ActionEvent e){
                card.show(PANEL, "panelLabel");
            }
        });
        
         // show the first card
        buttonFirst.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
               card.first(PANEL);
            }
        });
        
        // show the last card
        buttonLast.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
             
                card.last(PANEL);
            }
        });
        
        // show the next card
        buttonNext.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            
                card.next(PANEL);
            }
        });
        
        // show the previous card
        buttonPrevious.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                card.previous(PANEL);
            }
        });

        // set a Hgap to the cardlayout
        card.setHgap(20);
        
        // set a Vgap to the cardlayout
        card.setVgap(20);
        
        PANEL.setLayout(card);
        PANEL.add(panelText,"panelText");
        PANEL.add(panelLabel,"panelLabel");
        PANEL.add(panelRed,"RED");
        PANEL.add(panelGreen,"GREEN");
        PANEL.add(panelBlack,"BLACK");
        PANEL.add(panelWhite,"WHITE");

        card.layoutContainer(PANEL);
        
        frame.getContentPane().add(panelButton,BorderLayout.NORTH);
        frame.getContentPane().add(PANEL,BorderLayout.CENTER);
        
        frame.setTitle("CardLayout");
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

//OUTPUT:


java cardlayout
using cardlayout in java

Baca selengkapnya

JAVA - How To Use BorderLayout In Java NetBeans

BorderLayout Example In Java NetBeans

                                                                                                                                                            

In this java Code we will see How To Use The BorderLayout LayoutManager In Java NetBeans

Source Code:

package javaapp;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingLayout {

    public static void main(String[] args){
        
      JFrame frame = new JFrame("BorderLayout");
      
      JPanel panel1 = new JPanel();
      
      panel1.setLayout(new BorderLayout());
      
      // set the button in the top of the container
      panel1.add(new JButton("NORTH"), BorderLayout.NORTH);
      
      // set the button in the right of the container
      panel1.add(new JButton("EAST"), BorderLayout.EAST);
      
      // set the button in the middle of the container
      panel1.add(new JButton("CENTER"), BorderLayout.CENTER);
      
      // set the button in the top of left container
      panel1.add(new JButton("WEST"), BorderLayout.WEST);
      
      // set the button in the bottom of the container
      panel1.add(new JButton("SOUTH"), BorderLayout.SOUTH);
     
      // create an instance of borderlayout with gaps
      BorderLayout bl = new BorderLayout(50,50);
      
      JPanel panel2 = new JPanel(bl);
      
      panel2.add(new JButton("NORTH"), BorderLayout.NORTH);
      panel2.add(new JButton("EAST"), BorderLayout.EAST);
      panel2.add(new JButton("CENTER"), BorderLayout.CENTER);
      panel2.add(new JButton("WEST"), BorderLayout.WEST);
      panel2.add(new JButton("SOUTH"), BorderLayout.SOUTH);
      
        bl.removeLayoutComponent(new JButton("NORTH"));
      
      // return the state of the borderlayout Hgap and Vgap
      System.out.println(bl.toString());
      
      // return the borderlayout Hgap and Vgap
      System.out.println(bl.getHgap()+" - "+bl.getVgap());     
      
      frame.add(panel2);     
       
      frame.setSize(400, 400);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      
    }
}


//OUTPUT:

borderlayout in java
using the panel1

java borderlayout
using the panel2

java.awt.BorderLayout[hgap=50,vgap=50]
50 - 50
Baca selengkapnya