日期:2014-05-20  浏览次数:20705 次

为什么这个椭圆Button在移动的时候椭圆背景会消失???代码如下,急救啊??
public class MergeButton extends JButton
{
   
public JPanel jPanel = null;
//鼠标的原始点,按按钮坐标算,就是本按钮的左上方为原点
  private Point origin = new Point();
  //本个按钮
  MergeButton thisButton = this;
  //父容器,如你将按钮放在一个面板上,面板就是按钮的父容器
  Container parent = null;
   
  private boolean moved = false;
  //注意, parent不能在构造函数中初始化,因为当按钮创建的时候,他还没有放在一个容器里,
  //这个时候按钮是没有父容器的。
  public MergeButton ()
  {
  addListener();
  Dimension size = getPreferredSize(); // 这些声明把按钮扩展为一个圆而不是一个椭圆。
size.width = size.height = Math.max(size.width,size.height);
this.setPreferredSize(size);
this.setContentAreaFilled(false);//这个调用使JButton不画背景,而允许我们画一个圆的背景。
  }

  public MergeButton(String text)
  {
  super(text);
  Dimension size = getPreferredSize(); // 这些声明把按钮扩展为一个圆而不是一个椭圆。
size.width = size.height = Math.max(size.width,size.height);
setPreferredSize(size);
setContentAreaFilled(false);//这个调用使JButton不画背景,而允许我们画一个圆的背景。
  addListener();
  }
   
   
  protected void paintComponent(Graphics g){
  String text =this.getText();
  if (getModel().isArmed()) {
g.setColor(Color.lightGray); // 按钮按下时的属性
}else{
g.setColor(this.getBackground());  
}
  Point location = this.getLocation();
  if(!moved){
  System.out.println("location.y+text.length()*2+2:"+(location.y+text.length()*2+2));
g.fillOval(0,location.y+text.length()*2+2,this.getSize().width-5,(this.getSize().height)/2);
}else{
//thisButton.getX()
System.out.println("location.y:"+location.y);
// System.out.println("location.y+text.length()*2+2:"+(location.y+text.length()*2+2));
System.out.println("Move location.y+text.length()*2+2:"+(location.y+text.length()*2+2));
g.fillOval(0,location.y,this.getSize().width-5,(this.getSize().height)/2);
}
  super.paintComponent(g);//这个调用会画一个标签和焦点矩形,可以在button里面写入数据
}
   
// 用简单的弧画按钮的边界。
protected void paintBorder(Graphics g) {
g.setColor(this.getForeground());
String text = this.getText();
Point location = this.getLocation();
if(!moved){
g.drawOval(0, location.y+text.length()*2+2, this.getSize().width-5,(this.getSize().height)/2);
}else{
//location.x
g.drawOval(0, location.y, this.getSize().width-5,(this.getSize().height)/2);
}
}
 
  
  private void addListener()
  {
  //一个匿名类,实现mousePressed,当鼠标按下时,得到鼠标的坐标,
  //注意,是按本按钮的坐标系来算
  this.addMouseListener(new MouseAdapter()
  {
  public void mousePressed(MouseEvent event)
  {
  origin = event.getPoint();
  }
   
  public void mouseReleased(MouseEvent event)
  {
  thisButton.setLocation(thisButton.getLocation());
  thisButton.repaint();
  }
  });

  this.addMouseMotionListener(new MouseMotionAdapter()
  {
  public void mouseDragged(MouseEvent event)
  {
  moved = true;
  Point p = thisButton.getLocation();
  Point location = new Point(p.x+event.getX()-origin.x, p.y+event.getY()-origin.y);

  if (parent == null)