WHAT'S NEW?
Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts
Consider the following
Database Name: demodb
Table: Student (id int Primary Key, name varchar(100),percentage float)



Now let us consider a scenario where we need to load the names of Student in a Combo Box.

Basically i will write method by name loadName() which would like this.

public ArrayList<String> loadName()
{
ArrayList<String> list=new ArrayList<String>();
//Create a ArrayList to hold the list of names.
try
{
//Load the names from database table using JDBC.
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/demodb";
String user="root";
String password="your-db-password";
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
String query="Select name from student;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
list.add(rs.getString(1));
}
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// Return the list .
return list;
}


Now we have to integrate the above discussed method in a Swing form.

Now let us assume that combo is the object of JComboBox and this is how we will add the data in it.

             combo=new JComboBox();
     for(String name: loadName())
{
combo.addItem(name);
}
      combo.setBounds(100,100,200,30);
      c.add(combo);



So here is the full code for loading data in JComboBox.


LoadDataInCombo .java

iimport javax.swing.*;
import java.util.*;
import java.sql.*;
import java.awt.*;



public class LoadDataInCombo extends JFrame
{
JComboBox combo;
JLabel label;

LoadDataInCombo()
{
super("Load Data In Combo");
setSize(500,500);
  setResizable(false);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
       setLayout(null);
Container c=getContentPane();
c.setBackground(Color.WHITE);

combo=new JComboBox();
for(String name: loadName())
{
combo.addItem(name);
}
combo.setBounds(100,100,200,30);
c.add(combo);

setVisible(true);

}

public ArrayList<String> loadName()
{
ArrayList<String> list=new ArrayList<String>();
//Create a ArrayList to hold the list of names.
try
{
//Load the names from database table using JDBC.
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/demodb";
String user="root";
String password="your-db-password";
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
String query="Select name from student;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
list.add(rs.getString(1));
}
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// Return the list .
return list;
}

public static void main(String[] args)
{
LoadDataInCombo app=new LoadDataInCombo();
}


}

---------------------------------------Output would look like--------------------------------------------









Program discussed below have 4 JButton's arranged in following manner.


When the buttons Red,Green and Blue are clicked it changes the color of Display button.



DisplayColor.java


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class DisplayColor extends JFrame implements ActionListener 
{
   JButton jbtnDisplay,jbtnRed,jbtnGreen,jbtnBlue;
   Color cR=Color.RED;
   Color cG=Color.GREEN;
   Color cB=Color.BLUE;

   DisplayColor()
{
       super ("DISPLAY COLOR");
  setSize(1000,500);
  setResizable(false);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
       setLayout(null);
  Container c=getContentPane();

  jbtnDisplay=new JButton("");
  jbtnDisplay.setBounds(200,100,500,200);
  jbtnDisplay.setBackground(Color.BLACK);
  jbtnDisplay.addActionListener (this);
  c.add (jbtnDisplay);


       jbtnRed=new JButton("RED");
  jbtnRed.setBounds(50+100,350,100,50);
  jbtnRed.addActionListener (this);
  c.add (jbtnRed);
 
  jbtnGreen=new JButton("GREEN");
  jbtnGreen.setBounds(250+100,350,100,50);
  jbtnGreen.addActionListener (this);
  c.add (jbtnGreen);
   
        jbtnBlue=new JButton("BLUE");
   jbtnBlue.setBounds(450+100,350,100,50);
  jbtnBlue.addActionListener (this);
  c.add (jbtnBlue);
          
 setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
        if (ae.getSource()==(jbtnRed))
        {
jbtnDisplay.setBackground(Color.RED);
        }
if (ae.getSource()==(jbtnGreen))
        {
jbtnDisplay.setBackground(Color.GREEN);
        }
if (ae.getSource()==(jbtnBlue))
        {
jbtnDisplay.setBackground(Color.BLUE);
        }

}

  public static void main (String [] args)
{
  DisplayColor app=new DisplayColor();
  }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

class JComboBoxDemo extends JFrame
{
JComboBox jcb;
JButton jbtn;
JComboBoxDemo()
{
super("Java with Z");
setSize(500,500);
setDefaultCloseOperation(2);
setLocationRelativeTo(null);
Container c=getContentPane();
c.setLayout(null);

Vector v=new Vector();
v.add("Tom");
v.add("Alex");
v.add("Mike");
v.add("John");

jcb=new JComboBox(v);
jcb.setBounds(100,100,200,30);
c.add(jcb);

jbtn=new JButton("Find Tom");
jbtn.setBounds(100,300,100,30);
jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent ae)
{
int size=jcb.getItemCount();
for (int i=0;i<size ;i++)
{
String s=jcb.getItemAt(i).toString();
if (s.equalsIgnoreCase("tom"))
{
JOptionPane.showMessageDialog(null,"Found");
}
}

}
});
c.add(jbtn);



setVisible(true);
}
public static void main(String args[] )
{
JComboBoxDemo app=new JComboBoxDemo();
}
}

Inner Classes are those classes which are defined inside other class.

In simple word, the same manner in which a class contains a variable or method, a class can contain another class in it and these classes are known as INNER CLASSES.

Let see a simple example to understand Inner class.


InnerClassDemo.java

public class OuterClass
{
int i=;
public void m1()
{
System.out.println("I m in method m1");
}

class InnerClass
{
public void m2()
{
System.out.println("I m in method m2");
}
}
}

Code in red is the code of inner class and it is inside the boundary of the outer class(marked in blue);


Inner class can use all the variables and methods of outer class, even if they are private.

Inner class can use Outer Class data and vice versa.

Inner class is considered of nature useless because it is tightly bond to outer class and no other class can use it.

Inner Classes are used when  a class require to implement same interface more than once.

Let us see a Swing application to demonstrate the use of INNER Class.

OnOffDemo.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class OnOffDemo extends JFrame
{
JButton jbtnOn,jbtnOff;
JTextField jtfStatus;
OnOffDemo()
{
super("Zartab Nakhwa");
setSize(500,500);
setDefaultCloseOperation(2);
setLocationRelativeTo(null);
Container c=getContentPane();
c.setLayout(null);

jtfStatus=new JTextField("");
jtfStatus.setBounds(100,50,300,100);
c.add(jtfStatus);

jbtnOn=new JButton("On");
jbtnOn.setBounds(100,250,150,30);
jbtnOn.addActionListener(new OnHandler());
c.add(jbtnOn);

jbtnOff=new JButton("Off");
jbtnOff.setBounds(300-30,250,150,30);
jbtnOff.addActionListener(new OffHandler());
c.add(jbtnOff);




setVisible(true);
}
public static void main(String args[] )
{
OnOffDemo app=new OnOffDemo();
}

class OnHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
jtfStatus.setText("ON");
}
}

class OffHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
jtfStatus.setText("OFF");
}
}


}

Here the piece of code marked in Purple and Green are two inner classes.

You might not require to instantiate an object of inner class, but still in case if you require,let have a close look at it.



class Demo 
{
public static void main(String[] args) 
{
OuterClass outer=new OuterClass();
OuterClass.InnerClass inner=outer.new InnerClass()
}
}