FileDocCategorySizeDatePackage
ButtonPanel.javaAPI DocExample1583Tue Nov 27 14:15:46 GMT 2001None

ButtonPanel.java

//SwingDemo example from "Java 2 Complete" publisher Sybex[1999]


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

public class ButtonPanel extends JPanel 
{
	private JTextField log;
	public ButtonPanel(JTextField tf)
	{
		this.log = tf;
		// create button
		JButton btn = new JButton("Push me",
				new BoxIcon(Color.blue,2));
		// set alternative icons
		btn.setRolloverIcon(new BoxIcon(Color.cyan,3));
		btn.setPressedIcon(new BoxIcon(Color.yellow,4));

		// set text to left of icon
		btn.setHorizontalTextPosition(JButton.LEFT);
		
		// set border
		btn.setBorder(BorderFactory.createEtchedBorder());

		// set listener
		btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				log.setText("Button was pressed");
			}
		});
		
		// add button to panel
		add(btn);
	}
	// inner class creates a 20x20 icon with black border
	// width and color are specified in constructor
	class BoxIcon implements Icon
	{
		private Color color;
		private int borderWidth;
		BoxIcon(Color color, int borderWidth)
		{
			this.color=color;
			this.borderWidth=borderWidth;
		}
		public int getIconWidth(){return 20;}
		public int getIconHeight(){return 20;}
		public void paintIcon(Component c, Graphics g, int x, int y)
		{
			g.setColor(Color.black);
			g.fillRect(x,y,getIconWidth(),getIconHeight());
			g.setColor(color);
			g.fillRect(x+borderWidth, y+borderWidth,
				getIconWidth()-2*borderWidth,
				getIconHeight()-2*borderWidth);
		}
	}
			
	
	
} // end class