JLabel will not change after button click - swing

Basically, I want the text of 'lblIndividualScore' to change when the button 'btnCalculate' is clicked...but when i click it, the label doesn't change. I put a println right after it and I know that everything is being calculated correctly...it just won't change.
below is the code portions, any ideas?
Here is the action listener snippet
else if (e.getSource() == btnCalculate) {
setClassification();
setTargetOrLight();
setProneTotal();
setStandingTotal();
setKneelingTotal();
setIndividualTotal();
}
Here is what the action listener calls
public void setClassification() {
classification = (String)cmbClassification.getSelectedItem();
if (classification.equals("Senior") && target) {
txtProne2.setEditable(true);
txtKneeling2.setEditable(true);
txtStanding2.setEditable(true);
txtProne2.setVisible(true);
txtKneeling2.setVisible(true);
txtStanding2.setVisible(true);
lblStanding.setText("Standing");
lblKneeling.setText("Kneeling");
}
else if (classification.equals("Intermediate") || (classification.equals("Senior") && !target)) {
txtProne2.setEditable(false);
txtKneeling2.setEditable(false);
txtStanding2.setEditable(false);
txtProne2.setVisible(false);
txtKneeling2.setVisible(false);
txtStanding2.setVisible(false);
lblStanding.setText("Standing");
lblKneeling.setText("Kneeling");
}
else {
txtProne2.setEditable(false);
txtKneeling2.setEditable(false);
txtStanding2.setEditable(false);
txtProne2.setVisible(false);
txtKneeling2.setVisible(false);
txtStanding2.setVisible(false);
lblStanding.setText("Prone");
lblKneeling.setText("Prone");
}
}
public void setTargetOrLight() {
if (((String)cmbTarget.getSelectedItem()).equals("Target Rifle")) {
target = true;
}
else {
target = false;
}
}
public void setProneTotal() {
try {
if (classification.equals("Senior") && target) {
int prone1 = 0;
int prone2 = 0;
prone1 = Integer.parseInt(txtProne1.getText());
prone2 = Integer.parseInt(txtProne2.getText());
proneTotal = prone1 + prone2;
}
else if (classification.equals("Intermediate") || (classification.equals("Senior") && !target)) {
proneTotal = Integer.parseInt(txtProne1.getText());
}
else {
int prone1 = Integer.parseInt(txtProne1.getText());
int prone2 = Integer.parseInt(txtStanding1.getText());
int prone3 = Integer.parseInt(txtKneeling1.getText());
proneTotal = prone1 + prone2 + prone3;
}
}
catch(NumberFormatException nfe) {
System.err.println(nfe + ": You must enter a valid number - Prone");
}
}
public void setStandingTotal() {
try {
if (classification.equals("Senior") && target) {
int standing1 = 0;
int standing2 = 0;
standing1 = Integer.parseInt(txtStanding1.getText());
standing2 = Integer.parseInt(txtStanding2.getText());
standingTotal = standing1 + standing2;
}
else if (classification.equals("Intermediate") || (classification.equals("Senior") && !target)) {
standingTotal = Integer.parseInt(txtStanding1.getText());
}
else {
standingTotal = 0;
}
}
catch (NumberFormatException nfe) {
System.err.println(nfe + ": You must enter a valid number - Standing");
}
}
public void setKneelingTotal() {
try {
if (classification.equals("Senior") && target) {
int kneeling1 = 0;
int kneeling2 = 0;
kneeling1 = Integer.parseInt(txtKneeling1.getText());
kneeling2 = Integer.parseInt(txtKneeling2.getText());
kneelingTotal = kneeling1 + kneeling2;
}
else if (classification.equals("Intermediate") || (classification.equals("Senior") && !target)) {
kneelingTotal = Integer.parseInt(txtKneeling1.getText());
}
else {
kneelingTotal = 0;
}
}
catch (NumberFormatException nfe) {
System.err.println(nfe + ": You must enter a valid number - Kneeling");
}
}
public void setIndividualTotal() {
individualTotal = proneTotal + kneelingTotal + standingTotal;
lblIndividualTotal.setText("" + individualTotal);
System.err.println(individualTotal);
}
As stated above, I have that end println 'System.err.println(individualTotal);' printing the total and it DOES print so the number is getting there but the lbl isn't changing.
Please let me know if there is anything else that you need.
EDIT:
The setTexts in the setClassification() method also do not work.

