Different button shapes in swing

Make a class that extends JButton and in its constructor write following [Following code is common for all shapes]:

super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
setContentAreaFilled(false);
  • Round [Circular] buttons:

Circular Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
           g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, 0, getSize().width-1, getSize().height-1);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
     }
     return shape.contains(x, y);
}
  • Triangle buttons:

Triangle button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.fillPolygon(x3Points, y3Points, xPoints.length);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.drawPolygon(xPoints, yPoints, xPoints.length);
}
Polygon polygon;
public boolean contains(int x, int y) {
     if (polygon == null || !polygon.getBounds().equals(getBounds())) {
          int xPoints[] = {getSize().width/2, 0, getSize().width};
          int yPoints[] = {0, getSize().height, getSize().height};
          polygon = new Polygon(xPoints,yPoints, xPoints.length);
     }
     return polygon.contains(x, y);
}
  • Oval buttons:

Oval button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, getHeight()/8, getWidth(), getHeight()-getHeight()/4));
     }
     return shape.contains(x, y);
}
  • RoundRect buttons

RoundRect Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     }
     return shape.contains(x, y);
}
  • Star buttons:

Star button

public static Shape makeStarDesign(int arms, Point center, double r_out, double r_in) {
     double angle = Math.PI / arms;
     GeneralPath path = new GeneralPath();
     for (int i = 0; i < 2 * arms; i++) {
          double r = (i & 1) == 0 ? r_out : r_in;
          Point2D.Double p = new Point2D.Double(center.x + Math.cos(i * angle) * r, center.y + Math.sin(i * angle) * r);
          if (i == 0) path.moveTo(p.getX(), p.getY());
          else path.lineTo(p.getX(), p.getY());
     }
     path.closePath();
     return path;
}
protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     graphics2d.fill(makeStarDesign(5, new Point(50,50), 50, 30));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.draw(makeStarDesign(5, new Point(50,50), 50, 30));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Area(makeStarDesign(5, new Point(50,50), 50, 30));
     }
     return shape.contains(x, y);
}

More star buttons

Just change the first argument of makeStarDesign to number of arrows you want in star and it will try to draw it for you. 🙂

  • Play buttons:

Play button

      protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.fillPolygon(xPoints, yPoints, xPoints.length);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.drawPolygon(xPoints, yPoints, xPoints.length);
	}

	Polygon polygon;
	public boolean contains(int x, int y) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int xPoints[] = {0, 0, getWidth()};
			int yPoints[] = {0, getHeight(), getHeight()/2};
			polygon = new Polygon(xPoints,yPoints,xPoints.length);
		}
		return polygon.contains(x, y);
	}
  • Pentagon buttons:

Pentagon button

	int n=5;
	int x[]= new int[n];
	int y[]= new int[n];
	double angle = 2*Math.PI/n;
	protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.fillPolygon(x, y, n);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.drawPolygon(x, y, n);
	}

	Polygon polygon;
	public boolean contains(int x1, int y1) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int x0 = getSize().width/2;
			int y0 = getSize().height/2;
			for(int i=0; i<n; i++) {
				double v = i*angle;
				x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
				y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
			}
			polygon = new Polygon(x,y,n);
		}
		return polygon.contains(x1, y1);
	}
  • Diamond button:

Diamond button

Just change value of n in above code to 4.
  • Hexagon button:

Just change value of n in above code to 6.
By changing value of n you will get different shapes like follow:
Different pentagon shapes
  • More buttons:

You just have to change the code for shape everything else is same. So try it yourself…. 😉
Advertisements

Assembler in C

First of all what is an assembler? [1] [2]:

Typically a modern assembler creates object code by translating assembly instruction mnemonics into opcodes, and by resolving symbolic names for memory locations and other entities. The use of symbolic references is a key feature of assemblers, saving tedious calculations and manual address updates after program modifications.

Types of assembler:

There are two types of assemblers based on how many passes through the source are needed to produce the executable program.

  • One-pass assemblers go through the source code once and assume that all symbols will be defined before any instruction that references them.
  • Two-pass assemblers create a table with all symbols and their values in the first pass, then use the table in a second pass to generate code. The assembler must at least be able to determine the length of each instruction on the first pass so that the addresses of symbols can be calculated.

The advantage of the two-pass assembler is that symbols can be defined anywhere in program source code, allowing programs to be defined in more logical and meaningful ways, making two-pass assembler programs easier to read and maintain.

Starting now to make an assembler one first has to define an input and output form. That is what assembler takes as input and what kind of output it will provide. In here I’m trying to make an assembler based on book “System Programming and Operating System by D M Dhamdhere” so I’m assuming following input form:

             start 101

             read n

             mover breg,one

             movem breg,term

again:   mult breg,term

             add creg,one

             movem creg,term

             comp creg,four

             bc le,again

             div breg,two

             movem breg,result

             print result

             stop

n ds 2

result ds 1

one dc ‘1’

term ds 1

two dc ‘2’

four dc ‘4

end

And output form:

101) 90113     

102) 42116     

103) 52117     

104) 32117     

105) 13116     

106) 53117     

107) 63119     

108) 72104     

109) 82118     

110) 52115     

111) 100115   

112) 0 000

113) 

115) 

116)00 0 001 

117) 

118)00 0 001 

119)00 0 001 

120)  

At first declare fix structures that contains default information to be used.

struct directive{
     char symbol[10];
     int code;
}dir[5]={"start",1,"end",0,"origin",1,"ltorg",2};

struct mnemtab{
     char mnem[20];
     int opcode;
     int len;
}l[12]={"stop",0,1,"add",1,1,"sub",2,1,"mult",3,1,"mover",4,1,"movm",5,1
        "comp",6,1,"bc",7,1,"div",8,1,"read",9,1,"print",10,1};

struct regtab{
     char regsym[10];
     int code;
}reg[4]={"areg",1,"breg",2,"creg",3,"dreg",4};

struct dclcode{
     char mne[5];
     int address;
}dcl[2]={"ds",1,"dc",2};

struct compcode{
     char sym[5];
     int code;
}ccode[7]={"lt",1,"le",2,"eq",3,"gt",4,"ge",5,"any",6};

In above code I have declared all required struct that holds default information used in our program. The first one is “directive” which holds predefined directives and its code. Second one “mnemtab” holds mnemonics, its opcode and its length. Third one “regtab” is used for holding register name and its code. Fourth one “dclcode” are used for declaration statements and its code. The final one “compcode” are used for comparison symbols and its code. Beside this create some more structure that we will be used to store information as it process the input file:

struct buffer{
     char lbl[10];
     char m[10];
     char op1[10];
     char op2[10];
}buf;

struct symtab{
     char symbol[10];
     int add;
}sym[50];

struct littab{
     char lit[10];
     int address;
}literal[20];

struct tab_inc{
     int index;
     long fpos;
     int type;
}t_inc[10];

In above 4 structs the first one is used as buffer that will store information about the line that will be processed at the time. Second one is used as symbol table. This will store all symbol and its relevant addresses in it. The third one “littab” is used to store literals and its relevant address. Now create some getter, setter and update methods for above declared structs. First for getting directive code based on directive:

int get_dir(char a[10]){
      int i;
      for(i=0;i<4;i++){
            if(!strcmp(a,dir[i].symbol))
                 return dir[i].code;
      }
      return -1;
}

Update symbol to add new symbol entry in it. This function will also check for duplicate declaration of symbol. If duplicate declaration found then shows warning as “Multiple declaration of [symbolName]”.

void update_symtab(FILE *fe){
      int i,j;
      for(i=0;i<sc;i++){
            if(!strcmp(sym[i].symbol,buf.m)){
                   if(sym[i].add==0)
                         sym[i].add=lc;
                   else{
                         printf("\nMultiple declaration of %s",buf.m);
                         fprintf(fe,"\nMultiple declaration of %s",buf.m);
                   }
                   return;
            }
      }
}

Get symbol from symbol table.

