Saturday, January 7, 2012

Java GUI(Graphical User Interface)

Hi guys...,
        This time I thought of explaining you guys about java GUI's and how to create them and how to connect to a database using a java code.
        All the tools for GUI's are in java.awt and javax.swing packages.So we should first import them to use any GUI component like JButtons ,JTextField,JLabel etc. Any GUI window should be a subclass at JFrame class.If you do not know about the JFrame class then follow this link http://docs.oracle.com/javase/6/docs/api/javax/swing/JFrame.html .A window can have any number of GUI components.The all written components should then add to a container. To do that there's a thing known as layout manager.If you new to layout manager follow this link http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
        But we can add our own layout managers also. In the JFrame class there's a method known as getContentPane(), it will create a object of container class and will return a reference of that object.Or we can create a object of a Container class as below,

Container pane =new Container();

 To that container we add a layout to manage our components .Its like how do we want our components to appear in a interface. To do that there's a method known as setLayout() in the Container class . We can either give a layout manager a specific layout or we can just say null.
            
 pane.setLayout(new GridLayout(());
 pane.setLayout(new GridLayout(null);

If we say null ,then we have to place each and every component on the interface manually giving x coordinates ,y coordinates ,width of the component and the height of  the component .For that there's a method called setBounds() in the JFrame class.And the components will appear according to the order we add to the pane. If we used a layout like GridLayout ,BoxLayout etc , then we don't have to give coordinates because they are already implemented in the layout. We just have to add them to the container in order we prefer . To add components there's a method called add() in the Container class.
Below is an example code creating a interface for a registration like in any social network.If you carefully look  into it you will see that i didn't use a layout manager to manage my components.


class RegUi extends JFrame{

 private JLabel lTopic;
private JLabel lTopic1;
private JLabel lbFName;
private JTextField txtFName;
private JLabel lbLName;
private JTextField txtLName;
private JLabel lEmail;
private JTextField txtEmail;
private JLabel lbUName;
private JTextField txtUName;
private JLabel lPWord;
private JPasswordField txtPWord;
private JButton bSignUp;
private JButton bProceed;
private Container pane;
String str1;
String str2;
String str3;
String str4;
String str5;
boolean ans=false;

RegUi(){

lTopic=new JLabel("Sign Up");
lTopic1=new JLabel("Press Proceed to login with 
                your new Username and Password");
lbFName=new JLabel("First Name:");
txtFName=new JTextField();
lbLName=new JLabel("Last Name:");
txtLName=new JTextField();
lEmail=new JLabel("Your Email:");
txtEmail=new JTextField();
lbUName=new JLabel("User Name:");
txtUName=new JTextField();
lPWord=new JLabel("New Password:");
txtPWord=new JPasswordField();
bSignUp=new JButton("Sign Up");
bProceed=new JButton("Proceed");

pane=getContentPane();
pane.setLayout(null);



lTopic.setBounds(50, 10, 100, 50);
pane.add(lTopic);
lTopic.setFont(new java.awt.Font("Times New 
                Roman", Font.BOLD, 20));
lbFName.setBounds(20, 50, 100, 50);
pane.add(lbFName);
txtFName.setBounds(120, 65, 200, 25);
pane.add(txtFName);
lbLName.setBounds(20, 120, 100, 50);
pane.add(lbLName);
txtLName.setBounds(120, 135, 200, 25);
pane.add(txtLName);
lEmail.setBounds(20, 190, 100, 50);
pane.add(lEmail);
txtEmail.setBounds(120, 205, 200, 25);
pane.add(txtEmail);
lbUName.setBounds(20, 260, 100, 50);
pane.add(lbUName);
txtUName.setBounds(120, 275, 200, 25);
pane.add(txtUName);
lPWord.setBounds(20, 330, 100, 50);
pane.add(lPWord);
txtPWord.setBounds(120, 345, 200, 25);
pane.add(txtPWord);
bSignUp.setBounds(260, 400, 100, 40);
pane.add(bSignUp);
lTopic1.setBounds(20, 450, 500, 50);
pane.add(lTopic1);
bProceed.setBounds(260, 510, 100, 40);
pane.add(bProceed);

RegHandler handler=new RegHandler();
bSignUp.addActionListener(handler);
bProceed.addActionListener(handler);

                setSize(500,600);
setTitle("Register");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}


we say setVisible true to make our interface visible.If you execute this code u will see buttons like SignUp ,Proceed .But when you click on them nothing happens. That because we did not add a mechanism for those. So to make changes we should add event listener's. So using those ,once those buttons were clicked we can tell it to display a message , connect to a database and do some manipulations etc. Following link will show you how to work with event listeners..

http://docs.oracle.com/javase/tutorial/uiswing/events/index.html

So now i'll show you how to connect with a mysql database when you click signup button in the above code. So what will happen is a user will enter their information in those sections such as First Name, Last Name etc then when he click signup button it will connect with the database and will include those in a table known as user .So he will be able to log in using his username and password. To connect with a database first we have to create the connection between JDBC Api -java database connectivity and the JVM -java virtual machine .

To connect JDBC Api with DBMS -Data base management system we use JDBC driver.There are four drivers. JDBC/ODBC driver ,open database connectivity ,JDBC native driver etc .In the process we only need few classes such as class Class ,class DriverManager ,class PrepareStatement ,class ResultSet . You can see code below.


class Jdbc{

public static Connection createConnection()throws ClassNotFoundException,SQLException {
Connection con=null; 

String url = "jdbc:mysql://localhost:3306/";
String dbName = "regDb";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName, userName, password);

return con;
}
}


We should run apache and mysql servers using Xampp.And we can use localhost for this.below is the code we can use for the connection


class Register{
Connection c1=null;
Statement stmt=null;
PreparedStatement pst = null;
boolean check=false;

public void createUser(String s1,String s2,String s3,String s4,String s5){

try{
 c1=Jdbc.createConnection();
     stmt = c1.createStatement();

     pst=c1.prepareStatement("INSERT INTO users (FirstName,LastName,Email,UserName,Password) VALUES(?,?,?,?,?)");
     pst.setString(1, s1);
     pst.setString(2, s2);
     pst.setString(3, s3);
     pst.setString(4, s4);
     pst.setString(5, s5);
     pst.executeUpdate();
}
catch(ClassNotFoundException e){
System.out.println("Class not found!");
}
catch (SQLException e) {
System.out.println(e.toString());
}
try {
c1.close();
stmt.close();
pst.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
}

public boolean checkUser(String s1) throws ClassNotFoundException, SQLException{
c1=Jdbc.createConnection();
stmt = c1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String x = rs.getString("UserName");
if(x.equals(s1)){
check=true;
}   
   }
return check;
}
}


Hope you guys got something from this ....:)


   

No comments:

Post a Comment