我有一个头像类,它显示一个由形状(椭圆,矩形)制成的人,带有两个子类,它们是特殊的化身(例如ninjaavatar)和一个按钮类,延伸文本框。我必须设置它,以便按钮类构造函数将化身作为参数。另外,我还有另一个类,它在一个框架上显示我的所有三个化身,每个化身都在下面有一个"按钮",当按钮单击时,它应该使阿凡达在阿凡达(Avatar单击。
这是我的班级,将所有化身带入一个帧
import wheelsunh.users.*;
import java.awt.Color;
import java.awt.event.MouseEvent;
/**
* Creates and displays three avatars in three different locations
* and three different colors.
*
* @author Devin Gero
* Avatar
*/
public class Program5
{
private Button _basic, _smoking, _ninja;
public Avatar _a1;
public SmokingAvatar _s1;
public NinjaAvatar _n1;
public Program5 ( )
{
Avatar _a1 = new Avatar( 100, 225 );
SmokingAvatar _s1 = new SmokingAvatar( 300, 225 );
NinjaAvatar _n1 = new NinjaAvatar( 500, 225 );
Button _basic = new Button ( 200, 300, _a1 );
_basic.setText( " This Avatar is basic. " );
_basic.setColor( _a1.getColor( ) );
_basic.setLocation( _a1.getXLocation( ) - 70, _a1.getYLocation( ) + 130 );
Button _smoking = new Button ( 200, 300, _s1 );
_smoking.setText( " This Avatar is Smoking. " );
_smoking.setColor( _s1.getColor( ) );
_smoking.setLocation( _s1.getXLocation( ) - 60, _s1.getYLocation( ) + 130 );
Button _ninja = new Button ( 200, 300, _n1 );
_ninja.setText( " This Avatar is a ninja! " );
_ninja.setColor( _n1.getColor( ) );
_ninja.setLocation( _n1.getXLocation( ) - 50, _n1.getYLocation( ) + 130 );
}
public static void main( String[] args )
{
Frame f = new Frame();
Program5 a = new Program5 ( );
}
}
现在,当我单击三个按钮中的每个按钮中的每个按钮中,它可以做我想做的事情时,它将Avatars衬衫的颜色更改为青色,然后再回到黄色。但是问题是,我需要拥有它,以便每个按钮,当"激活"将使它的头像做一些不同的事情。我只希望在单击按钮时将其衬衫更改为蓝色的第一个头像,但是,例如,忍者按钮,我希望它将眼睛变成红色,将剑变成金色或任何东西。只是与基本的头像按钮不同的东西。
这是我的按钮类
import wheelsunh.users.*;
import java.awt.Color;
import java.awt.event.MouseEvent;
public class Button extends TextBox
{
Color _curr;
public Avatar _bs, _nj;
public SmokingAvatar _sm;
public Button ( int x, int y, Avatar _a1 )
{
setSize( x, y );
_bs = _a1;
_curr = _a1.getColor();
this.setColor( _curr );
}
public Button ( int x, int y, SmokingAvatar _s1 )
{
super( );
_sm = _s1;
_curr = _s1.getColor();
this.setColor( _curr );
}
public void mousePressed( MouseEvent e )
{
activate( e );
}
public void mouseReleased( MouseEvent e)
{
deactivate( e );
}
public void activate( MouseEvent e )
{
_bs.setColor( Color.CYAN );
_sm.setColor( Color.BLACK );
}
public void deactivate( MouseEvent e )
{
_bs.setColor( Color.YELLOW );
}
}
您可以将更改的逻辑(无论在按钮激活上进行任何操作)移动到头像类。在阿凡达(Avatar)中声明一种称为dochange()的方法,并在子类(忍者/smokingavatar)中覆盖该方法。在"激活方法"类中,只需在Avatar实例上调用此操纵方法传递给按钮构造函数即可。您也可以遵循相同的曲折进行停用。