int get_sym(char s[10]){
      int i,len=strlen(s);
      if(s[0]=='=') {
            for(i=0;i<ltc;i++){
                  if(!strcmp(literal[i].lit,s)) {
                        t_inc[tc].type=0;
                        return i;
                  }
            }
            strcpy(literal[ltc].lit,s);
            ltc++;
            t_inc[tc].type=0;
            return (ltc-1);
      }
      else if(s[len-1]==':'){
            s[len-1]='\0';
            strcpy(sym[sc].symbol,s);
            sym[sc].add=lc;
            sc++;
            return (sc-1);
      }
      else{
           for(i=0;i<sc;i++){
                 if(!strcmp(s,sym[i].symbol)) {
                        t_inc[tc].type=1;
                        return i;
                 }
           }
           strcpy(sym[sc].symbol,s);
           t_inc[tc].type=1;
           sym[sc].add=0;
           sc++;
           return (sc-1);
      }
}

Next is getting register code based on its name.

int get_reg(char a[]) {
      int i;
      for(i=0;i<3;i++) {
            if(!strcmp(a,reg[i].regsym))
                  return reg[i].code;
      }
      return 0;
}

Get mnemonics opcode based on its name,

int get_btcode(char a[20]) {
      int i;
      for(i=0;i<11;i++) {
            if(strcmp(l[i].mnem,a)==0)
                  return l[i].opcode;
      }
      return -1;
}

Get declaration statement code.

int get_dcl(char a[10]) {
      int i;
      for(i=0;i<3;i++) {
            if(!strcmp(dcl[i].mne,a))
                  return dcl[i].address;
      }
      return -1;
}

Clean buffer after processing on it.

void clean_buf() {
      strcpy(buf.lbl,"");
      strcpy(buf.m,"");
      strcpy(buf.op1,"");
      strcpy(buf.op2,"");
}

Get comparison statement code based on its name.

int get_ccode(char a[5]){
      int i;
      for(i=0;i<7;i++) {
            if(!strcmp(ccode[i].sym,a))
                   return ccode[i].code;
      }
      return -1;
}

Up to now I have declared data structure kind thing for the assembler and now let’s start building processing of assembler. At first one need to parse the input file to get desired information for this I have used following method which tokenize file line by line & store each token into buffer.

void parser(FILE *fi) {
      char a[20];
      int i;
      int ctr=0;
      while((c=getc(fi))!=EOF && (c!='\n')) {
            if((c!=' ') && (c!='\t') && (c!='\n')) {
                  i=0;
                  a[i++]=c;
                  while(((c=getc(fi))!=' ') && (c!=' ') && (c!='\n') && (c!=EOF) && (c!=',')) {
                         a[i++]=c;
                  }
                  a[i]='\0';
                  if(a[0]!='\0'){
                        if(ctr==0){
                             if(a[i-1]==':'){
                                    strcpy(buf.lbl,a);
                                    printf("\nlbl:%s",buf.lbl);
                                    continue;
                              }
                              else{
                                    strcpy(buf.m,a);
                                    printf("\nm:%s",buf.m);
                                    ctr++;
                              }
                        }
                        else if(ctr==1){
                              strcpy(buf.op1,a);
                              printf("\nop1:%s",buf.op1);
                              ctr++;
                        }
                        else if(ctr==2){
                              strcpy(buf.op2,a);
                              printf("\nop2:%s",buf.op2);
                              ctr=0;
                       }
                 }
                 if(c=='\n'){
                       ctr=0;
                       lnctr++;
                       return;
                 }
           }
      }
}

Now that data is parsed from file let’s start processing on this data. In pass-1 assemblers create a table with all symbols and their values. Also the assembler at least be able to determine the length of each instruction on the first pass so that the addresses of symbols can be calculated. I have created following method for Pass – 1 of assembler.

