Window To Viewport Transformation - C++ Program - Graphics & Multimedia Lab


Window To Viewport Transformation
 C++ Program - Graphics & Multimedia Lab

Sourcecode:
#include<graphics.h>

#include<iostream>

using namespace std;


int main()

{

    FILE *ip,*op;

    float xwmin,xwmax,ywmax,ywmin;

    float xvmin,xvmax,yvmax,yvmin;

    float x[10],y[10],yv,xv,sx,sy;

    int gd=DETECT,gm,i;

    ip=fopen("w2vinput.txt","r");

    op=fopen("w2voutput.txt","w");

    fscanf(ip,"%f %f %f %f",&xwmin,&ywmin,&xwmax,&ywmax);

    fscanf(ip,"%f %f %f %f",&xvmin,&yvmin,&xvmax,&yvmax);

    for(i=0;i < 3;i++)

    {

 fscanf(ip,"%f %f",&x[i],&y[i]);

    }

    sx=((xvmax-xvmin)/(xwmax-xwmin));

    sy=((yvmax-yvmin)/(ywmax-ywmin));



    initgraph(&gd,&gm,NULL);

    outtextxy(40,10,"Window port");

    rectangle(xwmin,ywmin,xwmax,ywmax);

    for(i=0;i <2;i++)

    {

     line(x[i],y[i],x[i+1],y[i+1]);

    }

    line(x[2],y[2],x[0],y[0]);

    getch();



    for(i=0;i <3;i++)

    {

     x[i]=xvmin+((x[i]-xwmin)*sx);

     y[i]=yvmin+((y[i]-ywmin)*sy);

    }

    outtextxy(190,145,"View port");

    rectangle(xvmin,yvmin,xvmax,yvmax);

    fprintf(op,"%s","Output points:\n");

    for(i=0;i <2;i++)

    {

     fprintf(op,"x[%d]=%f y[%d]=%f\n",i,x[i],i,y[i]);

   line(x[i],y[i],x[i+1],y[i+1]);

    }

    line(x[2],y[2],x[0],y[0]);

    fprintf(op,"x[2]=%f y[2]=%f\n",x[2],y[2]);

    getch();
    closegraph();
    
    return 0;

}

Output:
nn@linuxmint ~ $ g++ lab8.cpp -lgraph
lab8.cpp: In function ‘int main()’:
lab8.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lab8.cpp:38: warning: deprecated conversion from string constant to ‘char*’
nn@linuxmint ~ $ ./a.out



"w2vinput.txt"
22 22 150 150
200 200 350 250
45 45
125 45
125 125


"w2voutput.txt"
Output points:
x[0]=226.953125 y[0]=208.984375
x[1]=320.703125 y[1]=208.984375
x[2]=320.703125 y[2]=240.234375

Clip Lines - Cohen-Sutherland Line Clipping Algorithm - C++ Program - Graphics & Multimedia Lab

Cohen-Sutherland Line Clipping Algorithm

  C++ program - Graphics & Multimedia Lab


Sourcecode:

#include<graphics.h>

#include<iostream>

using namespace std;





#define MAX1 20



enum { TOP = 0x8, BOTTOM = 0x4, RIGHT = 0x2, LEFT = 0x1 };



enum { FALSE, TRUE };

typedef unsigned int outcode;

int m=0;

    FILE *ip,*op;

outcode compute_outcode(int x, int y, int xmin, int ymin, int xmax, int ymax)

{

    outcode oc = 0;



    if (y > ymax)

 oc |= TOP;

    else if (y < ymin)

 oc |= BOTTOM;





    if (x > xmax)

 oc |= RIGHT;

    else if (x < xmin)

 oc |= LEFT;



    return oc;

}



void cohen_sutherland (float x1, float y1, float x2, float y2, float xmin, float ymin, float xmax, float ymax)

{

    int accept;

    int done;

    outcode outcode1, outcode2;



    accept = FALSE;

    done = FALSE;



    outcode1 = compute_outcode (x1, y1, xmin, ymin, xmax, ymax);

    outcode2 = compute_outcode (x2, y2, xmin, ymin, xmax, ymax);

    do

    {

 if (outcode1 == 0 && outcode2 == 0)

 {

     accept = TRUE;

     done = TRUE;

 }

 else if (outcode1 & outcode2)

 {

     done = TRUE;

 }

 else

 {

     double x, y;

     double m=(y2-y1)/(x2-x1);

     int outcode_ex = outcode1 ? outcode1 : outcode2;

     if (outcode_ex & TOP)

     {

  x = x1 + (ymax - y1)/m;

  y = ymax;

     }



     else if (outcode_ex & BOTTOM)

     {

  x = x1 + (ymin - y1) /m;

  y = ymin;

     }

     else if (outcode_ex & RIGHT)

     {

  y = y1 + (xmax - x1)* m;

  x = xmax;

     }

     else

     {

  y = y1 + (xmin - x1)* m;

  x = xmin;

     }

     if (outcode_ex == outcode1)

     {

  x1 = x;

  y1 = y;

  outcode1 = compute_outcode (x1, y1, xmin, ymin, xmax, ymax);

     }

     else

     {

  x2 = x;

  y2 = y;

  outcode2 = compute_outcode (x2, y2, xmin, ymin, xmax, ymax);

     }

 }

    } while (done == FALSE);



   if (accept == TRUE)

   {

 fprintf(op,"\nx[%d] y[%d] x[%d] y[%d]=%.3f %.3f %.3f %.3f:(clipped line)",m,m,m+1,m+1,x1,y1,x2,y2);

 m=m+2;

 line (x1, y1, x2, y2);

   }

   else if((accept == FALSE) && (done == TRUE))

   {

   fprintf(op,"\nThe line (%.3f,%.3f),(%.3f,%.3f)is trivially rejected.",x1,y1,x2,y2);

   }

}

int main()