Please post an SSCCE instead of long pieces of code. See below for an example SSCCE which updates the text of a JLabel when a JButton is pressed, and which works without any fancy steps. When you manage to create an SSCCE reproducing your problem, you most likely will know what causes your problem, and if not, we do not have to go through irrelevant lines of code
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChangeLabelText {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
JPanel content = new JPanel( new FlowLayout( ) );
final JLabel label = new JLabel( "Label" );
content.add( label );
JButton button = new JButton( "Change text" );
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed( ActionEvent e ) {
label.setText( "Another text" );
}
} );
content.add( button );
frame.getContentPane().add( content );
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
} );
}
}

Related

How does LibGDX FitViewport keep aspect ratio after resizing?

I am a little bit confused why my FitViewport is not keeping the aspect ratio when resizing the window.
I thought that it should always keep the aspect ratio and then fill up the screen with black bars for areas which are not used.
However for me it is not keeping the aspect ratio and circles become ellipsis f.e. (see screenshots).
Code when creating my game renderer (32 and 18 are my world units)
viewport = new FitViewport(32, 18);
camera = viewport.getCamera();
visibleArea = new Rectangle(0, 0, viewport.getScreenWidth(), viewport.getScreenHeight());
scissors = new Rectangle();
Code when resizing the window
public void resize(int width, int height) {
Gdx.app.debug(TAG, "Resizing to " + width + " x " + height);
viewport.update(width, height);
visibleArea.set(0, 0, viewport.getScreenWidth(), viewport.getScreenHeight());
Render method
public void render(float alpha) {
viewport.calculateScissors(batch.getTransformMatrix(), visibleArea, scissors);
ScissorStack.pushScissors(scissors);
viewport.apply();
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
// ...
batch.end();
ScissorStack.popScissors();
}
correct aspect ratio on startup
wrong aspect ratio on resize
Okay the problem actually was with my framebuffer light method (prepareLightFrameBuffer) which also had a call to batch.begin(); and batch.end().
It seems like this messes up the view (or resets it to something?). To solve the issue I just applied the viewport again and set the view again in the render method (Note: I also have a stage so I think that viewport.apply() has to be called here and also in the stage.render() method).
Here is the complete code of the GameRenderer if anyone is interested. I guess somehow it could be simplified but I am no OpenGL/Matrix expert so I have no idea how to do it :)
package com.lok.game;
import java.util.Comparator;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMapImageLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.lok.game.ecs.components.AnimationComponent;
import com.lok.game.ecs.components.CollisionComponent;
import com.lok.game.ecs.components.MapRevelationComponent;
import com.lok.game.ecs.components.SizeComponent;
import com.lok.game.map.Map;
import com.lok.game.map.Map.Portal;
import com.lok.game.map.MapManager;
public class GameRenderer extends OrthogonalTiledMapRenderer {
private final static String TAG = GameRenderer.class.getName();
private static class yPositionComparator implements Comparator<Entity> {
private final ComponentMapper<SizeComponent> sizeComponentMapper;
private yPositionComparator(ComponentMapper<SizeComponent> sizeComponentMapper) {
this.sizeComponentMapper = sizeComponentMapper;
}
#Override
public int compare(Entity o1, Entity o2) {
if (o1 == o2) {
return 0;
} else if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
}
return sizeComponentMapper.get(o1).boundingRectangle.y > sizeComponentMapper.get(o2).boundingRectangle.y ? -1 : 1;
}
}
private SizeComponent cameraLockEntitySizeComponent;
private MapRevelationComponent cameraLockEntityRevelationComponent;
private Map map;
private TiledMapTileLayer groundLayer;
private final Array<TiledMapTileLayer> backgroundLayers;
private final Array<TiledMapTileLayer> foregroundLayers;
private TiledMapImageLayer lightMapLayer;
private final yPositionComparator entityComparator;
private final ComponentMapper<SizeComponent> sizeComponentMapper;
private final ComponentMapper<AnimationComponent> animationComponentMapper;
private final Camera camera;
private final Viewport viewport;
private final Rectangle visibleArea;
private final Rectangle scissors;
private final ShapeRenderer shapeRenderer;
private FrameBuffer frameBuffer;
private final AtlasRegion lightTexture;
private final AtlasRegion shadowTexture;
public GameRenderer() {
super(null, MapManager.WORLD_UNITS_PER_PIXEL);
if (Gdx.app.getLogLevel() == Application.LOG_DEBUG) {
Gdx.app.debug(TAG, "Creating in debug mode");
shapeRenderer = new ShapeRenderer();
} else {
Gdx.app.debug(TAG, "Creating in non-debug mode");
shapeRenderer = null;
}
viewport = new FitViewport(32, 18);
camera = viewport.getCamera();
visibleArea = new Rectangle();
scissors = new Rectangle();
this.backgroundLayers = new Array<TiledMapTileLayer>();
this.foregroundLayers = new Array<TiledMapTileLayer>();
this.sizeComponentMapper = ComponentMapper.getFor(SizeComponent.class);
this.animationComponentMapper = ComponentMapper.getFor(AnimationComponent.class);
this.entityComparator = new yPositionComparator(sizeComponentMapper);
final TextureAtlas textureAtlas = AssetManager.getManager().getAsset("lights/lights.atlas", TextureAtlas.class);
lightTexture = textureAtlas.findRegion("light");
shadowTexture = textureAtlas.findRegion("shadow");
frameBuffer = null;
}
public void setMap(Map map) {
this.map = map;
super.setMap(map.getTiledMap());
this.backgroundLayers.clear();
this.foregroundLayers.clear();
this.lightMapLayer = null;
for (MapLayer mapLayer : map.getTiledMap().getLayers()) {
if (mapLayer instanceof TiledMapTileLayer) {
if ("ground".equals(mapLayer.getName())) {
groundLayer = (TiledMapTileLayer) mapLayer;
} else if (mapLayer.getName().startsWith("background")) {
backgroundLayers.add((TiledMapTileLayer) mapLayer);
} else {
foregroundLayers.add((TiledMapTileLayer) mapLayer);
}
} else if (mapLayer instanceof TiledMapImageLayer) {
lightMapLayer = (TiledMapImageLayer) mapLayer;
}
}
}
public void resize(int width, int height) {
Gdx.app.debug(TAG, "Resizing with " + width + "x" + height + " from viewport " + viewport.getScreenWidth() + "x" + viewport.getScreenHeight());
viewport.update(width, height, false);
visibleArea.set(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
Gdx.app.debug(TAG, "To viewport " + viewport.getScreenWidth() + "x" + viewport.getScreenHeight());
if (frameBuffer != null) {
frameBuffer.dispose();
}
try {
frameBuffer = FrameBuffer.createFrameBuffer(Pixmap.Format.RGBA8888, viewport.getScreenWidth(), viewport.getScreenHeight(), false);
} catch (GdxRuntimeException e) {
frameBuffer = FrameBuffer.createFrameBuffer(Pixmap.Format.RGB565, viewport.getScreenWidth(), viewport.getScreenHeight(), false);
}
}
public void lockCameraToEntity(Entity entity) {
if (entity == null) {
cameraLockEntitySizeComponent = null;
cameraLockEntityRevelationComponent = null;
} else {
cameraLockEntityRevelationComponent = entity.getComponent(MapRevelationComponent.class);
cameraLockEntitySizeComponent = entity.getComponent(SizeComponent.class);
if (cameraLockEntitySizeComponent == null) {
throw new GdxRuntimeException("Trying to lock camera to an entity without size component: " + entity);
}
}
}
private void interpolateEntities(float alpha) {
for (Entity entity : map.getEntities()) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
final float invAlpha = 1.0f - alpha;
sizeComp.interpolatedPosition.x = sizeComp.interpolatedPosition.x * invAlpha + sizeComp.boundingRectangle.x * alpha;
sizeComp.interpolatedPosition.y = sizeComp.interpolatedPosition.y * invAlpha + sizeComp.boundingRectangle.y * alpha;
}
}
public void render(float alpha) {
AnimatedTiledMapTile.updateAnimationBaseTime();
interpolateEntities(alpha);
map.getEntities().sort(entityComparator);
if (cameraLockEntitySizeComponent != null) {
camera.position.set(cameraLockEntitySizeComponent.interpolatedPosition, 0);
visibleArea.setCenter(cameraLockEntitySizeComponent.interpolatedPosition);
}
prepareLightFrameBuffer();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
viewport.apply();
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
viewport.calculateScissors(batch.getTransformMatrix(), visibleArea, scissors);
ScissorStack.pushScissors(scissors);
if (groundLayer != null) {
renderTileLayer(groundLayer);
}
for (Entity entity : map.getEntities()) {
renderEntityShadow(entity);
}
for (TiledMapTileLayer layer : backgroundLayers) {
renderTileLayer(layer);
}
for (Entity entity : map.getEntities()) {
renderEntity(entity);
}
for (TiledMapTileLayer layer : foregroundLayers) {
renderTileLayer(layer);
}
batch.end();
applyLightFrameBuffer();
if (Gdx.app.getLogLevel() == Application.LOG_DEBUG) {
renderDebugInformation();
}
ScissorStack.popScissors();
}
private void renderEntityShadow(Entity entity) {
final AnimationComponent animationComp = animationComponentMapper.get(entity);
if (animationComp.animation != null) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (!viewBounds.overlaps(sizeComp.boundingRectangle)) {
return;
}
if (cameraLockEntityRevelationComponent != null && !Intersector.overlaps(cameraLockEntityRevelationComponent.revelationCircle, sizeComp.boundingRectangle)) {
return;
}
batch.draw(shadowTexture, sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y - sizeComp.boundingRectangle.height * 0.2f, sizeComp.boundingRectangle.width,
sizeComp.boundingRectangle.height * 0.5f);
}
}
private void renderEntity(Entity entity) {
final AnimationComponent animationComp = animationComponentMapper.get(entity);
if (animationComp.animation != null) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (!viewBounds.overlaps(sizeComp.boundingRectangle)) {
return;
}
if (cameraLockEntityRevelationComponent != null && !Intersector.overlaps(cameraLockEntityRevelationComponent.revelationCircle, sizeComp.boundingRectangle)) {
return;
}
final TextureRegion keyFrame = animationComp.animation.getKeyFrame(animationComp.animationTime, true);
batch.draw(keyFrame, sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y, sizeComp.boundingRectangle.width, sizeComp.boundingRectangle.height);
}
}
private void prepareLightFrameBuffer() {
if (cameraLockEntityRevelationComponent != null) {
frameBuffer.begin();
final Color mapBackgroundColor = map.getBackgroundColor();
Gdx.gl.glClearColor(mapBackgroundColor.r, mapBackgroundColor.g, mapBackgroundColor.b, mapBackgroundColor.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
if (lightMapLayer != null) {
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
renderImageLayer(lightMapLayer);
}
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
final Rectangle boundingRectangle = cameraLockEntitySizeComponent.boundingRectangle;
batch.draw(lightTexture, cameraLockEntitySizeComponent.interpolatedPosition.x + boundingRectangle.width * 0.5f - cameraLockEntityRevelationComponent.revelationRadius, // x
cameraLockEntitySizeComponent.interpolatedPosition.y + boundingRectangle.height * 0.5f - cameraLockEntityRevelationComponent.revelationRadius, // y
cameraLockEntityRevelationComponent.revelationRadius * 2f, cameraLockEntityRevelationComponent.revelationRadius * 2f);
batch.end();
frameBuffer.end();
}
}
private void applyLightFrameBuffer() {
if (cameraLockEntityRevelationComponent != null) {
batch.setProjectionMatrix(batch.getProjectionMatrix().idt());
batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_COLOR);
batch.begin();
batch.draw(frameBuffer.getColorBufferTexture(), -1, 1, 2, -2);
batch.end();
}
}
private void renderDebugInformation() {
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.RED);
for (Rectangle rect : map.getCollisionAreas()) {
shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
}
for (Entity entity : map.getEntities()) {
final CollisionComponent collisionComponent = entity.getComponent(CollisionComponent.class);
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (collisionComponent != null) {
shapeRenderer.setColor(Color.RED);
shapeRenderer.rect(sizeComp.interpolatedPosition.x + collisionComponent.rectOffset.x, sizeComp.interpolatedPosition.y + collisionComponent.rectOffset.y,
collisionComponent.collisionRectangle.width, collisionComponent.collisionRectangle.height);
}
if (sizeComp != null) {
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.rect(sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y, sizeComp.boundingRectangle.width, sizeComp.boundingRectangle.height);
}
}
shapeRenderer.setColor(Color.BLUE);
for (Portal portal : map.getPortals()) {
shapeRenderer.rect(portal.getArea().x, portal.getArea().y, portal.getArea().width, portal.getArea().height);
}
if (cameraLockEntityRevelationComponent != null) {
shapeRenderer.setColor(Color.WHITE);
shapeRenderer.circle(cameraLockEntitySizeComponent.interpolatedPosition.x + cameraLockEntitySizeComponent.boundingRectangle.width * 0.5f,
cameraLockEntitySizeComponent.interpolatedPosition.y + cameraLockEntitySizeComponent.boundingRectangle.height * 0.5f,
cameraLockEntityRevelationComponent.revelationCircle.radius, 64);
}
shapeRenderer.end();
}
#Override
public void dispose() {
Gdx.app.debug(TAG, "Disposing Gamerenderer");
super.dispose();
if (shapeRenderer != null) {
shapeRenderer.dispose();
}
if (frameBuffer != null) {
frameBuffer.dispose();
}
}
}

