In the last article, I showed the use of borders and how you can use the BorderFactory class to create one of the predefined Borders. Now, what if none of the Java-supplied Borders meet your needs?
Creating a Custom Border
To create a custom border, you should implement the javax.swing.Border interface. There are three important methods that you need to override
- Insets getBorderInsets(Component comp)
- void paintBorder(Component comp, Graphics g)
- boolean isBorderOpaque()
The 1st method getBorderInsets(), should be properly return the Insets within which the component should restrict itself. This makes sense,as the component to paint itself properly within this insets, show it doesn’t extend beyond the border.
The 2nd method paintBorder(), performs the rendering. Note: The border should paint itself within the Insets specified by the getBorderInsets() method.
The 3rd method isBorderOpaque() should return true or false depending on whether the border is opaque or transparent.
So in all, your class should look something like this:
1
2
3
4
5
6
7
8
9
10
| import ...;
public class MyBorder implements Border{
public boolean isBorderOpaque(){return true/false;}
public void paintBorder(Component comp, Graphics g){
//your paint code here, just like the paintComponent method() for components
}
public Insets getBorderInsets(component c){
return new Insets(xx,xx,xx,xx);
}
} |
[…] Accelerator/Mnemonic Keys in Swing Creating a Custom Border […]
j6n80325zp45til8