{

    int n;

    int i, j;

    int ln[MAX1][4];

    int clip[4];

    int gd = DETECT, gm;





   ip=fopen("csinput.txt","r");

   op=fopen("csoutput.txt","w");

    fscanf (ip,"%d", &n);

    for (i=0; i<n; i++)

 for (j=0; j<4; j++)

     fscanf (ip,"%d", &ln[i][j]);



    for (i=0; i<4; i++)

    fscanf (ip,"%d", &clip[i]);



    initgraph (&gd, &gm, NULL);



    rectangle (clip[0], clip[1], clip[2], clip[3]);

    for (i=0; i<n; i++)

 line (ln[i][0], ln[i][1], ln[i][2], ln[i][3]);

    getch();

    cleardevice();

    printf("AFTER CLIPPING");

    rectangle (clip[0], clip[1], clip[2], clip[3]);

    fprintf(op,"OUTPUT POINTS\n");

    for (i=0; i<n; i++)

    {

 cohen_sutherland (ln[i][0], ln[i][1], ln[i][2], ln[i][3],

     clip[0], clip[1], clip[2], clip[3]);

 getch();

    }

    closegraph();

    return 0;

}
Output:
nn@linuxmint ~ $ g++ lab7.cpp -lgraph
nn@linuxmint ~ $ ./a.out




"csinput.txt"
4

40 40  125 220

10 10 40 210

75 80 175 175

60 230 210 45


55 55 200 2005 



"csoutput.txt"
OUTPUT POINTS

x[0] y[0] x[1] y[1]=55.000 71.765 115.556 200.000:(clipped line)
The line (10.000,10.000),(40.000,210.000)is trivially rejected. 

2D Transformations: Translation, Scaling, Rotation - C++ Implementation - Graphics & Multimedia Lab

2D Transformations: Translation, Scaling, Rotation

  C++ program - Graphics & Multimedia Lab


Sourcecode:
#include<graphics.h>

#include<iostream>

#include<math.h>

#include<stdio.h>
using namespace std;

void translate();
void scale();
void rotate();

int main()
{
int gd=DETECT,gm,ch,exitp=0;
initgraph(&gd,&gm,NULL);
int x0,x1,y0,y1;
FILE *ip;
ip=fopen("2Dip.txt","r");
fscanf(ip,"%d %d %d %d",&x0,&y0,&x1,&y1);
rectangle(x0,y0,x1,y1);
fclose(ip);

translate();
scale();
rotate();

getch();
closegraph();
return 0;
}

void translate()
{
 int x0,x1,y0,y1;
 FILE *op,*ip1,*ip2;
 ip1=fopen("2Dip.txt","r");
 fscanf(ip1,"%d %d %d %d",&x0,&y0,&x1,&y1);
 setcolor(1);
 fclose(ip1);
 int tx,ty;
 ip2=fopen("2Dtransip.txt","r");
 fscanf(ip2,"%d %d",&tx,&ty);
 fclose(ip2);
 op=fopen("2Dop.txt","a+");
 rectangle(x0+tx,y0+ty,x1+tx,y1+ty);
 outtextxy((x0+tx+20),(y0+ty+20),(char*)"Translation");
 fprintf(op,"\nTranslation:\n");
 fprintf(op,"%d %d %d %d",x0+tx,y0+ty,x1+tx,y1+ty);
 fclose(op);
}

void scale()
{
 int x0,x1,y0,y1;
 FILE *op,*ip1,*ip2;
 int sx,sy;
 setcolor(2);
 ip1=fopen("2Dip.txt","r");
 fscanf(ip1,"%d %d %d %d",&x0,&y0,&x1,&y1);
 fclose(ip1);
 ip2=fopen("scaleip.txt","r");
 fscanf(ip2,"%d %d",&sx,&sy);
 op=fopen("2Dop.txt","a+");
 fclose(ip2);
 outtextxy(x0*sx+20,y0*sy+20,(char*)"Scaling");
 rectangle(x0*sx,y0*sy,x1*sx,y1*sy);
 fprintf(op,"\nSclaing:\n");
 fprintf(op,"%d %d %d %d",x0*sx,y0*sy,x1*sx,y1*sy);
 fclose(op);
}

void rotate()
{
 setcolor(3);
 FILE *op,*ip1,*ip2;
 float theta;
 int x0,x1,x2,x3,x4;
 int y0,y1,y2,y3,y4;
 int ax1,ax2,ax3,ax4,ay1,ay2,ay3,ay4;
 int refx,refy;
 ip1=fopen("2Dip.txt","r");
 fscanf(ip1,"%d %d %d %d",&x0,&y0,&x1,&y1);
 fclose(ip1);
 ip2=fopen("Rotip.txt","r");
 fscanf(ip2,"%f",theta);
 fclose(ip2);
 op=fopen("2Dop.txt","a+");
 theta=theta*(3.14/180);
 fprintf(op,"\nRotation:\n");

 refx=100;
 refy=100;

 ax1=refy+(x0-refx)*cos(theta)-(y1-refy)*sin(theta);
 ay1=refy+(x0-refx)*sin(theta)+(y1-refy)*cos(theta);

 ax2=refy+(x1-refx)*cos(theta)-(y1-refy)*sin(theta);
 ay2=refy+(x1-refx)*sin(theta)+(y1-refy)*cos(theta);

 ax3=refy+(x1-refx)*cos(theta)-(y0-refy)*sin(theta);
 ay3=refy+(x1-refx)*sin(theta)+(y0-refy)*cos(theta);

 ax4=refy+(x0-refx)*cos(theta)-(y0-refy)*sin(theta);
 ay4=refy+(x0-refx)*sin(theta)+(y0-refy)*cos(theta);


 line(ax1,ay1,ax2,ay2);
 fprintf(op,"%d %d %d %d\n",ax1,ay1,ax2,ay2);

 line(ax2,ay2,ax3,ay3);
 fprintf(op,"%d %d %d %d\n",ax2,ay2,ax3,ay3);

 line(ax3,ay3,ax4,ay4);
 fprintf(op,"%d %d %d %d\n",ax3,ay3,ax4,ay4);

 line(ax4,ay4,ax1,ay1);
 fprintf(op,"%d %d %d %d\n",ax4,ay4,ax1,ay1);


 fclose(op);
 outtextxy(ax1+20,ay1+20,(char*)"Rotation ");

}

