Changing borders on the fly

Here is a short program that creates four labels. Each label draws a bevel border around itself when the mouse pointer enters the component’s region and erases it when the mouse leaves the region. This kind of “rollover” effect has become a popular feature in some applications’ toolbars. Modifying the program to use soft bevel borders would be trivial.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class BevelExample extends JPanel {

	BevelBorder bevel;
	EmptyBorder empty;
	JLabel label[] = new JLabel[4];

	public BevelExample() {
		setLayout(new GridLayout(1, 4));

		bevel = new BevelBorder(BevelBorder.RAISED);
		empty = new EmptyBorder(5, 5, 5, 5);

		label[0] = new JLabel("Home");
		label[1] = new JLabel("Back");
		label[2] = new JLabel("Forward");
		label[3] = new JLabel("Stop");

		for (int i = 0; i < label.length; i++) {
			label[i].addMouseListener(new RolloverListener());

	public static void main(String s[]) {
		JFrame frame = new JFrame("Bevel Border");
		frame.setSize(400, 100);
		frame.setContentPane(new BevelExample());

	// Inner class to respond to mouse events for the "rollover" effect
	class RolloverListener extends MouseAdapter {
		public void mouseEntered(MouseEvent e) {
			((JLabel) e.getComponent()).setBorder(bevel);

		public void mouseExited(MouseEvent e) {
			((JLabel) e.getComponent()).setBorder(empty);

		public void mouseClicked(MouseEvent e) {
			String text = ((JLabel) e.getComponent()).getText();
			System.out.println("You clicked " + text + "!");