public String getLabel()
{
return label;
}
public void setMargin(int x,int y)
{
this.marginx = x;
this.marginy = y;
}
protected void paintArea(Graphics g, boolean hasFocus)
{
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(x, y, w - 1, h - 1);
if (selected)
{
g.setColor(getForeColor());
g.fillRect(x, y, w - 1, h - 1);
g.setColor(getBackColor());
} else if (hasFocus)
{
g.setStrokeStyle(Graphics.DOTTED);
g.drawRect(x + 3, y + 3, w - 7, h - 7);
g.setStrokeStyle(Graphics.SOLID);
}
g.drawString(label, x + marginx, y + marginy, Graphics.TOP | Graphics.LEFT);
}
public void keyPressed(int keyCode)
{
int num = keyCode - 48;
if (num >= 0)
{
if (modifiable)
{
this.label = num + "";
}
repaintArea(this, true);
moveFocus(true);
return;
}
int action = getGameAction(keyCode);
switch (action)
{
case UP:
case LEFT:
moveFocus(false);
break;
case DOWN:
case RIGHT:
moveFocus(true);
break;
case FIRE:
if (listener != null)
{
listener.buttonPressed(this);
}
break;
}
}
public void setLabel(String s)
{
this.label = s;
}
public void keyReleased(int keyCode)
{
}
public void setListener(ButtonListener listener)
{
this.listener = listener;
}
}
我们应该重点关注一下paintArea()方法,以及keyPressed()方法。如果我们注册了一个ButtonListener给Button的话,那么当按键事件发生的时候,buttonPressed()方法就会触发并且把这个按键传递给他,这样我们应用程序就可以根据用户的事件来处理相关的逻辑了。