Output:
nn@linuxmint ~ $ g++ lab6.cpp -lgraph
nn@linuxmint ~ $ ./a.out




"2Dip.txt"
50 60 100 75 


"2Dtransip.txt"
250 250


"scaleip.txt"
3 3


"Rotip.txt"
90.0


"2Dop.txt"
Translation:
300 310 350 325
Sclaing:
150 180 300 225
Rotation:
124 49 124 99
124 99 139 99
139 99 139 49
139 49 124 49

Draw Ellipse - Midpoint Ellipse Algorithm - C++ program - Graphics & Multimedia Lab

Midpoint Ellipse Algorithm 

Ellipse Drawing C++ program - Graphics & Multimedia Lab

Sourcecode:
#include<graphics.h>

#include<iostream>

using namespace std;



int points[20000];

int i=0;

int count=0;



void ellipsePoints(int x, int y, int value)

 {

 int maxx = getmaxx()/2;

 int maxy = getmaxy()/2;

 putpixel(maxx+x,maxy+y,value);

 points[i]=maxx+x;

 points[i+1]=maxy+y;

 i+=2;



 putpixel(maxx-x,maxy+y,value);

 putpixel(maxx+x,maxy-y,value);

 putpixel(maxx-x,maxy-y,value);

 }



void midPointEllipse(float a,float b,int value)

 {

 double d2;

 int x=0;

 int y=b;

 double dl=b*b-(a*a*b)+(0.25*a*a);

 putpixel(x,y,value);

 while((a*a*(y-0.5))>(b*b*(x+1)))

  {

  if(dl<0)

  dl+=b*b*(2*x+3);

  else

   {

   dl+=b*b*(2*x+3)+a*a*(-2*y+2);

   y--;

   }

  x++;

  ellipsePoints(x,y,value);

  }

 d2=b*b*(x+0.5)*(x+0.5)+a*a*(y-1)*(y-1)-a*a*b*b;

 while(y>0)

  {

  if(d2<0)

   {

   d2+=b*b*(2*x+2)+a*a*(-2*y+3);

   x++;

   }

  else

  d2+=a*a*(-2*y+3);

  y--;

  ellipsePoints(x,y,value);

  }

 }



int main()

 {

 int gd=DETECT, gm,np;

 FILE *fp;

 int ax1,ax2;

 initgraph(&gd, &gm, NULL);

 fp=fopen("elinput.txt","r");

 if(fp==NULL)

  {

  printf("ERROR !");

  getch();

  exit(0);

  }



 fscanf(fp,"%d %d",&ax1,&ax2);

 fclose(fp);

 midPointEllipse(ax1,ax2,WHITE);



 count=i;np=0;

 fp=fopen("eloutput.txt","w");

 fprintf(fp,"%s","Plotted points are:-\n");

 for(i=0;i<count;i+=2)

 {

  fprintf(fp,"(%d %d) ",points[i],points[i+1]);

  np++;

  if(np==5){fprintf(fp,"\n");np=0;}

 }

 fclose(fp);



 getch();

 closegraph();

 return 0;

 }


Output:
nn@linuxmint ~ $ g++ lab4.cpp -lgraph
nn@linuxmint ~ $ ./a.out




"elinput.txt"
75 50


"eloutput.txt"
Plotted points are:-
(320 289) (321 289) (322 289) (323 289) (324 289) 
(325 289) (326 289) (327 289) (328 289) (329 289) 
(330 288) (331 288) (332 288) (333 288) (334 288) 
(335 288) (336 288) (337 288) (338 287) (339 287) 
(340 287) (341 287) (342 287) (343 286) (344 286) 
(345 286) (346 286) (347 285) (348 285) (349 285) 
(350 285) (351 284) (352 284) (353 284) (354 283) 
(355 283) (356 282) (357 282) (358 282) (359 281) 
(360 281) (361 280) (362 280) (363 279) (364 279) 
(365 278) (366 278) (367 277) (368 277) (369 276) 
(370 276) (371 275) (372 274) (373 274) (374 273) 
(375 272) (376 271) (377 271) (378 270) (379 269) 
(380 268) (381 267) (382 266) (383 265) (384 264) 
(385 263) (386 262) (386 261) (387 260) (388 259) 
(388 258) (389 257) (390 256) (390 255) (391 254) 
(391 253) (391 252) (392 251) (392 250) (392 249) 
(393 248) (393 247) (393 246) (393 245) (394 244) 
(394 243) (394 242) (394 241) (394 240) (394 239) 

Midpoint Circle Algorithm - C++ Program - Graphics & Multimedia Lab


Midpoint Circle Algorithm 

Circle Drawing - C++ program - Graphics & Multimedia Lab


Sourcecode:

#include<graphics.h>

#include<iostream>

using namespace std;



int points[10000];

int i=0;

int count=0;



void circlePoints(int x, int y, int value)

 {

 int maxx = getmaxx()/2;

 int maxy = getmaxy()/2;

 putpixel(maxx+x,maxy+y,value);


 points[i]=maxx+x;

 points[i+1]=maxy+y;

 i+=2;

 
 putpixel(maxx+y,maxy+x,value);

 putpixel(maxx-x,maxy+y,value);

 putpixel(maxx+y,maxy-x,value);

 putpixel(maxx+x,maxy-y,value);

 putpixel(maxx-y,maxy+x,value);

 putpixel(maxx-x,maxy-y,value);

 putpixel(maxx-y,maxy-x,value);

 }



void midPointCircle(int radius,int value)

{

 int x = 0, y = radius;

 double d = 5.0/4.0-radius;

 while(y>x)

 {

 if(d<0)

  d += 2.0*x+3.0;

 else

    {

  d += 2.0*(x-y)+5.0;

  y--;

 }

 x++;

 circlePoints(x,y,value);

  }

}



int main()