libgdx snake logic explained

This is the code from a book I am reading. It is just a snake game. you can paste this code into editor and change 3 texture files to what you have on computer. The code works fine and this is probably really stupid, but I am unable to make the connection between snakeBody parts and their position. How exactly does the body of the snake(not the head) knows where it should go after the head of the snake changes position? Can you elaborate on this? Thank you
// class 1/2:
public class MyGdxGame extends Game {
#Override
public void create () {
setScreen(new GameScreen());
}
}
class 2/2:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.utils.Array;
public class GameScreen extends ScreenAdapter{
private static final float MOVE_TIME = 0.5F;
private static final int SNAKE_MOVEMENT = 32;
private static final int RIGHT = 0;
private static final int LEFT = 1;
private static final int UP = 2;
private static final int DOWN = 3;
private SpriteBatch batch;
private Texture snakeHead;
private Texture snakeBody;
private Texture apple;
private boolean appleAvailable = false;
private int appleX, appleY;
private float timer = MOVE_TIME;
private int snakeX = 0, snakeY = 0;
private int snakeXBeforeUpdate = 0, snakeYBeforeUpdate = 0;
private int snakeDirection = RIGHT;
private Array<BodyPart> bodyParts = new Array<BodyPart>();
#Override
public void show() {
super.show();
batch = new SpriteBatch();
snakeHead = new Texture(Gdx.files.internal("snakehead.png"));
snakeBody = new Texture(Gdx.files.internal("snakeBody.png"));
apple = new Texture(Gdx.files.internal("apple.png"));
}
#Override
public void render(float delta) {
super.render(delta);
queryInput();
timer -= delta;
if (timer <= 0) {
timer = MOVE_TIME;
moveSnake();
checkForOutOfBounds();
updateBodyPartsPosition();
}
checkAppleCollision();
checkAndPlaceApple();
clearScreen();
draw();
}
private void queryInput() {
boolean lPressed = Gdx.input.isKeyPressed(Input.Keys.LEFT);
boolean rPressed = Gdx.input.isKeyPressed(Input.Keys.RIGHT);
boolean uPressed = Gdx.input.isKeyPressed(Input.Keys.UP);
boolean dPressed = Gdx.input.isKeyPressed(Input.Keys.DOWN);
if (lPressed) snakeDirection = LEFT;
if (rPressed) snakeDirection = RIGHT;
if (uPressed) snakeDirection = UP;
if (dPressed) snakeDirection = DOWN;
}
private void moveSnake() {
snakeXBeforeUpdate = snakeX;
snakeYBeforeUpdate = snakeY;
switch (snakeDirection) {
case RIGHT: {
snakeX += SNAKE_MOVEMENT;
return;
}
case LEFT: {
snakeX -= SNAKE_MOVEMENT;
return;
}
case UP: {
snakeY += SNAKE_MOVEMENT;
return;
}
case DOWN: {
snakeY -= SNAKE_MOVEMENT;
return;
}
}
}
private void checkForOutOfBounds() {
if (snakeX >= Gdx.graphics.getWidth()) {
snakeX = 0;
}
if (snakeX < 0) {
snakeX = Gdx.graphics.getWidth() - SNAKE_MOVEMENT;
}
if (snakeY >= Gdx.graphics.getHeight()) {
snakeY = 0;
}
if (snakeY < 0) {
snakeY = Gdx.graphics.getHeight() - SNAKE_MOVEMENT;
}
}
private void updateBodyPartsPosition() {
if (bodyParts.size > 0) {
BodyPart bodyPart = bodyParts.removeIndex(0);
bodyPart.updateBodyPosition(snakeXBeforeUpdate, snakeYBeforeUpdate);
bodyParts.add(bodyPart);
}
}
private void checkAndPlaceApple() {
if (!appleAvailable) {
do {
appleX = MathUtils.random(Gdx.graphics.getWidth() / SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT;
appleY = MathUtils.random(Gdx.graphics.getHeight() / SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT;
appleAvailable = true;
} while (appleX == snakeX && appleY == snakeY);
}
}
private void checkAppleCollision() {
if (appleAvailable && appleX == snakeX && appleY == snakeY) {
BodyPart bodyPart = new BodyPart(snakeBody);
bodyPart.updateBodyPosition(snakeX, snakeY);
bodyParts.insert(0,bodyPart);
appleAvailable = false;
}
}
private void clearScreen() {
Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void draw() {
batch.begin();
batch.draw(snakeHead, snakeX, snakeY);
for (BodyPart bodyPart : bodyParts) {
bodyPart.draw(batch);
}
if (appleAvailable) {
batch.draw(apple, appleX, appleY);
}
batch.end();
}
private class BodyPart {
private int x, y;
private Texture texture;
public BodyPart(Texture texture) {
this.texture = texture;
}
public void updateBodyPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void draw(Batch batch) {
if (!(x == snakeX && y == snakeY)) batch.draw(texture, x, y);
}
}
}
First it moves the head in moveSnake(), making sure to keep track of where the head was before the move. Then in updateBodyPartsPosition() it puts the last piece of the body where the head was just moved from.

how to ViewFlipper addView or removeView after autoStart set to true

For my app, I have lots of images(from url not from phone memory) required to be shown as slideshow. I am using ViewFlipper for this. I am getting this images from url and adding them in viewFlipper. Problem is when i add 5-6 images it works fine but for more than 5-6 it goes into OutOfMemory error.
I think, this can be done if we can somehow do something like this..
1. add some set of images to ViewFlipper
2. startFlipping, remove view after showing that image/view,
3. add more images.
Not sure if it can be done using viewFlipper or are there any other way ?
Sample Code of my AutoSlideShow:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class AutoSlideShow extends Activity {
ViewFlipper viewFlipper = null;
Button pauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
viewFlipper.setFlipInterval(2000);
viewFlipper.setAutoStart(true);
for (int i = 0; i < allUrls.length; i++) {
setFlipperImage(allUrls[i]);
}
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pauseButton.getText().equals("Resume")) {
viewFlipper.startFlipping();
pauseButton.setText("Pause");
} else {
viewFlipper.stopFlipping();
pauseButton.setText("Resume");
}
}
});
}
private void setFlipperImage(String url) {
ImageView image = new ImageView(getApplicationContext());
Bitmap bitmap = null;
try {
InputStream content = (InputStream) new URL(url).getContent();
bitmap = BitmapFactory.decodeStream(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
viewFlipper.addView(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_slide_show, menu);
return true;
}
}
private ViewFlipper mViewFlipper;
private GestureDetector mGestureDetector;
int i = 0;
int k = 0;
int l = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
if (i == 0) {
for (int i = 0; i < 2; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(allUrls[i]);
mViewFlipper.addView(imageView);
k++;
}
i = 1;
}
mViewFlipper.getDisplayedChild();
// Add all the images to the ViewFlipper
CustomGestureDetector customGestureDetector = new CustomGestureDetector();
mGestureDetector = new GestureDetector(this, customGestureDetector);
mViewFlipper.setInAnimation(this, android.R.anim.fade_in);
mViewFlipper.setOutAnimation(this, android.R.anim.fade_out);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class CustomGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Swipe left (next)
if (e1.getX() > e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.left_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.left_out);
mViewFlipper.showNext();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
Log.d("Count", "" + mViewFlipper.getChildCount());
}
// Swipe right (previous)
if (e1.getX() < e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.right_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.right_out);
mViewFlipper.showPrevious();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}