void pass1(FILE *fe,FILE *fo){
      int code,opcode,dcode;
      static int fstop=1,fend=1;
      long fpos;
      if(fstop){
            if(strcmp(buf.lbl,""))
                  get_sym(buf.lbl);
            opcode=get_btcode(buf.m);
            if(opcode==0){
                  fstop=0;
                  fprintf(fo,"%d) 0 000 \n",lc);
                  lc++;
                  return;
            }
            if(opcode==7){
                  fprintf(fo,"%d) %d",lc,opcode);
                  code=get_ccode(buf.op1);
                  fprintf(fo,"%d",code);
                  code=get_sym(buf.op2);
                  fpos=ftell(fo);
                  t_inc[tc].index=code;
                  t_inc[tc].fpos=fpos;
                  tc++;
                  fprintf(fo,"   \n");
                  lc++;
                  return;
            }
            if(opcode!=-1){
                  fprintf(fo,"%d) %d",lc,opcode);
                  code=get_reg(buf.op1);
                  if(code==0){
                        strcpy(buf.op2,buf.op1);
                  }
                  fprintf(fo,"%d",code);
                  code=get_sym(buf.op2);
                  fpos=ftell(fo);
                  t_inc[tc].index=code;
                  t_inc[tc].fpos=fpos;
                  tc++;
                  lc++;
                  fprintf(fo,"   \n");
            }
            else{
                  dcode=get_dir(buf.m);
                  if(dcode!=-1) {
                        switch(dcode){
                              case 1:
                                    lc=atoi(buf.op1);
                                    break;
                        }
                  }
                  else{
                        fprintf(fo,"%d) ***",lc);
                        code=get_reg(buf.op1);
                        if(code==0) {
                              if(!strcmp(buf.op2,""))
                                    strcpy(buf.op2,buf.op1);
                              else{
                                    fprintf(fo," *** ");
                                    fprintf(fe," Error at line %d :: Illegal register %s",lnctr 1,buf.op1);
                                    code=get_sym(buf.op2);
                                    fpos=ftell(fo);
                                    t_inc[tc].index=code;
                                    t_inc[tc].fpos=fpos;
                                    tc++;
                                    lc++;
                              }
                        }
                        fprintf(fo," %d",code);
                        code=get_sym(buf.op2);
                        fpos=ftell(fo);
                        t_inc[tc].index=code;
                        t_inc[tc].fpos=fpos;
                        tc++;
                        lc++;
                        fprintf(fo,"   \n");
                        printf("\n Error at line %d :: Unknown mnemonics: %s",lnctr-1,buf.m);
                        fprintf(fe,"\n Error at line %d :: Unknown mnemonics: %s",lnctr-1,buf.m);
                  }
            }
      }
      else{
            if(fend) {
                  if(!strcmp(buf.m,"end")){
                        fprintf(fo,"%d)   \n",lc);
                        lc++;
                        fend=0;
                  }
                  else{
                        code=get_dcl(buf.op1);
                        switch(code) {
                              case 1:
                                    fprintf(fo,"%d)  \n",lc);
                                    update_symtab(fe);
                                    lc+=atoi(buf.op2);
                                    break;
                              case 2:
                                    fprintf(fo,"%d)00 0 001  \n”,lc);
                                    update_symtab(fe);
                                    lc++;
                                    break;
                        }
                  }
            }
            else if(strcmp(buf.m,"")) {
                  code=decode_lit(buf.m,fe);
                  fprintf(fo,"%d) 00 0 %d  \n",lc,code);
                  lc++;
            }
      }
      clean_buf();
      return;
}

And for the final thing that is Pass – 2 of assembler. In pass-2 assembler uses the table created in first pass and generates code for that. For that I have created following method:

void pass2(FILE *fop){
      int i,adr,x;
      long pos;
      for(i=0;i<tc;i++){
            pos=t_inc[i].fpos;
            adr=t_inc[i].index;
            fseek(fop,pos,0);
            if(t_inc[i].type==0) {
                  if(literal[adr].address!=0)
                        fprintf(fop,"%d \t",literal[adr].address);
                  else{
                        fprintf(fop,"***");
                        printf("\n Undelared literal: %s",literal[adr].lit);
fprintf(fop,"\n Undelared literal: %s",literal[adr].lit);
                  }
            }
            else{
                  if(sym[adr].add!=0)
                        fprintf(fop,"%d\t",sym[adr].add);
                  else{
                        fprintf(fop,"***");
                        printf("\n Undeclared symbol: %s",sym[adr].symbol);
                        fprintf(fop,"\n Undeclared symbol: %s",sym[adr].symbol);
                  }
            }
      }
}

And it’s done. Assembler is ready to run. Go on try it and give your valuable response.

References:-

  1. http://en.wikipedia.org/wiki/Assembly_language#Assembler
  2. http://searchdatacenter.techtarget.com/definition/assembler
  3. http://www.cse.iitb.ac.in/~dmd/

Note: – This is not perfect assembler solution and may have some bugs. It is just for understanding basic assembler concept. Also above code is not an optimized version.

Useful Ant build tags

Questions:

How to do following tasks in ant file?

  1. Make zip file.
  2. Run command.
  3. Copy files to remote machine.
  4. Run commands on Remote Linux machine.
  5. Open an input box and respond to input value.
  6. Make an ant call.

Answers:

1. Make zip file:

Following is the xml for making zip file in ant:

<zip destfile="${destination.folder}/zipName.zip">
     <fileset dir= "${Source.folder}" />
</zip>

In here “destfile” is the name and location of the created zip file. Inside fileset tag the dir attricute is used to specify source folder form where all files will be zipped.

2. Run commands:

Here I will show you how to start tomcat in ant file to demonstrate how to run commands in ant. Following is the xml for this:

<exec dir="${tomcat.home}/bin" executable="cmd" os="Windows XP">
     <arg line="/c startup.bat"/>
</exec>

Here “${tomcat.home}” is the path of the tomcat folder. The command is given in “<arg>” tag in “line” attribute.

 

Note: To run following commands you will need JSCH jar.

3. Copy files to remote machine:

If remote machine is in your LAN and you can access it directly as \\remote_machine\path then you can use simple copy command as follows:

<copy file="${source.folder.file} " todir="\\remote\path">
</copy>

To copy files on remote machine that supports SCP use following tag:

<scp file="${source.folder.file} " todir="${remote.user}@${remote.host}:${remote.path.where.to.do.copy}"
       password="${remote.password}" trust="true">
</scp>

In above both commands “file” is the source file which you want to copy with its path. And “todir” is the remote machine folder path where you want to copy the file.

 

4. Run commands on remote machine:

You can use following tag to execute commands on remote Linux machine.

<sshexec host="${remote.host}" username="${remote.username}" password="${remote.password}"
     command="${command.to.run}" trust="true" />

For example to start tomcat use following tag:

<sshexec host="${remote.host}" username="${remote.user}" password="${remote.password}"
         command="sh ${tomcat.home}/startup.sh" trust="true" />

5. Open an input box and respond to input value:

To open an input dialog use following tag:

<input message="Enter id: " addproperty="my.id">
</input>

Here “my.id” in “addproperty” is the variable name which holds input value. Now to check if user has denied to enter value in input:

<condition property="do.abort">
     <equals arg1="n" arg2="${my.id}"/>
</condition>
<fail if="do.abort">Build aborted by user.</fail>

And if user enters value and press OK then after you can refer to entered value as “${my.id}”.

6. Make an ant call:

<antcall target="targetName">
</antcall>

Here “target” is the name of the target that will be executed.

Note: In above examples all values starting with “${”and ending with “}’’ are variables and you may have to put appropriate values in them to successfully run them.

Some useful JavaScript functions

Some JavaScript techniques and functions that will be helpful in web development.

1. Toggling visibility of a table or a div or any other element:

function toggle(div_id) {
      var el = document.getElementById(div_id);
      if ( el.style.display == 'none' ) {  el.style.display = 'block';}
      else {el.style.display = 'none';}
}

2. Remove all child nodes of an element:

var Parent = document.getElementById('elementId');
while(Parent.hasChildNodes()) {
      Parent.removeChild(Parent.firstChild);
}

3. Validate radio group:

function checkradio(formNme,radioGroupName) {
      var radios=document[formNme].elements[radioGroupName];
      for(var i=0;i<radios.length;i++){
              if(radios[i].checked)
                      return true;
      }
      return false;
}

4. Sending an async request to server:

if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
}
else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.send(null);
function handleReadyStateChange()  {
      if (xmlhttp.readyState == 4) {
          ///--- Request completed
      }
}