{

 int gd=DETECT, gm,np;

 FILE *fp;

 int radius;

 initgraph(&gd, &gm, NULL);

 fp=fopen("incircle.txt","r");

 if(fp==NULL)

  {

  printf("Error in reading file!");

  getch();

  exit(0);

  }



 fscanf(fp,"%d",&radius);

 fclose(fp);

 midPointCircle(radius, WHITE);



 count=i;

 np=0;

 fp=fopen("outcircle.txt","w");

 fprintf(fp,"%s","Plotted points are:-\n");

 for(i=0;i<count;i+=2)

 {

  fprintf(fp,"(%d %d) ",points[i],points[i+1]);

 np++;

 if(np==5){fprintf(fp,"\n");np=0;}

  }

  fclose(fp);



 getch();

 closegraph();

 return 0;

 }
Output:
nn@linuxmint ~ $ g++ lab3.cpp -lgraph
nn@linuxmint ~ $ ./a.out




"incircle.txt"
100


"outcircle.txt"
Plotted points are:-
(320 339) (321 339) (322 339) (323 339) (324 339) 
(325 339) (326 339) (327 339) (328 339) (329 338) 
(330 338) (331 338) (332 338) (333 338) (334 338) 
(335 338) (336 338) (337 337) (338 337) (339 337) 
(340 337) (341 337) (342 336) (343 336) (344 336) 
(345 336) (346 335) (347 335) (348 335) (349 334) 
(350 334) (351 334) (352 333) (353 333) (354 333) 
(355 332) (356 332) (357 331) (358 331) (359 331) 
(360 330) (361 330) (362 329) (363 329) (364 328) 
(365 328) (366 327) (367 327) (368 326) (369 326) 
(370 325) (371 324) (372 324) (373 323) (374 323) 
(375 322) (376 321) (377 320) (378 320) (379 319) 
(380 318) (381 317) (382 317) (383 316) (384 315) 
(385 314) (386 313) (387 312) (388 311) (389 310) 
(390 309) 

Midpoint Line Algorithm - Line Drawing C++ program - Graphics & Multimedia Lab

Midpoint Line Algorithm 

Line Drawing C++ program - Graphics & Multimedia Lab


Sourcecode:



//MIDPOINT ALGORITHM



#include<graphics.h>

#include<iostream>

using namespace std;


int count,points[1000];

int i=0;

int gd=DETECT,gm;

int np;



void midLine(int x0,int y0,int x1,int y1)

 {

 int maxy=getmaxy();

 int dx=x1-x0;

 int dy=y1-y0;

 int d=2*dy-dx;

 int incE=2*dy;

 int incNE=2*(dy-dx);

 int x=x0;

 int y=y0;



 putpixel(x,(maxy-y),WHITE);

 points[i]=x;

 points[i+1]=y;

 i+=2;

 while(x<x1)

  {

  if(d<=0)

   {

   d=d+incE;

   x++;

   }

  else

   {

   d=d+incNE;

   x++;

   y++;

   }

  putpixel(x,(maxy-y),WHITE);

  points[i]=x;

  points[i+1]=y;

  i+=2;

  }

 }



main()

 {
  int x0,y0,x1,y1;

 FILE *fp;

 initgraph(&gd,&gm,NULL);



 fp=fopen("inlpoints.txt","r");

 if(fp==NULL)

  {

  printf("ERROR IN READING FILE !");

  getch();

  exit(0);

  }



 fscanf(fp,"%d",&x0);

 fscanf(fp,"%d",&y0);

 fscanf(fp,"%d",&x1);

 fscanf(fp,"%d",&y1);

 fclose(fp);



 midLine(x0,y0,x1,y1);

 fp=fopen("outlpoints.txt","w");

 fprintf(fp,"%s","Plotted points are:-\n");



 count=i;

 np=0;

 for(i=0;i<count;i+=2)

  {

  fprintf(fp,"(%d, %d) ",points[i],points[i+1]);

  np++;

  if(np==5) { fprintf(fp,"\n"); np=0; }

  }

 fclose(fp);



 getch();

 closegraph();

 return(0);

 }
Output:

nn@linuxmint ~ $ g++ lab2.cpp -lgraph
nn@linuxmint ~ $ ./a.out

"inlpoints.txt"
22 22 72 40


"outlpoints.txt"
Plotted points are:-
(22, 22) (23, 22) (24, 23) (25, 23) (26, 23) 
(27, 24) (28, 24) (29, 25) (30, 25) (31, 25) 
(32, 26) (33, 26) (34, 26) (35, 27) (36, 27) 
(37, 27) (38, 28) (39, 28) (40, 28) (41, 29) 
(42, 29) (43, 30) (44, 30) (45, 30) (46, 31) 
(47, 31) (48, 31) (49, 32) (50, 32) (51, 32) 
(52, 33) (53, 33) (54, 34) (55, 34) (56, 34) 
(57, 35) (58, 35) (59, 35) (60, 36) (61, 36) 
(62, 36) (63, 37) (64, 37) (65, 37) (66, 38) 
(67, 38) (68, 39) (69, 39) (70, 39) (71, 40) 
(72, 40) 

DDA Line Drawing Algorithm - C++ program - Graphics & Multimedia Lab

DDA Line Drawing Algorithm 

Line Drawing - C++ implementation - Graphics & Multimedia Lab


Sourcecode:


//DDA LINE DRAWING ALGORITHM

#include<graphics.h>

#include<iostream>

using namespace std;



int gd=DETECT,gm,maxy,points[1000];

float dx,dy,m,tmp,x,y;

FILE *fp;

int a0,b0,a1,b1;

int i,count,np;



void DDALine(int x0, int y0, int x1, int y1)

 {

  i=0;

  dx=x1-x0;

  dy=y1-y0;

  maxy=getmaxy();



  if(dx==0)

   {

    for(y=y0;y<=y1;y++)

    {

     putpixel(x0,y,WHITE);

     points[i]=x0;

     points[i+1]=y;

     i+=2;

    }

   }



  else if(dy==0)

   {

    for(x=x0;x<=x1;x++)

     {

      putpixel(x,y0,WHITE);

      points[i]=x0;

      points[i+1]=y;

      i+=2;

     }

   }



  else if(dy<=dx)

   {

    m=dy/dx;

    y=y0;

    for(x=x0;x<=x1;x++)

     {

      putpixel(x,(int)(maxy-y),WHITE);

      points[i]=x;

      points[i+1]=(int)y;

      i+=2;

      y=y+m;

     }

   }



  else

   {

    m=dx/dy;

    x=x0;

    for(y=y0;y<=y1;y++)

     {

      putpixel((int)x,maxy-y,WHITE);

      points[i]=(int)x;

      points[i+1]=y;

      i+=2;

      x=x+m;

     }

   }

 }



