Hi im trying to get a sprite to fade in and scale up after fading out and scaling down. For this i used an Entitiy modifier listener but its not working? Heres my code:
public class GameScene {
Scene gameScene;
Engine engine;
Activity activity;
BitmapTextureAtlas mTextureAtlas;
ITextureRegion X;
ITextureRegion O;
ITextureRegion XO;
FadeInModifier fadeIn = new FadeInModifier(2);
FadeOutModifier fadeOut = new FadeOutModifier(2);
ScaleModifier scaleDown = new ScaleModifier(3, 1, 0);
ScaleModifier scaleUp = new ScaleModifier(2, 0, 1);
Sprite XOsprite;
Random rand = new Random();
boolean XYset = false;
public GameScene(Engine eng, Activity act) {
engine = eng;
activity = act;
}
public Scene getScene() {
gameScene = new Scene();
gameScene.setBackground(new Background(0, 256, 59));
int x = 0, y = 0;
if (rand.nextInt(2) == 0) {
XO = X;
} else {
XO = O;
}
if (!XYset) {
x = rand.nextInt(MainActivity.CAM_WIDTH);
y = rand.nextInt(MainActivity.CAM_HEIGHT);
XYset = true;
}
XOsprite = new Sprite(x, y, XO, engine.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent te, final float xVal,
final float yVal) {
XOsprite.registerEntityModifier(fadeOut);
XOsprite.registerEntityModifier(scaleDown);
return true;
}
};
IEntityModifierListener fadeOutListener = new IEntityModifierListener() {
#Override
public void onModifierStarted(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
}
#Override
public void onModifierFinished(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
XOsprite.clearEntityModifiers();
XOsprite.setPosition(rand.nextInt(MainActivity.CAM_WIDTH), rand.nextInt(MainActivity.CAM_HEIGHT));
XOsprite.registerEntityModifier(fadeIn);
XOsprite.registerEntityModifier(scaleUp);
}
};
fadeOut.addModifierListener(fadeOutListener);
XOsprite.registerEntityModifier(scaleUp);
XOsprite.registerEntityModifier(fadeIn);
gameScene.attachChild(XOsprite);
gameScene.registerTouchArea(XOsprite);
return gameScene;
}
The sprite just fades out and nothing happens. I also want the sprite to change to a random position on the screen when it fades back in. Help?
If you want to do fade in and scale in parallel then you can use use parallelEntityModifier.
Similarly for fade out and scale out parallel then you can use use parallelEntityModifier.
To run these two in sequence use SequenceEntityModifier.
Try this it will work.
Related
i need to create a Service and a Task to calculate the Mandelbrot and JuliaSet.
The calculation is working pretty good and now we need to give it into a Service and call it inside the task.
I have now the Problem, that every Time the task is executed, the Parameters are different.
I wrote a little Setter Function to parse those Arguments to the Service first.
But i'm not sure if this is the right Way?!
I'm also not sure how to correctly call the service in the main Function?
Now it works like this:
First time the service is executed, everything seems to work, but when i call it a secound Time, nothing seems to happen.....
Just to make sure: A Service can execute the Task multiple Times at the same Time?
Is it also posible with different Parameters?
Code Task:
private MandelbrotRenderOptions mandelbrot;
private JuliaRenderOptions juliaset;
private Canvas leftCanvas;
private Canvas rightCanvas;
//Constructor
public RenderTask(Canvas leftCanvas, Canvas rightCanvas) {
this.leftCanvas = leftCanvas;
this.rightCanvas = rightCanvas;
}
public void setOptions(MandelbrotRenderOptions mandelbrot, JuliaRenderOptions juliaset) {
this.mandelbrot = mandelbrot;
this.juliaset = juliaset;
}
#Override
protected Void call() throws Exception {
try {
System.out.println("HALLO SERVICE");
// instances for rendering the left canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
// creates an writable image which contains the dimensions of the canvas
WritableImage wimLeftCanvas = new WritableImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
// instance which can write data into the image (instance above)
PixelWriter pwLeftCanvas = wimLeftCanvas.getPixelWriter();
// instance which fills the canvas
GraphicsContext gcLeftCanvas = leftCanvas.getGraphicsContext2D();
// instances for rendering the right canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
WritableImage wimRightCanvas = new WritableImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
PixelWriter pwRight = wimRightCanvas.getPixelWriter();
GraphicsContext gcRightCanvas = rightCanvas.getGraphicsContext2D();
gcLeftCanvas.clearRect(0, 0, leftCanvas.getWidth(), leftCanvas.getHeight());
//Pixel[][] pixels; // contains pixel data for rendering canvas
// instances for logging the rendered data
SimpleImage simpleImageLeftCanvas = new SimpleImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
SimpleImage simpleImageRightCanvas = new SimpleImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
short dataSimpleImage[] = new short[3]; // contains pixel data for logging rendered data
// fills left canvas (mandelbrot) PixelWriter instance with data
Pixel[][] pixels = mandelbrot.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) leftCanvas.getHeight(); y++) {
for (int x = 0; x < (int) leftCanvas.getWidth(); x++) {
// parses color data to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwLeftCanvas.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageLeftCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of mandelbrot is finished
FractalLogger.logRenderFinished(FractalType.MANDELBROT, simpleImageLeftCanvas);
// fills left canvas (juliaset) PixelWriter instance with data
pixels = juliaset.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) rightCanvas.getHeight(); y++) {
for (int x = 0; x < (int) rightCanvas.getWidth(); x++) {
// pareses color to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwRight.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageRightCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of juliaset is finished
FractalLogger.logRenderFinished(FractalType.JULIA, simpleImageRightCanvas);
// writes data from WriteableImage instance to GraphicsContext instance, which finally parses renders it into the canvas
gcLeftCanvas.drawImage(wimLeftCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.MANDELBROT);
gcRightCanvas.drawImage(wimRightCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.JULIA);
return null;
} catch (Exception e) {
System.out.println("ERROR");
System.out.println(e);
return null;
}
}
#Override
protected void cancelled()
{
super.cancelled();
updateMessage("The task was cancelled.");
}
#Override
protected void failed()
{
super.failed();
updateMessage("The task failed.");
}
#Override
public void succeeded()
{
super.succeeded();
updateMessage("The task finished successfully.");
} ```
And i call it like this in the main:
``` Service service = new Service() {
#Override
protected Task createTask() {
return new RenderTask(leftCanvas, rightCanvas);
}
};
task.setOptions(mandelbrot, juliaset);
service.restart(); ```
I have recently started up a 3d first person shooter game in Monogame and I am having some issues with the camera controls, I am unable to figure out how I make the camera slowly turn on it's X axis when I hold down the left/right arrow keys.
At the minute, the code I have is as follows:
Matrix view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(0, 0, 0), Vector3.UnitZ);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100f);
And then down in the update section I have this:
if (kb.IsKeyDown(Keys.Left))
{
view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(-2, -2, -2), Vector3.UnitZ);
}
The issue is at the minute this code simply moves the camera to the side a little then stops. I am unsure on how to keep having it move until I let go of the key?
The entire of my code will be shown below incase I forgot something (the floor verts currently don't work and the names related to a ship is due to me working from a tutorial):
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Game1
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Model model;
Vector3 ship1Location = new Vector3(40, 0, 0);
Vector3 ship2Location = new Vector3(20, 0, 0);
Matrix view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(0, 0, 0), Vector3.UnitZ);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100f);
VertexPositionTexture[] floorVerts;
BasicEffect effect;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
floorVerts = new VertexPositionTexture[6];
floorVerts[0].Position = new Vector3(-20, -20, 0);
floorVerts[1].Position = new Vector3(-20, 20, 0);
floorVerts[2].Position = new Vector3(20, -20, 0);
floorVerts[3].Position = floorVerts[1].Position;
floorVerts[4].Position = new Vector3(20, 20, 0);
floorVerts[5].Position = floorVerts[2].Position;
effect = new BasicEffect(graphics.GraphicsDevice);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
model = Content.Load<Model>("health2");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1Location);
Matrix ship2WorldMatrix = Matrix.CreateTranslation(ship2Location);
if (IsCollision(model, ship1WorldMatrix, model, ship2WorldMatrix))
{
ship1Location = new Vector3(0, -20, 0);
}
KeyboardState kb = Keyboard.GetState();
if (kb.IsKeyDown(Keys.A))
{
ship1Location += new Vector3(-0.1f, 0, 0);
}
if (kb.IsKeyDown(Keys.Left))
{
view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(-2, -2, -2), Vector3.UnitZ);
}
ship2Location += new Vector3(0, 0, 0);
base.Update(gameTime);
}
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
{
BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
sphere1 = sphere1.Transform(world1);
for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
{
BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
sphere2 = sphere2.Transform(world2);
if (sphere1.Intersects(sphere2))
return true;
}
}
return false;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
DrawGround();
Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1Location);
Matrix ship2WorldMatrix = Matrix.CreateTranslation(ship2Location);
DrawModel(model, ship1WorldMatrix, view, projection);
DrawModel(model, ship2WorldMatrix, view, projection);
base.Draw(gameTime);
}
void DrawGround()
{
// The assignment of effect.View and effect.Projection
// are nearly identical to the code in the Model drawing code.
float aspectRatio =
graphics.PreferredBackBufferWidth / (float)graphics.PreferredBackBufferHeight;
float fieldOfView = Microsoft.Xna.Framework.MathHelper.PiOver4;
float nearClipPlane = 1;
float farClipPlane = 200;
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
fieldOfView, aspectRatio, nearClipPlane, farClipPlane);
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
graphics.GraphicsDevice.DrawUserPrimitives(
// We’ll be rendering two trinalges
PrimitiveType.TriangleList,
// The array of verts that we want to render
floorVerts,
// The offset, which is 0 since we want to start
// at the beginning of the floorVerts array
0,
// The number of triangles to draw
2);
}
}
private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.AmbientLightColor = new Vector3(2f, 0, 0);
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
}
Since the camera's position and the point it is looking at are necessary parameters to create a view matrix, you can simply rotate (think orbit) the LookAt camLookAt around the camPosition like this:
//declare class scope variables
Vector3 camPosition = new Vector3(60, 20, 10);//your starting camera position
Vector3 camLookAt = Vector3.Zero;//your starting camera focus point (look at)
Vector2 camUp = Vector3.Up;
float camYawRate = 0.004f;//set to taste
//in the Update method
float elapsed = gameTime.ElapsedGameTime.TotalSeconds;
//later in the method...
if (kb.IsKeyDown(Keys.Left))
{
camLookAt = Vector3.Transform(camLookAt - camPosition,Matrix.CreateRotationY(-camYawRate * elapsedTime)) + camPosition;);//remove the - sign from camYawRate to rotate to the right (or vice versa)
view = Matrix.CreateLookAt(camPosition, camLookAt, camUp);
}
And that's it, give it a shot. Add another similar block to rotate to the right.
I want to implement in my 2d jump and run game that my player can shoot but I always get a null pointer exception.
Does anyone know why?
In this class I check for input:
public class InputIngame implements InputProcessor {
Player player;
public void handleInput(){
//control our player using immediate impulses
if (Gdx.input.isKeyJustPressed(Input.Keys.W) && PlayScreen.player.b2body.getLinearVelocity().y == 0)
PlayScreen.player.b2body.applyLinearImpulse(new Vector2(0, 6f), PlayScreen.player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.D) && PlayScreen.player.b2body.getLinearVelocity().x <= 2)
PlayScreen.player.b2body.applyLinearImpulse(new Vector2(0.2f, 0), PlayScreen.player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.A) && PlayScreen.player.b2body.getLinearVelocity().x >= -2)
PlayScreen.player.b2body.applyLinearImpulse(new Vector2(-0.2f, 0), PlayScreen.player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.D) && Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT) && PlayScreen.player.b2body.getLinearVelocity().x > 1)
PlayScreen.player.b2body.setLinearVelocity(1, PlayScreen.player.b2body.getLinearVelocity().y);
if (Gdx.input.isKeyPressed(Input.Keys.A) && Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT) && PlayScreen.player.b2body.getLinearVelocity().x < -1)
PlayScreen.player.b2body.setLinearVelocity(-1, PlayScreen.player.b2body.getLinearVelocity().y);
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE))
player = new Player();
player.fire();
}
in my screen class I draw the fireball:
#Override
public void render(float delta) {
//separate our update logic from render
update(delta);
//Clear the game screen with Black
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//render our game map
renderer.render();
if (player.isDead == true)
player.die();
player.draw(runner.batch);
//renderer our Box2DDebugLines
b2dr.render(world, gamecam.combined);
runner.batch = new SpriteBatch();
runner.batch.setProjectionMatrix(gamecam.combined);
runner.batch.begin();
player.draw(runner.batch);
runner.batch.end();
if (TimeUtils.timeSinceNanos(startTime) > 1000000000) {
startTime = TimeUtils.nanoTime();
}
Gdx.app.log("FPSLogger", "fps: " + Gdx.graphics.getFramesPerSecond());
}
In my player class I set my variables:
private PlayScreen screen;
private Array<FireBall> fireballs;
And init them:
public Player(PlayScreen screen){
//initialize default values
runner = new HardwareRunner();
this.screen = screen;
fireballs = new Array<FireBall>();
And this method is execudet in the render method:
public void update(float dt){
//update our sprite to correspond with the position of our Box2D body
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
//update sprite with the correct frame depending on marios current action
setRegion(getFrame(dt));
for(FireBall ball : fireballs) {
ball.update(dt);
}
}
And there are also these methods:
public void fire(){
fireballs.add(new FireBall(screen, b2body.getPosition().x, b2body.getPosition().y, runningRight ? true : false));
}
public void draw(Batch batch){
super.draw(batch);
for(FireBall ball : fireballs)
ball.draw(batch);
}
And then theres my fireball class:
public class FireBall extends Sprite {
PlayScreen screen;
World world;
Array<TextureRegion> frames;
Animation fireAnimation;
float stateTime;
boolean destroyed;
boolean setToDestroy;
boolean fireRight;
Body b2body;
public FireBall(PlayScreen screen, float x, float y, boolean fireRight){
this.fireRight = fireRight;
this.screen = screen;
this.world = screen.getWorld();
frames = new Array<TextureRegion>();
for(int i = 0; i < 4; i++){
frames.add(new TextureRegion(screen.getAtlas().findRegion("fireball"), i * 8, 0, 8, 8));
}
fireAnimation = new Animation(0.2f, frames);
setRegion(fireAnimation.getKeyFrame(0));
setBounds(x, y, 6 / HardwareRunner.PPM, 6 / HardwareRunner.PPM);
defineFireBall();
}
public void defineFireBall(){
BodyDef bdef = new BodyDef();
bdef.position.set(fireRight ? getX() + 12 /HardwareRunner.PPM : getX() - 12 /HardwareRunner.PPM, getY());
bdef.type = BodyDef.BodyType.DynamicBody;
if(!world.isLocked())
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(3 / HardwareRunner.PPM);
fdef.filter.categoryBits = HardwareRunner.PROJECTILE_BIT;
fdef.filter.maskBits = HardwareRunner.GROUND_BIT |
HardwareRunner.BRICK_BIT |
HardwareRunner.OBJECT_BIT;
fdef.shape = shape;
fdef.restitution = 1;
fdef.friction = 0;
b2body.createFixture(fdef).setUserData(this);
b2body.setLinearVelocity(new Vector2(fireRight ? 2 : -2, 2.5f));
}
public void update(float dt){
stateTime += dt;
setRegion(fireAnimation.getKeyFrame(stateTime, true));
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
if((stateTime > 3 || setToDestroy) && !destroyed) {
world.destroyBody(b2body);
destroyed = true;
}
if(b2body.getLinearVelocity().y > 2f)
b2body.setLinearVelocity(b2body.getLinearVelocity().x, 2f);
if((fireRight && b2body.getLinearVelocity().x < 0) || (!fireRight && b2body.getLinearVelocity().x > 0))
setToDestroy();
}
public void setToDestroy(){
setToDestroy = true;
}
public boolean isDestroyed(){
return destroyed;
}
}
But if I try to start the game I get this error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at de.tobls.hardwarerunner.Input.InputIngame.handleInput(InputIngame.java:30)
at de.tobls.hardwarerunner.Screens.PlayScreen.update(PlayScreen.java:109)
at de.tobls.hardwarerunner.Screens.PlayScreen.render(PlayScreen.java:130)
at com.badlogic.gdx.Game.render(Game.java:46)
at de.tobls.hardwarerunner.HardwareRunner.render(HardwareRunner.java:71)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
line 30 is player.fire();
line 109 is input.handleInput();
line 130 is update(delta);
and line 71 is update(delta); in my main class
I hope anyone can help me!
i think your problem is you forget brakets in "if" condition try this :
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
player = new Player();
player.fire();
}
good luck ;
if any trouble leave a comment ;)
I want to animate slide down and slide up on expandablelistview when I click the groupItem.Then I have finish the slide down.
public class ExpandAnimation extends Animation {
private static final String TAG = "ExpandAnimation";
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;
/**
* Initialize the animation
* #param view The layout we want to animate
* #param duration The duration of the animation, in ms
*/
public ExpandAnimation(View view, int duration) {
setDuration(duration);
mAnimatedView = view;
mViewLayoutParams = (LayoutParams) view.getLayoutParams();
// if the bottom margin is 0,
// then after the animation will end it'll be negative, and invisible.
mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
mMarginStart = mViewLayoutParams.bottomMargin;
Log.i(TAG, "mMarginStart:>>>>>>>"+mMarginStart);
mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
Log.i(TAG, "mMarginEnd:>>>>>>>"+mMarginEnd);
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
Log.i(TAG, "applyTransformation-->"+interpolatedTime);
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart
+ (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout();
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd;
mAnimatedView.requestLayout();
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.GONE);
}
mWasEndedAlready = true;
}
}
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Log.i(TAG, "getChildView");
#SuppressWarnings("unchecked")
String text = ((Map<String, String>) getChild(groupPosition,
childPosition)).get("child");
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child, null);
}
View toolbar = convertView.findViewById(R.id.toolbar);
setAnimationView(toolbar);
((LinearLayout.LayoutParams) toolbar.getLayoutParams()).bottomMargin = -75;
toolbar.setVisibility(View.GONE);
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 1000);
toolbar.startAnimation(expandAni);
TextView tv = (TextView) convertView.findViewById(R.id.childTo);
tv.setText(text);
return convertView;
}
But when I click the groupItem to collapse the group,it doesn't call the getChildView() method.So how can I to call the getChildView() and let it slide up?
I believe that you want to extend BaseExpandableListAdapter if you want to call (or #Override) getChildView.
http://developer.android.com/reference/android/widget/BaseExpandableListAdapter.html
I have a simple game that is in progress. As of right now all I want to do is click the green button and have the fifth and third pieces switch places. The paintComponent is called after the swap in the arraylist is made, but the JPanel is not refreshed to show these changes. When i am running my application I am choosing 4 for the pieces for each side. Thus, the inner green and black pieces should change place. Please help.
Number1.java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.Container;
public class Number1 {
private static JButton greenButton,blackButton,newGameButton,inputButton;
private static JTextFieldNumber inputField;
static MyActionListen actionListen;
static Number1 myGame;
static JFrame myDialog,myFrame;
static DrawGamePieces gamePanel;
public int piecesPerSide = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
myGame = new Number1();
actionListen = new MyActionListen();
myGame.getStartingTokensValue();
System.out.println(Color.WHITE.toString());
}
private void makeComponents()
{
//Setting up the green button click
greenButton = new JButton("Green");
greenButton.setBounds(40, 0 , 100, 40);
greenButton.setForeground(Color.GREEN);
greenButton.addActionListener(actionListen);
//Setting up the black button click
blackButton = new JButton("Black");
blackButton.setBounds(greenButton.getLocation().x + greenButton.getWidth() + 10
, 0 , 100, 40);
blackButton.setForeground(Color.BLACK);
blackButton.addActionListener(actionListen);
//Setting up the new game button click
newGameButton = new JButton("New Game");
newGameButton.setBounds(blackButton.getLocation().x + blackButton.getWidth() + 10
, 0 , 100, 40);
newGameButton.setForeground(Color.BLUE);
newGameButton.addActionListener(actionListen);
//init gamePanel
gamePanel = new DrawGamePieces(myGame.piecesPerSide,myFrame.getSize().width, myFrame.getSize().height - 40);
gamePanel.setLocation(0, 40);
gamePanel.setBackground(Color.YELLOW);
}
private void makeGameFrame()
{
myFrame = new JFrame();
if(myGame.piecesPerSide <= 10) myFrame.setSize(400, 250);
else myFrame.setSize(600, 250);
myFrame.setLocation(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
myFrame.setTitle("Solitary Game"); //sets the title of the window
Container mainFrameContents = myFrame.getContentPane();//get the content pane to add components to
mainFrameContents.setLayout(null); //allowed setBounds on components to work properly
mainFrameContents.setBackground(Color.YELLOW);
myGame.makeComponents(); //makes all the sub components
//adds all subcomponents to content pane
mainFrameContents.add(greenButton);
mainFrameContents.add(blackButton);
mainFrameContents.add(newGameButton);
mainFrameContents.add(gamePanel);
myFrame.setVisible(true);
}
//gets the starting value of the tokens for the game
private void getStartingTokensValue()
{
myDialog = new JFrame("New Game Information");
myDialog.setSize(450, 150);
myDialog.setLocation(300, 100);
myDialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
JLabel l = new JLabel("Please Enter the Number of Pieces for each side of the game (1-20)");
l.setBounds((myDialog.getSize().width - 420)/2, 0, 420, 30);
inputField = new JTextFieldNumber("0123456789");
inputField.setBounds((myDialog.getSize().width - 100)/2, 35, 100, 30);
inputButton = new JButton("Submit");
inputButton.setBounds((myDialog.getSize().width - 100)/2, 75, 100, 30);
inputButton.addActionListener(actionListen);
myDialog.setLayout(null);
myDialog.add(inputButton);
myDialog.add(l);
myDialog.add(inputField);
myDialog.setVisible(true);
}
private static class MyActionListen implements ActionListener
{
public void actionPerformed(ActionEvent ap)
{
if(ap.getSource().equals(greenButton)){
System.out.println("Requet to green move");
gamePanel.greenMove();
}else if(ap.getSource().equals(blackButton)){
System.out.println("Requet to black move");
}else if(ap.getSource().equals(newGameButton)){
System.out.println("Requet to start new game");
}else if(ap.getSource().equals(inputButton)){
if(inputField.getText().length()>0)
{
myGame.piecesPerSide = Integer.parseInt(inputField.getText());
if(inputField.checkAllCharacters() && (myGame.piecesPerSide <= 20) && (myGame.piecesPerSide>0))
{
myDialog.dispose();
myGame.makeGameFrame();
}else{
JOptionPane.showMessageDialog(inputField, "Please only type in an integer from 1 to 20");
}
}
}
}
}
}
DrawGamePieces.java
import java.awt.*;
import java.util.ArrayList;
import javax.swing.JPanel;
public class DrawGamePieces extends JPanel{
private ArrayList<GamePiece> gamePieces;
private int ballR = 15;
//paint or repaints the board
protected void paintComponent( Graphics g ){
super.paintComponent(g);
System.out.println("paint components called");
for(int i=0;i<gamePieces.size();i++)
{
GamePiece temp = gamePieces.get(i);
g.setColor(temp.getColor());
g.fillOval(temp.x,temp.y,ballR,ballR);
}
}
//init the game board
public DrawGamePieces(int piecesPerSide,int aWidth,int aHeight){
gamePieces = new ArrayList<GamePiece>();
super.setSize(aWidth, aHeight);
//space between wall and first piece
int blankSpace = (int)((aWidth - (ballR)*(2*piecesPerSide+1))/2);
//initalized the pieces in the arraylist
for(int i=0;i<(2*piecesPerSide+1);i++)
{
GamePiece temp = null;
if(i == 0) temp = new GamePiece(blankSpace,80,Color.GREEN);
if((i < piecesPerSide) && (i != 0)) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.GREEN);
if(i > piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.BLACK);
if(i == piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.YELLOW);
gamePieces.add(temp);
}
}
public void greenMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
repaint();
}
public void blackMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
}
private int pieceMoveable(Color c){
int index = -1, start = 0, end = 0,change = 0;
if(c == Color.GREEN){
start = 0;
end = gamePieces.size();
change = 1;
}else{
start = gamePieces.size();
end = 0;
change = -1;
}
for (int i=start;i<end;i= i+change){
//if(change = )
}
return index;
}
}
GamePiece.java
import java.awt.Color;
import java.awt.Point;
public class GamePiece extends Point{
private Color pieceColor;
public Color getColor(){
return pieceColor;
}
public GamePiece()
{
super();
}
public GamePiece(int x,int y,Color aColor)
{
super(x,y);
pieceColor = aColor;
}
}
Add more printfs to get more information about what is happening. Inside greenMove(), print out the contents of the ArrayList after you do the swap. Do the same inside paintComponent. In the printf, also indicate where these debugging messages are being printed from. In the loop in printComponent, print out the location and color of each piece as you draw it.