現象:
JButton類按鈕的一種擴展,當鼠標移入、移出、被點擊時有不同的外觀
解決方案:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
/** * Title: * Description: * Copyright: * Company: * @author * @version 1.0 */
/** * JButton類按鈕的一種擴展,當鼠標移入、移出、被點擊時有不同的外觀 */
public class ZButton extends JButton
{
private Border borderOut;
private Border borderIn;
private Border borderPressed;
public ZButton() { init(); } /**初始化*/
private void init()
{
borderOut = BorderFactory.createEmptyBorder();//(2,2,2,2);
borderIn = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.white,Color.white, new Color(148, 145, 140),new Color(103, 101, 98));
borderPressed = BorderFactory.createBevelBorder(BevelBorder.LOWERED,Color.white,Color.white, new Color(148, 145, 140),new Color(103, 101, 98));
this.setBorder( borderOut );
this.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(MouseEvent e)
{
thisButton_mouseEntered(e);
}
public void mouseExited(MouseEvent e)
{
thisButton_mouseExited(e);
}
public void mousePressed(MouseEvent e)
{
thisButton_mousePressed(e);
}
public void mouseReleased(MouseEvent e)
{
thisButton_mouseReleased(e);
}
});
}
/**鼠標移入時的外觀*/
void thisButton_mouseEntered(MouseEvent e)
{
if( this.isEnabled() ) this.setBorder( borderIn ); }
/**鼠標移出時的外觀*/
void thisButton_mouseExited(MouseEvent e)
{
this.setBorder( borderOut );
}
/**鼠標被點擊時的外觀*/
void thisButton_mousePressed(MouseEvent e)
{
if( this.isEnabled()) this.setBorder( borderPressed );
}
/**鼠標被釋放時的外觀*/
void thisButton_mouseReleased(MouseEvent e)
{
if( (this.getBounds().contains(e.getX(), e.getY())) && this.isEnabled() )
this.setBorder( borderIn ); else this.setBorder( borderOut ); }
}