Thursday, July 8, 2010

Adding Border in Swing Application componenets  

0 comments


The Border class is in javax.swing.border package.Make sure you have imported the package before using borders in your application.You can add borders to components by using setBorder() method.This method has been declared in JComponent class and is available for all the components.Method getBorder() gives the name of border for the component.Borders add look and feel in your components.
BorderFactory class is used to create borders for a component.BorderFactory class has been declared in javax.swingpackage and contains method for creating various types of borders.

You can use following borders:-
  • Line Border
  • Etched Border
  • Bevel Border
Example for Line Border:-
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.BorderFactory.*;

public class bordertest extends JFrame{

public bordertest(){

JFrame frm=new JFrame("Border Test");
JButton button=new JButton("Line Border");
Border line=BorderFactory.createLineBorder(new Color(0,0,0),3);
button.setBorder(line);
frm.getContentPane().add(button);
frm.show();
frm.setSize(200,100);
}
public static void main(String a[]){
new bordertest();
}
}

createLineBorder() method is used to create a black line border that is three pixels wide.The setBorder() method is used to set the line border for the button.

Etched Border:-Replace the above code by following code from line 6.

/*
JButton button=new JButton("Etched Border");
Border etched=BorderFactory.createEtchedBorder();
button.setBorder(etched);
*/

createEtchedBorder() method is used to create Etched Border.


Bevel Border:-Bevel Border are of two types raised and lowered.You need to specify in the method createBevelBorder() which border you want.

Bevel Border Lowered:-Replace the line Border code by following code from line 6.

/*
JButton button=new JButton("Bevel Border");
Border bevellower=BorderFactory.createBevelBorder(BevelBorder.LOWERED);
button.setBorder(bevellower);
*/


Bevel Border Raised:-Replace the line Border code by following code from line 6.

/*
JButton button=new JButton("Bevel Border");
Border bevelraised=BorderFactory.createBevelBorder(BevelBorder.RAISED);
button.setBorder(bevelraised);
*/

Note:-Remove Comments from all the code before use.

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



Extension Factory Builder