main()

 {

  initgraph(&gd,&gm,NULL);



  fp=fopen("linput.txt","r");

  if(fp==NULL)

   {

    printf("eRROR !");

    getch();

    exit(0);

   }



  fscanf(fp,"%d",&a0);

  fscanf(fp,"%d",&b0);

  fscanf(fp,"%d",&a1);

  fscanf(fp,"%d",&b1);

  fclose(fp);



  DDALine(a0,b0,a1,b1);



  fp=fopen("loutput.txt","w");

  fprintf(fp,"%s","Plotted points are:-\n");



  count=i;

  np=0;

  for(i=0;i<count;i+=2)

   {

    fprintf(fp,"(%d, %d) ",points[i],points[i+1]);

    np++;

    if(np==5) { fprintf(fp,"\n"); np=0; }

   }

  fclose(fp);



  getch();

  closegraph();

  return 0;

 }
Output: 
nn@linuxmint ~ $ g++ lab1.cpp -lgraph
nn@linuxmint ~ $ ./a.out


"linput.txt"
18 22 70 40


Plotted points are:-
(18, 22) (19, 22) (20, 22) (21, 23) (22, 23) 
(23, 23) (24, 24) (25, 24) (26, 24) (27, 25) 
(28, 25) (29, 25) (30, 26) (31, 26) (32, 26) 
(33, 27) (34, 27) (35, 27) (36, 28) (37, 28) 
(38, 28) (39, 29) (40, 29) (41, 29) (42, 30) 
(43, 30) (44, 30) (45, 31) (46, 31) (47, 32) 
(48, 32) (49, 32) (50, 33) (51, 33) (52, 33) 
(53, 34) (54, 34) (55, 34) (56, 35) (57, 35) 
(58, 35) (59, 36) (60, 36) (61, 36) (62, 37) 
(63, 37) (64, 37) (65, 38) (66, 38) (67, 38) 
(68, 39) (69, 39) (70, 39) 

A Simple Program to Draw a Line - - Ubuntu (libgraph) - Graphics & Multimedia Lab

A Simple C++ Program to Draw a Line 
  Ubuntu (libgraph) - Graphics & Multimedia Lab

Program:

//
#include<iostream>
#include<graphics.h>
using namespace std;
int main()
{
 int gd=DETECT,gm,x,y;
 initgraph(&gd,&gm,NULL);
 line(0,0,100,100);
 getch();
 closegraph();
 return 0;
}


Output:

nn@linuxmint ~ $ g++ cg2.cpp -lgraph
nn@linuxmint ~ $ ./a.out


Java Swing Example : JList, JOptionPane, NetBeans


Java Swing Examples: JList
NetBeans - Internet & Web Programming Lab
Design:

Sourcecode:

/*
 * sw4_list.java
 *
 * Created on Nov 26, 2011, 1:32:59 PM
 */
package swing;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author nn
 */
public class sw4_list extends javax.swing.JFrame {
DefaultListModel l1,l2;
    /** Creates new form sw4_list */
    public sw4_list() {
        initComponents();
        jList1.setModel(l1= new DefaultListModel());
        jList2.setModel(l2= new DefaultListModel());
    }

    /** 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jList1);

        jScrollPane2.setViewportView(jList2);

        jButton1.setText("ADD");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("REMOVE");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("SORT");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("<");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText(">");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel1.setText("List 1");

        jLabel2.setText("List 2");

        jButton6.setText("<<");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setText(">>");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel2))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(8, 8, 8)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jButton1)
                .addGap(1, 1, 1)
                .addComponent(jButton2)
                .addGap(1, 1, 1)
                .addComponent(jButton3)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel2)
                .addGap(3, 3, 3)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    Object[] listops= {"List 1","List 2"};
            
    String ch=(String) JOptionPane.showInputDialog(rootPane, "Select","Select List Box", JOptionPane.PLAIN_MESSAGE,null, listops,"list1");
    if(ch.compareTo("List 1")==0)
            l1.addElement(JOptionPane.showInputDialog("Enter the element: "));
    else
        l2.addElement(JOptionPane.showInputDialog("Enter the element: "));
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    Object[] obj1 = jList1.getSelectedValues();
    Object[] obj2 = jList2.getSelectedValues();
    if((obj1.length==0)&&(obj2.length==0))
            JOptionPane.showMessageDialog(rootPane, "Please select an item");
    else
    {
        int i;
        for(i=0;i<obj1.length;i++)
        l1.removeElement(obj1[i]);
        for(i=0;i<obj2.length;i++)
        l2.removeElement(obj2[i]);
    }
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
     Object[] listops= {"List 1","List 2"};
            
    String ch=(String) JOptionPane.showInputDialog(rootPane, "Select","Select List Box", JOptionPane.PLAIN_MESSAGE,null, listops,"list1");
    if(ch.compareTo("List 1")==0)
           l1= sort(l1);
    else
        l2=sort(l2);
}//GEN-LAST:event_jButton3ActionPerformed

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
     Object[] temp = jList1.getSelectedValues();
   if(temp.length>1)
       JOptionPane.showMessageDialog(rootPane, "Please select only one item...");
   else if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else
   {
       l2.addElement(temp[0]);
       l1.removeElement(temp[0]);
   }
}//GEN-LAST:event_jButton5ActionPerformed

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList2.getSelectedValues();
      if(temp.length>1)
       JOptionPane.showMessageDialog(rootPane, "Please select only one item...");
   else if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
    l1.addElement(temp[0]);
    l2.removeElement(temp[0]);
   }
}//GEN-LAST:event_jButton4ActionPerformed

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList1.getSelectedValues();
    if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
        
        for(int i=0;i<temp.length;i++)
        {
            l2.addElement(temp[i]);
            l1.removeElement(temp[i]);
        }
    }
}//GEN-LAST:event_jButton7ActionPerformed

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList2.getSelectedValues();
    if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
        
    
    for(int i=0;i<temp.length;i++)
    {
        l1.addElement(temp[i]);
        l2.removeElement(temp[i]);
    }}
}//GEN-LAST:event_jButton6ActionPerformed
public DefaultListModel sort (DefaultListModel dm){
    Object[] obj = dm.toArray();
    int n= obj.length;
    for(int i=0;i<n;i++)
        for(int j=0;j<n-i-1;j++)
            if(Integer.parseInt(obj[j].toString())>Integer.parseInt(obj[j+1].toString()))
            {
                Object temp = obj[j];
                obj[j]=obj[j+1];
                obj[j+1]=temp;
            }
    dm.removeAllElements();
    for(int i=0;i<n;i++)
        dm.addElement(obj[i]);
    return dm;
}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(sw4_list.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(sw4_list.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(sw4_list.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(sw4_list.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new sw4_list().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}

Java Swing Examples: Transfer Data Between JLists - NetBeans - Internet & Web Programming Lab

Java Swing Examples: Transfer Data Between JLists 
NetBeans - Internet & Web Programming Lab

Design:

Sourcecode:


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * sw3.java
 *
 * Created on 22 Nov, 2011, 4:21:10 PM
 */
package swing;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author student
 */
public class sw3 extends javax.swing.JFrame {
    DefaultListModel dm1,dm2;
    /** Creates new form sw3 */
    public sw3() {
        initComponents();
        jList1.setModel(dm1=new DefaultListModel());
        jList2.setModel(dm2=new DefaultListModel());
        dm1.addElement("Nidheesh");
        dm1.addElement("Hunaif");
        dm1.addElement("Adarsh");
        dm1.addElement("Mirosha");
        dm1.addElement("Jamsheena");
        dm1.addElement("Anamika");
    }