5. To hide/disable scroll bar of a browser:

document.documentElement.style.overflow=document.body.style.overflow='hidden';
// To again enable scroll bar do as follows:
document.documentElement.style.overflow=document.body.style.overflow='auto';

6. Validate url using Regex:

function isValidURL(url){
      //var RegExp = /^(http:\/\/|https:\/\/|ftp:\/\/){1}([0-9A-Za-z]+\.)/;
      var RegExp = /^(http:\/\/){1}([0-9A-Za-z]+\.)/;
      if (RegExp.test(url)) {
               return true;
      }
      return false;
}

7. Swap table columns:

function swapColumns (table, colIndex1, colIndex2) {
      if (!colIndex1 < colIndex2){
            var t = colIndex1;
            colIndex1 = colIndex2;
            colIndex2 = t;
      }
      if (table && table.rows && table.insertBefore && colIndex1 != colIndex2) {
            for (var i = 0; i < table.rows.length; i++) {
                   var row = table.rows[i];
                   var cell1 = row.cells[colIndex1];
                   var cell2 = row.cells[colIndex2];
                   var siblingCell1 = row.cells[Number(colIndex1) + 1];
                   row.insertBefore(cell1, cell2);
                   row.insertBefore(cell2, siblingCell1);
            }
      }
}

