import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonwithImageIcon extends JFrame {
public static void main(String[] args) {
ButtonwithImageIcon that = new ButtonwithImageIcon();
that.setVisible(true);
}
public ButtonwithImageIcon() {
setSize(450, 350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ButtonPanel(), BorderLayout.SOUTH);
}
}
class ButtonPanel extends JPanel {
public ButtonPanel() {
JButton btn = new JButton("Push Me", new BoxIcon(Color.blue, 2));
btn.setRolloverIcon(new BoxIcon(Color.cyan, 3));
btn.setPressedIcon(new BoxIcon(Color.yellow, 4));
btn.setHorizontalTextPosition(JButton.LEFT);
btn.setBorder(BorderFactory.createEtchedBorder());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was pressed.");
}
});
add(btn);
}
}
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);
}
}
|