    /** 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "1", "2", "3" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        jScrollPane2.setViewportView(jList2);

        jButton1.setText("<");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(">");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("<<");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(">>");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setText("JList 1");

        jLabel2.setText("JList 2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))
                        .addGap(34, 34, 34)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(76, 76, 76)
                        .addComponent(jLabel1)
                        .addGap(222, 222, 222)
                        .addComponent(jLabel2)))
                .addContainerGap(37, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
                .addGap(49, 49, 49))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(29, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(3, 3, 3)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList1.getSelectedValues();
   if(temp.length>1)
       JOptionPane.showMessageDialog(rootPane, "Please select only one item...");
   else if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else
   {
       dm2.addElement(temp[0]);
       dm1.removeElement(temp[0]);
   }
   
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
     Object[] temp = jList2.getSelectedValues();
      if(temp.length>1)
       JOptionPane.showMessageDialog(rootPane, "Please select only one item...");
   else if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
    dm1.addElement(temp[0]);
    dm2.removeElement(temp[0]);
   }
    
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList1.getSelectedValues();
    if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
        
        for(int i=0;i<temp.length;i++)
    {
        dm2.addElement(temp[i]);
        dm1.removeElement(temp[i]);
    }
    }
}//GEN-LAST:event_jButton4ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
    Object[] temp = jList2.getSelectedValues();
    if(temp.length<1)
       JOptionPane.showMessageDialog(rootPane, "Please select an item...");
   else{
        
    
    for(int i=0;i<temp.length;i++)
    {
        dm1.addElement(temp[i]);
        dm2.removeElement(temp[i]);
    }}
}//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(sw3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(sw3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(sw3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(sw3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new sw3().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}

Java Swing Examples: Add, Remove, Sort Elements in JList using JOptionPane - Internet & Web Programming Lab

Java Swing Example: Add, Remove, Sort Elements in JList using JOptionPane

Design: 

Source code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * sw4.java
 *
 * Created on 21 Nov, 2011, 8:11:19 PM
 */

package swingexamples;

import java.util.Enumeration;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author nn
 */
public class sw4 extends javax.swing.JFrame {
    DefaultListModel dm;
    /** Creates new form sw4 */
    public sw4() {
        initComponents();
        jList1.setModel(dm=new DefaultListModel());
    }

    /** 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("ADD");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("REMOVE");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("SORT");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
        jLabel1.setText("JList");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(52, 52, 52)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(jLabel1)))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(71, 71, 71)
                        .addComponent(jButton1)
                        .addGap(32, 32, 32)
                        .addComponent(jButton2)
                        .addGap(36, 36, 36)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        dm.addElement(JOptionPane.showInputDialog("Enter an element to add"));
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Object s[]=jList1.getSelectedValues();
        for(int i=0;i<s.length;i++)
           dm.removeElement(s[i]);
       
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
      Object temp;
      Object ob[]= dm.toArray();
      int n=ob.length;
      for(int i=0;i<n;i++)
          for(int j=0;j<n-i-1;j++)
          {
            if(ob[j].toString().compareTo(ob[j+1].toString())>0) // used to sort strings
            //    if(Integer.parseInt(ob[j].toString()) > Integer.parseInt(ob[j+1].toString())) used to sort ineger numbers
                
            {
             temp=ob[j];
             ob[j]=ob[j+1];
             ob[j+1]=temp;
            }

          }
    dm.removeAllElements();
    for(int i=0;i<n;i++)
      dm.addElement(ob[i]);
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new sw4().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
Note: In the source code < is replaced with "&lt;" for syntax highlighting.

Calculator - Java Swing - Netbeans - Internet & Web Programming Lab


Calculator Implementation in Java Swing - NetBeans


Design:



Sourcecode (NetBeans):
/*
 * NewFrame.java
 *
 * Created on Nov 20, 2011, 4:29:49 AM
 */
package swing;

/**
 *
 * author nn
 */
public class swingCalc extends javax.swing.JFrame {
    String stringtemp;
    float resltemp;
    boolean opflag,startflag,decimalflag;
    int chooseop;
    /** Creates new form swingCalc */
    public swingCalc() {
        super("Calculator");
        initComponents();
        startflag=true;
    }