8. Tab view:

Refer to this link.

9. Limiting textbox/textarea to number of characters:

Refer to this link.

Lightbox Jar

LightBox.jar
--- Jar that helps you providing light box like effect in your desktop 
 application built in swing.

 You may have seen light box effects on a website but very rarely have seen light box effect in a desktop application specifically in applications that are built in java swing.  This jar helps you put light box like effect into your swing application. So now you can also give same light box effect as on your website to your desktop application made in swing.

Light box effect

Light box effect

It’s very simple and easy to use this jar. You just have to create a instance of LightBox class and then call createLightBoxEffect() method on it with desired parameters and have a light box effect in your frame with a JPanel as popup.


This jar contains following 4 classes:

LightBox.java

  • Main class that helps in providing light box like effect using JFrame and JPanel.

LightBoxUtil.java

  • Light box utility class that contains utility methods like giving buzz effect to frame, blinking frame on taskbar, making beep sound, etc.

LightBoxMouseListener.java

  • If light box is modal then this listener will be added to light box so that all mouse clicks and other mouse events comes in this class and not get passed to underlying components. This is the simplest way I thought about making light box effect modal.

LightBoxException.java

  • Exception class for Light box effect jar.

Following is the description of constructor and methods of the class used to provide light box effect in this jar:

Constructors:

public LightBox()

Creates new LightBox instance. By default the lightbox effect is modal.


public LightBox(boolean modal)

Create new LightBox instance. If modal then all components under light box effect will be not able to generate any event until light box panel is closed.

Parameters:

          modal – Whether to make light box effect modal or not.


 Methods:

public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel)

To give a light box effect.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY)

To give a light box effect and show pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on taskbar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame. Also shows pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel and pop up panel’s location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

         LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

        LightBoxException – If given size of shade panel is not proper then this exception will be raised.


 public void closeLightBox( javax.swing.JFrame jFrame,
                                           javax.swing.JPanel jPanel)

Exist light box effect.

Parameters:

          jFrame – Frame on which light box effect has taken place.

          jPanel – Panel that is shown as a pop up in light box effect.


 Links:

  1. Swing light box source code and test class are shared here.

Feel free to comment for any query or information regarding this jar on this site.

%d bloggers like this: