Java Notes
Border Example
Example -- A Titled, Etched, Empty Border around a Panel
Problem: Create a panel with 10 pixels of space around it, then an etched line with a title at the top left.
To do this, we need to create the etched border, then create a titled border from that. Then we put the titled border (which includes the etched border) together with the empty border to form a compound border. Then this compound border is added to the panel. Here are some ways to do this.
Solution 1 - Inline code
You need to create the borders and combine them. You could add the border in one massive statement, but here it's broken down for simplicity.import javax.swing.border.*; . . . JPanel processPanel = new JPanel(); Border etchedBdr = BorderFactory.createEtchedBorder(); Border titledBdr = BorderFactory.createTitledBorder(etchedBdr, "Process"); Border emptyBdr = BorderFactory.createEmptyBorder(10,10,10,10); Border compoundBdr=BorderFactory.createCompoundBorder(titledBdr, emptyBdr); processPanel.setBorder(compoundBdr);
Solution 2 - Utility method
It's common to use the same style of border on several panels. Write a utility method to do this, and save the method in your collection of handy methods.- There will be a consistent border style.
- Changes will be made consistently.
- The initial extra writing is repaid with only two calls.
import javax.swing.border.*; . . . // We can do this because the same border object can be reused. static final Border empty10Border = BorderFactory.createEmptyBorder(10,10,10,10); static final Border etchedBorder = BorderFactory.createEtchedBorder(); . . . public static Border myTitledBorder(String title) { return BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder(etchedBorder, title), empty10Border); }//end myTitledBorder . . . JPanel processPanel = new JPanel(); processPanel.setBorder(myTitledBorder("Process"));