    /** 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jButton13 = new javax.swing.JButton();
        jButton16 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jButton17 = new javax.swing.JButton();
        jButton14 = new javax.swing.JButton();
        jButton15 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(36, 119, 125));

        jPanel1.setOpaque(false);

        jTextField1.setEditable(false);
        jTextField1.setFont(new java.awt.Font("DejaVu Sans", 1, 18));
        jTextField1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel1.setFont(new java.awt.Font("URW Gothic L", 1, 24));
        jLabel1.setForeground(new java.awt.Color(52, 169, 236));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("www.2k8618.blogspot.com");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setLayout(new java.awt.GridLayout(4, 4));

        jButton1.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton1.setText("1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);

        jButton2.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton2.setText("2");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jButton3.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton3.setText("3");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);

        jButton11.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18)); // NOI18N
        jButton11.setText("+");
        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton11);

        jButton4.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton4.setText("4");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);

        jButton5.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton5.setText("5");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton5);

        jButton6.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton6.setText("6");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton6);

        jButton12.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton12.setText("-");
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton12);

        jButton7.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton7.setText("7");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton7);

        jButton8.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton8.setText("8");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton8);

        jButton9.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton9.setText("9");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton9);

        jButton13.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton13.setText("*");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton13);

        jButton16.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton16.setText("Clear");
        jButton16.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton16ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton16);

        jButton10.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton10.setText("0");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton10);

        jButton17.setFont(new java.awt.Font("DejaVu Sans", 1, 18)); // NOI18N
        jButton17.setText(".");
        jButton17.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton17ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton17);

        jButton14.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton14.setText("/");
        jButton14.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton14ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton14);

        jButton15.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18));
        jButton15.setText("=");
        jButton15.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton15ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addGap(12, 12, 12))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton15, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"1");
    opflag=false;
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
// TODO add your handling code here:
    resltemp += Float.parseFloat(jTextField1.getText());
    jTextField1.setText(Float.toString(resltemp));
    chooseop=1;
    opflag=true;
    startflag=false;
    decimalflag=false;
}//GEN-LAST:event_jButton11ActionPerformed

private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed
// TODO add your handling code here:
    if(opflag||startflag) 
        jTextField1.setText("error");
    else{
        switch(chooseop)
        {
            case 1:
                jTextField1.setText(Float.toString(resltemp += Float.parseFloat(jTextField1.getText())));
                break;
            case 2:
                jTextField1.setText(Float.toString(resltemp -= Float.parseFloat(jTextField1.getText())));
                break;
            case 3:
                jTextField1.setText(Float.toString(resltemp *= Float.parseFloat(jTextField1.getText())));
                break;
            case 4:
                jTextField1.setText(Float.toString(resltemp /= Float.parseFloat(jTextField1.getText())));
                break;                
        }   
    
  
    }
    resltemp=0;
    opflag=true;
    startflag=true;
    decimalflag=false;
}//GEN-LAST:event_jButton15ActionPerformed

private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
// TODO add your handling code here:
    if(startflag)
      resltemp = Float.parseFloat(jTextField1.getText());
    else
      resltemp -= Float.parseFloat(jTextField1.getText());  
    jTextField1.setText(Float.toString(resltemp));
    opflag=true;
    chooseop=2;
    startflag=false;
    decimalflag=false;
}//GEN-LAST:event_jButton12ActionPerformed

private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed
// TODO add your handling code here:
    jTextField1.setText(null);
    resltemp=0;
    startflag=true;
    decimalflag=false;
    
}//GEN-LAST:event_jButton16ActionPerformed

private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
// TODO add your handling code here:
   if(startflag)
      resltemp = Float.parseFloat(jTextField1.getText());
   else
      resltemp *= Float.parseFloat(jTextField1.getText());
    jTextField1.setText(Float.toString(resltemp));
    chooseop=3;
    opflag=true;
    startflag=false;
    decimalflag=false;
}//GEN-LAST:event_jButton13ActionPerformed

private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
// TODO add your handling code here:
      if(startflag)
      resltemp = Float.parseFloat(jTextField1.getText());
    else
        resltemp /= Float.parseFloat(jTextField1.getText());
    
    jTextField1.setText(Float.toString(resltemp));
    chooseop=4;
    opflag=true;
   startflag=false;
   decimalflag=false;
}//GEN-LAST:event_jButton14ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"2");
    opflag=false;
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"3");
    opflag=false;
}//GEN-LAST:event_jButton3ActionPerformed

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"4");
  opflag=false;
}//GEN-LAST:event_jButton4ActionPerformed

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"5");
  opflag=false;
}//GEN-LAST:event_jButton5ActionPerformed

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"6");
  opflag=false;
}//GEN-LAST:event_jButton6ActionPerformed

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"7");
    opflag=false;
}//GEN-LAST:event_jButton7ActionPerformed

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"8");
    opflag=false;
}//GEN-LAST:event_jButton8ActionPerformed

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"9");
    opflag=false;
}//GEN-LAST:event_jButton9ActionPerformed

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
// TODO add your handling code here:
     if(opflag)
        jTextField1.setText(null);
    stringtemp = jTextField1.getText();
    jTextField1.setText(stringtemp+"0");
    opflag=false;
}//GEN-LAST:event_jButton10ActionPerformed

private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed
// TODO add your handling code here:
    if(!decimalflag)
    {
        if(opflag)
        jTextField1.setText(null);
        stringtemp = jTextField1.getText();
        jTextField1.setText(stringtemp+".");
        opflag=false;
        decimalflag=true;
    }
    else
    {
        jTextField1.setText("error");
        resltemp=0;
        opflag=true;
        startflag=true;
    }
}//GEN-LAST:event_jButton17ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(swingCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(swingCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(swingCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(swingCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new swingCalc().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton14;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton16;
    private javax.swing.JButton jButton17;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
}

Shredskerala - Oracle Campus Recruitment Aptitude Questions - Basic Computer Knowledge - Java Aptitude Questions



Shreds Kerala 
Oracle Financial Services Campus Recruitment - 2012

Aptitude Questions
 

BASIC COMPUTER KNOWLEDGE APTITUDE SECTION – Sample Questions
Java- Aptitude Questions
Basic level of the Java assessment. This is to test your skills in Fundamentals of java, Object Oriented P rogramming, Collections and Generics , etc...


Question Number 1

Which of the following correctly maps the default values of the array elements of the types indicated?

a. String → "null"
b. float → 0.0
c. boolean → true
d. char → '\u0000'


Question Number 2 
What will be the output of the following code snippet?
public class LoopTest  {
public static void main(String[] args)  
{
int[] aLoop = {1,3,5,7,9}; 
for(int x : aLoop) 
{ 
for(int j = 0; j < 3; j++) 
{ 
if(x > 4 && x < 8) continue; 
System.out.print(" " + x);
if(j == 1) break; 
continue; 
}
continue;
}
}
}

a. 1 1 3 3 9 9
b. 1 3 3 9 9
c. 5 5 7 7
d. 1 3 9


Question Number 3 
Select from below options what is the right order in which the compilation units (class, interface, package and import statements) must appear in a file?

a. Package declaration
 Import statements
 Class, interface definitions
b. Import statements
Package declaration
Class, interface definitions
c. Package declaration
Class, interface definitions
Import statements
d. None of these


Question Number 4 
Which of the following statements will NOT cause an early termination of the loop?

a. continue
b. return
c. System.exit()
d. break


Question Number 5

Consider the following lines of code:

byte xValue=64; 
byte yValue=5;
byte zValue= (byte)(xValue*yValue);

After execution, what is the value of zValue?

a. 320
b. 0
c. 64
d. 645


Question Number 6 
Select the static methods which are defined in the java.lang.String class.

a. valueOf
b. length
c. indexOf
d. compare


Question Number 7 
Which of the following code fragments will compile without errors?

a. float f = 56.66;
b. boolean v = false,i;
c. double d = 34.56L;
d. char c = "d";

Question Number 8

Which of the following options correctly places a file named 'Test.java' in a directory 'src/test/'?

a. package src.test.Test.java;
b. package src;
package test;
public class Test
{
}
c. package src.test;
public class Test
{
}
d. package src/test;
public class Test
{
}


Question Number 9
 
Which of the following is the result of compiling and running the following program?

public class Test  
{ 
public static final String TEST = "test"; 
public static void main(String[ ] args)  
{ 
Test b = new Test(); 
Sub s = new Sub(); 
System.out.print(Test.TEST);
System.out.print(Sub.TEST) ; 
System.out.print(b.TEST); 
System.out.print(s.TEST); 
System.out.print(((Test)s).TEST); 
}  
} 
class Sub extends Test { public static final String TEST= "test1"; } 


a. testtest1testtest1test
b. test1test1test1test1test1
c. testtesttesttest1test
d. testtesttesttest1test1


Question Number 10
With respect to the below code choose the correct option.
public class Test
{
private static String var1; 
private int var2;
private String var3; 
void method1() 
{
String var4;
}
void method2() 
{
}
void method3() 
{
}
}
a. var4 is an instance variable
b. var2 is a class variable
c. var1 is a class variable
d. var3 is a local variable


Question Number 11 
What will be the output of the following program?
class Parent
{
private final void callParent()  
{
System.out.println("Parent");
}
}
public class Child extends Parent
{
public final void callParent()
{
System.out.println("Child");
}
public static void main(String [] args)
{
new Child ().callParent();
}
} 
a. Child
b. Compilation fails
c. Child
d. Parent
Parent


Question Number 12
Consider a method with the below signature.
void test(Double r)
Which of the following invocations will result in a compiler error?

a. test(2)
b. test(.2d)
c. test(2D)
d. test(2.0)

Question Number 13 
Which of the following statements is TRUE about the program given below?

interface Test1 { } 
interface Test2 extends Test1 { } 
class Test3 implements Test2 { }
class Test4 extends Test3 implements Test2 { }
public class Test 
{
public static void main(String[] args)
{
System.out.println(new Test4() instanceof Test3); //line 1
System.out.println(new Test4() instanceof Test2);//line 2
System.out.println(new Test4() instanceof Test1);//line 3
System.out.println(new Test3() instanceof Test4);//line 4 
System.out.println(new Test3() instanceof Test1);//line 5
}
}

a. All lines will evaluate to true
b. Only line 1 and 2 will evaluate to true
c. All lines will evaluate to true and only line 4 will evaluate to false
d. Lines 3 and 5 will evaluate to false

Question Number 14
Consider the following code segment:

import myLibrary.*;
class TestClass
{
// code for the class... 
}

What should be the name of this file in order to compile and run the code segment successfully?

a. TestClass
b. TestClass.java
c. Any filename with the extension .java
d. TestClass.class


Question Number 15 
Which of the following keywords cannot be used for an abstract method in abstract class?

a. abstract
b. static
c. public
d. void


Question Number 16
Consider a method with the below signature.
public void testDouble(double a)
Which of the following invocations will result in a compiler error?

a. testDouble(0.5+0.1)
b. testDouble(0.3,0.2)
c. testDouble(0.2f)
d. testDouble(0) 

Question Number 17
 
A __________ is a collection with no duplicate elements.
a. List
b. Set
c. Map
d. Queue


Question Number 18
Which of the following is a Java collection interface?

a. ConcurrentSkipListSet
b. LinkedBlockingDeque
c. ConcurrentSkipListMap
d. NavigableMap

Question Number 19 
Which of the following methods is to be used for adding elements to a generic Map?

a. insert()
b. put()
c. addvalue()
d. add()


Question Number 20
What is the legal syntax for accessing collection loop in generics?
a.
void printList(Collection<Object> c)  
{
for (Object e =c)
{
System.out.println(e);
}
}
b.
void printList(Collection<Object> c)
{
for (int count=0 ; count < c.size();)
{
System.out.println(e);
}
}
c.
void printList(Collection<Object> c)
{
for (c)
{
System.out.println(e);
}
}
d.
void printList(Collection<Object> c)
{
for (Object e : c)
{
System.out.println(e);
}
}

Related Posts Plugin for WordPress, Blogger...