import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
class Demo extends JFrame{
JTree jt;
Demo(){
DefaultMutableTreeNode a=new DefaultMutableTreeNode("A");
DefaultMutableTreeNode b=new DefaultMutableTreeNode("B");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("C");
DefaultMutableTreeNode d=new DefaultMutableTreeNode("D");
Container c1=getContentPane();
c1.setLayout(new FlowLayout());
setSize(500,500);
a.add(c);
a.add(b);
b.add(d);
jt =new JTree(a);
c1.add(jt);
}
}
public class Tree {
public static void main(String arg[]){
Demo d=new Demo();
d.setVisible(true);
}
}
A blog provide anexample with sample code for swing , servlet, jdbc and odbc connection to database, jsp, servlets, taglib, sql server, cassandra and many more. we also provide Apache camel sample code for integration.
Wednesday, November 7, 2012
Jtree
Create Login form using swing
import java.awt.Container;
import java.awt.FlowLayout;
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.JTextField;
public class Login extends JFrame implements ActionListener{
JButton jb1;
JLabel jl1,jl2,jl3;
JTextField jt1,jt2;
public Login(){
setSize(500,500);
jb1=new JButton("LogIn");
jl1=new JLabel("");
jl2=new JLabel("\n User Name\n");
jl3=new JLabel("\n Password\n");
jt1=new JTextField(10);
jt2=new JTextField(10);
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.add(jl1);
c.add(jl2);
c.add(jt1);
c.add(jl3);
c.add(jt2);
c.add(jb1);
jb1.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(jt1.getText().equals("uttam") && jt2.getText().equals("123")){
jl1.setText("LogIN successfuly");
jt2.setText("");
jb1.setText("LogOut");
}
else if(jb1.getText().equals("LogOut")){
jl1.setText("LogOut successfuly");
jb1.setText("LogIn");
}
}
public static void main(String[] args) {
// TODO code application logic here
Login l=new Login();
l.setVisible(true);
}
}
Monday, November 5, 2012
Calculator useing jsp
Cal.jsp
<%--
Document : Cal
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calculator</title>
</head>
<body>
<form metod="get" action="Cal1.jsp">
Value1:<input type="text" name="v1"/><br/>
Value2:<input type="text" name="v2"/><br/>
Opration:<select name="op">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select><br/>
<input type="submit" name="b" value="ok"/>
</form>
</body>
</html>
Cal1.jsp
<%--
Document : Cal1
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%! int ans; %>
<% int s=Integer.parseInt(request.getParameter("v1"));
int r=Integer.parseInt(request.getParameter("v2"));
String op1=request.getParameter("op");
if(op1.equals("+")){
ans=s+r;
}
if(op1.equals("-")){
ans=s-r;
}
if(op1.equals("*")){
ans=s*r;
}
if(op1.equals("/")){
ans=s/r;
}%>
<h1> answer is : <%=ans%> </h1>
</body>
</html>
How to create Jmenu
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
class Demo extends JFrame /*implements ActionListener*/
{
JMenu jm1,jm2;
JMenuBar jb;
JMenuItem jl1,jl2,jl3,jl4,jl5,jl6;
Demo()
{
jb= new JMenuBar();
jm1=new JMenu("Home");
jm2=new JMenu("Product");
jl1=new JMenuItem("File1");
jl2=new JMenuItem("File2");
jl3=new JMenuItem("File3");
jl4=new JMenuItem("Product1");
jl5=new JMenuItem("Product2");
jl6=new JMenuItem("Product3");
Container c= getContentPane();
c.setLayout(new FlowLayout());
setSize(500,500);
c.add(jb);
jb.add(jm1);
jb.add(jm2);
jm1.add(jl1);
jm1.add(jl2);
jm1.add(jl3);
jm2.add(jl4);
jm2.add(jl5);
jm2.add(jl6);
}
}
public class Jmenu {
public static void main(String arg[]){
Demo d=new Demo();
d.setVisible(true);
}
}
Sunday, November 4, 2012
Textbox with only number
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class Demo1 extends JFrame implements KeyListener{
JTextField jt;
JLabel jl;
Demo1(){
jt=new JTextField(15);
jl=new JLabel("Enter String ");
Container c=getContentPane();
c.setLayout(new FlowLayout());
setSize(500,500);
c.add(jl);
c.add(jt);
jt.addKeyListener(this);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()>=65 && e.getKeyCode()<=91){
//jt.setText(e.getKeyCode());
jt.setText("");
String s=jt.getText();
int l=s.length();
s=s.substring(0,l-1);
jt.setText(s);
}else
{
}
}
}
public class Textbox {
public static void main(String arg[]){
Demo1 d=new Demo1();
d.setVisible(true);
}
}
Moving ball across the boundry
import java.applet.*;
import java.awt.Color;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Moveball extends Applet implements Runnable{
public int x=1,y=0;
public void init(){
Thread t=new Thread(this);
t.start();
}
public void run(){
while(true){
try {
if(x<300 && y==0)x=x+1;
if(x==300 && y<150)y++;
if(y==150 && x>0)x=x-1;
if(x==0 && y<=150)y=y-1;
Thread.sleep(3);
repaint();
} catch (InterruptedException ex) {
Logger.getLogger(Moveball.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void paint(Graphics g){
setBackground(Color.BLUE);
setForeground(Color.GREEN);
g.drawOval(x, y, 50, 50);
}
}
Using applet to demonstrate the wind
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
public class Wind extends Applet implements Runnable{
int Theta;
int x11=0,y11=0,x12=0,y12=0,x21=0,y21=0,x22=0,y22=0;
@Override
public void run() {
while(true){
Dimension d=getSize();
x11=150+(int)(100*Math.cos(Math.toRadians(Theta)));
y11=150+(int)(100*Math.sin(Math.toRadians(Theta)));
x12=150+(int)(100*Math.cos(Math.toRadians(Theta+180)));
y12=150+(int)(100*Math.sin(Math.toRadians(Theta+180)));
x21=150+(int)(100*Math.cos(Math.toRadians(Theta+90)));
y21=150+(int)(100*Math.sin(Math.toRadians(Theta+90)));
x22=150+(int)(100*Math.cos(Math.toRadians(Theta+270)));
y22=150+(int)(100*Math.sin(Math.toRadians(Theta+270)));
Theta++;
try{
Thread.sleep(3);
repaint();
}
catch(Exception e){
}
}
}
@Override
public void init(){
Thread t1=new Thread(this);
t1.start();
}
@Override
public void paint(Graphics g){
g.drawLine(x11,y11,x12,y12);
g.drawLine(x21,y21,x22,y22);
}
}
OUTPUT
Saturday, October 20, 2012
Echoserver
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("Localhost", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = r.readLine();
if( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err) {
System.err.println(err);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket server;
public Server(int portnum) {
try{
server = new ServerSocket(portnum);
}
catch (Exception err) {
System.out.println(err);
}
}
public void serve() {
try {
while (true) {
Socket client = server.accept();
BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do {
line = r.readLine();
if( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err) {
System.err.println(err);
}
}
public static void main(String[] args){
Server s = new Server(9999);
s.serve();
}
}
Output
Welcome to the Java EchoServer. Type 'bye' to close.
hi
Got: hi
whats up
Got: whats up
f9
Got: f9
Tag library with coustom tag
author.tld
authorTagHandler.java
index.jsp
file Structure
output
1.0
au
/WEB-INF/tlds/author ;
authorTagHandler
handler.authorTagHandler
scriptless
authorTagHandler.java
package handler;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class authorTagHandler extends SimpleTagSupport {
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
out.println("welcome to my business");
JspFragment f = getJspBody();
if (f != null) {
f.invoke(out);
}
} catch (java.io.IOException ex) {
throw new JspException("Error in authorTagHandler tag", ex);
}
}
}
index.jsp
<%--
Document : index
Created on : Oct 18, 2012, 8:17:18 PM
Author : UTTAM KASUNDARA
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<%@taglib uri="/WEB-INF/tlds/author" prefix="au" %>
<au:authorTagHandler></au:authorTagHandler>
</body>
</html>
file Structure
output
Tuesday, October 16, 2012
my sql connectivity
Connection to demonstrate My sql connectivity to student with name and id filled
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class mysql1 {
public static void main(String[] args)
{
try {
System.out.println("My sql Connect Example.");
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","");
System.out.println("Connected to the database");
Statement statement = conn.createStatement();
//create table statement
String createStudentTable = "CREATE TABLE student(NAME VARCHAR(64),ID number(10))";
statement.executeUpdate(createStudentTable);
statement.executeUpdate("INSERT INTO student VALUES ( 'UML User Guide','1909')");
statement.executeUpdate("INSERT INTO student VALUES ( 'UML User Guide2','2909')");
statement.execute("UPDATE student SET id=27889 WHERE id=28889");
statement.executeQuery("delete * from student");
conn.close();
System.out.println("Disconnected from database");
} catch (InstantiationException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Connect java to Microsoft access(odbc) database
In this example demonstrate the Microsoft access(odbc) connectivity database contain the bank table with sr_no,name,Ac.no,balance,ph.no.
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Connectivity {
public static void main(String args[]){
try {
Connection c;
Statement st;
ResultSet r;
Class.forName("sun.jdbc.odbc.JdcbOdbcDrive");
c = DriverManager.getConnection("jdbc:odbc:Pruthvi”);
st = c.createStatement();
st.executeUpdate("insert into Bank(name,account_no,balance,pn_no) values('uttam',1005,10512,1612)");
r = st.executeQuery("select * from Bank");
System.out.println("Sr.No."+"\t"+"Name"+"\t"+"Ac.No."+"\t"+"Balance"+"\t"+"Ph.No");
while (r.next()) {
System.out.print(r.getInt(1)+"\t");
System.out.print(r.getString(2)+"\t");
System.out.print(r.getInt(3)+"\t");
System.out.print(r.getInt(4)+"\t");
System.out.print(r.getInt(5)+"\t");
System.out.println("");
}
c.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Connectivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connectivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
statefull visitor counter
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class counter extends HttpServlet
{
@Override
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
HttpSession session=req.getSession(true);
Integer count=(Integer)session.getAttribute("count");
if(count==null)
{
count=1;
}
else
{
count=new Integer(count.intValue()+1);
}
session.setAttribute("count", count);
PrintWriter pw=res.getWriter();
pw.println("counter is="+count);
}
}
Saturday, October 13, 2012
Create login servlet
Loginservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author UTTAM KASUNDARA
*/
@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class Loginservlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String unm=request.getParameter("unm");
String pass=request.getParameter("pass");
if(unm.equals("uttam") && pass.equals("123")){
out.println("<html><body>wel-come "+unm+"</body></html>");
}
else{
out.println("<html><body>sign again "+unm+"</body></html>");
}
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Loginservlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Loginservlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
} finally {
out.close();
}
} // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
URL connection send and properties
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class URLTesting
{
private static Map<String, List<String>> headerMap;
private static boolean key;
public static void main(String args[]) throws MalformedURLException, IOException
{
URL url=new URL("http://www.google.com:80/html/default.asp");
URLConnection urlcon=url.openConnection();
URL urltemp=new URL("http://www.google.com/html/default.asp");
HttpURLConnection httpurlcon=(HttpURLConnection) url.openConnection();
System.out.println("Protocol:"+url.getProtocol());
System.out.println("Port for URL:"+url.getPort());
System.out.println("Port for urltemp:"+urltemp.getPort());
System.out.println("Host:"+url.getHost());
System.out.println("File:"+url.getFile());
//System.out.println("String representation of URl:"+url.getExternalForm());
System.out.println("Content Type:"+urlcon.getContentType());
System.out.println("Content Encoding:"+urlcon.getContentEncoding());
System.out.println("Content Length:"+urlcon.getContentLength());
System.out.println("Date:"+ new Date(urlcon.getDate()));
System.out.println("Last Modified:"+new Date(urlcon.getLastModified()));
System.out.println("Expiration:"+new Date(urlcon.getExpiration()));
System.out.println("Request method:"+httpurlcon.getRequestMethod());
System.out.println("Responsee Message:"+httpurlcon.getResponseMessage());
System.out.println("Response code:"+httpurlcon.getResponseCode());
Map<String, List<String>>
HeaderMap=httpurlcon.getHeaderFields();
Set<String> headerKeys=(Set<String>) HeaderMap.keySet();
System.out.println("....NOW THW HEADER....");
for(String key:headerKeys)
{
System.out.println("Key:"+key);
System.out.println("value:"+HeaderMap.get(key));
System.out.println("--------------");
}
}
static class string {
public string() {
}
}
private static class set<T> {
public set() {
}
}
}
how to create dropdown list in java swing
Dropdownlist.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Dropdownlist extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Dropdownlist</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Dropdownlist at " + request.getContextPath () + "</h1>");
out.println("<form method='get'>");
out.println("<select name='s'>");
for(int i=0;i<10;i++){
out.println("<option name="+i+">"+i+"</option>");
}
out.println("</select>");
out.println("<input type='submit'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
int b=Integer.parseInt(request.getParameter("s"));
for(int j=1;j<=10;j++){
out.print(b+"*"+j+"=");
out.println(j*b);
out.println("<br>");
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
create stateless visitor counter
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author UTTAM
*/
@WebServlet(name = "Visitorcoounter", urlPatterns = {"/Visitorcoounter"})
public class Visitorcoounter extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
public static int counter=0;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession ses=request.getSession(true);
Integer count=(Integer)ses.getAttribute("count");
if(count == null){
count=1;
}
else{
count=new Integer(count.intValue()+1);
}
ses.setAttribute("counter",count);
out.println("<html><body>my sessiion"+count+"<body><html> ");
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Visitorcoounter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Visitorcoounter at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Subscribe to:
Posts (Atom)