File not found AS3

I am writing a program in AS3. It's exact contents don't seem to matter here. I basically have 4 classes, split in 4 files. Thing is, it can't find one of these files, and I can't understand why. I have checked it several times and even had my teacher check it, and we still can't find what is wrong with it. Did anyone else have a similar problem, or have any idea on how to solve this problem?
EDIT:
Line 37 1046: Type was not found or was not a compile-time constant: CustomTextField.
Line 37 1180: Call to a possibly undefined method CustomTextField. (Twice)
package
{
// Import stuff
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.*;
public class CustomButton extends MovieClip
{
// Private variables:
private var animationsListAR_:Array = [];// Array for the animations.
private var textArea_:CustomTextField = new CustomTextField();
private var curState_:int = 1;// The current state (1 = Normal, 2 = Pressed, 3 = Over).
private var active_:Boolean;
private var type_:String;// Multi choice, single choice, normal.
private var group_:int;
private var animated_:Boolean = false;
// Protected variables:
// Public variables:
// Constructor:
// This constructor sets up the event listeners and the button's properties.
public function CustomButton( animationAR:Array, buttonlabel:String = "Hello", animated:Boolean = false, active:Boolean = true, type:String = "free", group:int = 0 )
{
this.gotoAndStop( curState_ );
// Prevents the start of the animations.
// Deals with the text inside the button.
this.buttonMode = true;
active_ = active;
this.addChild( textArea_ );
if (animated == true)
{
animated_ = true;
/*
animationsListAR_[0] = 1;
for (var i:int = 1; i < animationAR.length; i++)
{
animationsListAR_[i] = animationAR[i - 1];
}
*/
}
// If active_ is true the game will add EventListeners to this object.
if (active_ == true)
{
this.addEventListener(MouseEvent.MOUSE_DOWN,mouseOverHandler);
this.addEventListener(MouseEvent.MOUSE_OVER,mouseOverHandler);
this.addEventListener(MouseEvent.MOUSE_OUT,mouseOutHandler);
}
// Needed to monitor the active_ var.
this.addEventListener(Event.CHANGE, activeChangeHandler);
}
// This function swaps the active_ variable value and calls activeChangeHandler.
public function ActiveChange()
{
active_ = ! active_;
this.dispatchEvent(new Event(Event.CHANGE));
}
public function mouseOverHandler( evt:MouseEvent )
{
if(evt.type == MouseEvent.MOUSE_DOWN)
{
curState_ = 2;
if (animated_ == true)
{
loopSegment( ( animationsListAR_[1] + 1 ), animationsListAR_[2] );
}
else
{
this.gotoAndStop( curState_ );
}
this.addEventListener( MouseEvent.MOUSE_UP, function( evt:MouseEvent ):void
{
evt.target.removeEventListener( MouseEvent.MOUSE_DOWN, arguments.callee );
curState_ = 3;
evt.target.gotoAndStop( curState_ );
});
}
else if( evt.buttonDown != true )
{
curState_ = 3;
if (animated_ == true)
{
loopSegment( ( animationsListAR_[2] + 1 ), animationsListAR_[3] );
}
else
{
this.gotoAndStop( curState_ );
}
}
dispatchEvent(new CustomButtonEvent(CustomButtonEvent.OVER));
}
public function mouseOutHandler(evt:MouseEvent)
{
curState_ = 1;
if (animated_ == true)
{
loopSegment( ( animationsListAR_[0] ), animationsListAR_[1] );
}
else
{
this.gotoAndStop( curState_ );
}
dispatchEvent(new CustomButtonEvent(CustomButtonEvent.OUT));
}
public function activeChangeHandler(evt:Event)
{
if (active_ == true)
{
this.addEventListener(MouseEvent.CLICK,mouseOverHandler);
this.addEventListener(MouseEvent.MOUSE_OVER,mouseOverHandler);
this.addEventListener(MouseEvent.MOUSE_OUT,mouseOutHandler);
}
else
{
this.removeEventListener(MouseEvent.CLICK,mouseOverHandler);
this.removeEventListener(MouseEvent.MOUSE_OVER,mouseOverHandler);
this.removeEventListener(MouseEvent.MOUSE_OUT,mouseOutHandler);
}
// modifyMaskButton();
}
/*
public function modifyMaskButton():void
{
if (active_ = true)
{
}
else
{
}
}
*/
public function playSegment( begin:int, end:int ):void
{
if (begin != end)
{
gotoAndPlay( begin );
addEventListener(Event.ENTER_FRAME,function( evt:Event ):void
{
if( currentFrame == end )
{
stop();
removeEventListener(Event.ENTER_FRAME, arguments.callee);
}
});
}
else
{
this.gotoAndStop( end );
}
}
// This loops continuosly an animation. Should, at least...
public function loopSegment( begin:int, end:int ):void
{
if (begin != end)
{
gotoAndPlay( begin );
addEventListener(Event.ENTER_FRAME,function( evt:Event ):void
{
if( currentFrame == end )
{
gotoAndPlay( begin );
}
});
}
else
{
this.gotoAndStop( end );
}
}
}
}
Second File:
package
{
import flash.display.MovieClip;
import flash.text.TextField;
public class CustomTextField extends MovieClip
{
private var textArea:TextField;
private var boldText:TextFormat = new TextFormat();
function CustomTextField()
{
textArea = new TextField;
}
override function CustomTextfield( labelText:String, font:String = "Arial", color:uint = 0xFFFFFFFF, size:uint = 10 )
{
textArea = new TextField;
boldText.font = font;
boldText.color = color;
boldText.size = size;
this.text = labelText;
}
function changeFont( font:String ):void
{
boldText.font = font;
updateText();
}
function changeColor( color:uint ):void
{
boldText.color = color;
updateText();
}
function changeSize( size:uint ):void
{
boldText.size = size;
updateText();
}
function embedText( choice:Boolean ):void
{
this.embedFonts = choice;
}
function updateText():void
{
this.setTextFormat( boldText );
}
}
}
Check this line in the second file:
override function CustomTextfield( labelText:String, font:String = "Arial"
"CustomTextfield" // should be "CustomTextField",within your script missing the capital letter.
I think your getting 2 errors as this function is triggered twice within script or some related change it and let us know.

Searching for instances of a string in a text area, counting the number found and printing in a text field. Java code

Here is My code for a Searcher Listener class for my main class WordSearch. This Compiles but does not get me the results I need, which is to find the number of times a string shows up in a text area. Any help would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Searcher implements ActionListener
{
private JTextField foundTextField;
private JTextArea mainTextArea;
private JTextField searchTextField;
private int count;
public Searcher(JTextField field, JTextArea main, JTextField searched)
{
this.foundTextField = field;
this.mainTextArea = main;
this.searchTextField = searched;
count = 0;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("search"))
{
count = 0;
String allOfText = mainTextArea.getText();
String searchedText = searchTextField.getText();
int firstString = allOfText.indexOf(searchedText);
boolean valid = false;
while(!valid)
{
if(firstString !=-1)
{
count+=1;
foundTextField.setText("" + count);
firstString = allOfText.indexOf(searchedText, firstString);
}
else
{
valid = true;
}
}
if(mainTextArea.getText().equals(""))
{
JOptionPane error = new JOptionPane();
error.showMessageDialog(null,"target text is empty", " target text is empty", JOptionPane.ERROR_MESSAGE);
}
else if(searchTextField.getText().equals(""))
{
JOptionPane error = new JOptionPane();
error.showMessageDialog(null,"search text is empty", "search text is empty", JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getActionCommand().equals("Reset All"))
{
mainTextArea.setText("");
foundTextField.setText("");
searchTextField.setText("");
}
else if(e.getActionCommand().equals("Reset"))
{
mainTextArea.setText("");
foundTextField.setText("");
searchTextField.setText("");
}
else if(e.getActionCommand().equals("Clear"))
{
mainTextArea.setText("");
}
}
}