处于按下状态,并且第一次按下时为该button,则设为按下状态的border,如果处于按下状态,但第一次按下时不在该button上,则不设置任何border。具体代码如下:
package com.bhr.ioat.coolbutton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractButton;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class CoolButtonMouseListener extends MouseAdapter
{
public final static Border DEFAULT_BORDER = new EmptyBorder(2, 2, 2, 2);
public final static Border ENTERED_BORDER = new ThinBevelBorder(ThinBevelBorder.RAISED);
public final static Border PRESSED_BORDER = new ThinBevelBorder(ThinBevelBorder.LOWERED);
private final static CoolButtonMouseListener listener_ = new CoolButtonMouseListener();
private CoolButtonMouseListener() { }
public static CoolButtonMouseListener getInstance()
{
return listener_;
}
public void mouseEntered(MouseEvent e)
{
AbstractButton button = (AbstractButton) e.getSource();
if ( (!button.isEnabled()))
{
return;
}
if (button.isSelected())
{
return;
}
if (button.getModel().isPressed())
{
button.setBorder(PRESSED_BORDER);
}
else
{
if (e.getModifiers() != MouseEvent.BUTTON1_MASK)
{
button.setBorder(ENTERED_BORDER);
}
}
}
public void mouseExited(MouseEvent e)
{
AbstractButton button = (AbstractButton) e.getSource();
if ( (!button.isEnabled()))
{
return;
}
if (button.isSelected())
{
return;
}
else
{
button.setBorder(DEFAULT_BORDER);
}
}
public void mousePressed(MouseEvent e)
{
AbstractButton button = (AbstractButton) e.getSource();
if ( (!button.isEnabled()))
{
return;
}
if (button.isSelected())
{
return;
}
button.setBorder(PRESSED_BORDER);
}
public void mouseReleased(MouseEvent e)
{
AbstractButton button = (AbstractButton) e.getSource();
if ( (!button.isEnabled()))
{
return;
}
if (button.isSelected())
{
return;
}
button.setBorder(DEFAULT_BORDER);
}
}
利用Java三步实现Cool Button(3)
时间:2010-07-19
最后一步:编写一个测试类。生成一个JButton,设置border和listener,添加到JFrame上,运行,终于大功告成了!不过,别太高兴,你会发现还是有点难看,button周围有一个小蓝框,而且鼠标按下时button的背景是深灰色。再修改一下,首先覆盖JButton的isFocusTraversable方法,让它返回false,不让它得到焦点,再调用button的setRequestFocusEnabled(false),这样button周围就不会有蓝框了。然后再调用button的setContentAreaFilled(false)方法,使得鼠标按下时不会出现深灰色背景。这样就完成了。具体代码如下:
package com.bhr.ioat.coolbutton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.JButton;
public class Test extends JFrame
{
public Test()
{
getContentPane().setLayout(new FlowLayout());
JButton button = new JButton("CoolButton") {
public boolean isFocusTravers
|