How to listen to a container that uses a Label to display images - codenameone

How to listen to a container that uses a Label to display images.
I have created a class that inherits a container and displays images in sequence within a Label component.
I want to modify the code of the class so that it loops through a list of the image name and the URL that should be executed when the container is pressed.
An alternative would be to use a button instead of the Label component and use the "setLeadComponent" method but I'm not sure how to vary the images. Also thank you tell me the command to execute the URL.
The class has the following code.
public class Imagenes extends Container {
Resources datosMundial;
public Imagenes(Resources datosMundial) {
this.datosMundial = datosMundial;
muestraImagenes();
}
private void muestraImagenes() {
Label lbInicio = new Label(datosMundial.getImage("p.png"));
lbInicio.getStyle().setAlignment(Label.CENTER);
this.addComponent(lbInicio);
while (true) {
for (int i = 0; i < 10; i++) {
Label lb = null;
lb = new Label(datosMundial.getImage("p" + i + ".png"));
lb.getStyle().setAlignment(Label.CENTER);
Component lbActual = this.getComponentAt(0);
int aleatorio = aleatorio(5);
if (aleatorio == 1) {
this.replaceAndWait(lbActual, lb, CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 5000));
}
if (aleatorio == 2) {
this.replaceAndWait(lbActual, lb, CommonTransitions.createCover(CommonTransitions.SLIDE_HORIZONTAL, true, 5000));
}
if (aleatorio == 3) {
this.replaceAndWait(lbActual, lb, CommonTransitions.createFade(5000));
}
if (aleatorio == 4) {
this.replaceAndWait(lbActual, lb, CommonTransitions.createCover(CommonTransitions.SLIDE_VERTICAL, true, 5000));
}
if (aleatorio == 5) {
this.replaceAndWait(lbActual, lb, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 5000));
}
}
}
}
private int aleatorio(int x) {
int num = 0;
Random r = new Random();
num = r.nextInt(x) + 1;
return num;
}
}

Related

WPF list modification during iteration?

I'm trying to make a very simple game where the yellow ball bouncing back and fourth. If it collides with one of the moving blue squares, the square is supposed to disappear and a new one should appear (always 3 in the window) elsewhere. When my code reaches this part, all 3 squares disappear (then reappears as intended it is not a problem) and I just cant figure out why. It would be a huge help if somebody could run over my methods responsible for the problem. Thank you in advance.
So my timer_Tick method, responsible for every frame:
void timer_Tick(object sender, EventArgs e)
{
logic.MoveBall();
if (model.Enemy.Count<3)
{
logic.AddEnemy();
}
int iii = 0;
foreach (MyShape enemy in model.Enemy) //the whole thing from here is me trying to solve list modification during iteration
{
if (logic.MoveEnemy(enemy) == -1)
{
logic.MoveEnemy(enemy);
}
else iii = logic.MoveEnemy(enemy);
}
if (iii > -1)
{
for (int j = model.Enemy.Count - 1; j >= 0; j--)
{
if (j == model.Enemy.Count - iii)
{
model.Enemy.RemoveAt(j);
}
}
}
}
MoveEnemy: I try to decide whether there is collusion and if yes, then try to remove the given shape object (blue square). Because This whole method is in a foreach, I just save the removable element and forward it to timer_Tick
public int MoveEnemy(MyShape shape)
{
int i = 0;
int ii = -1;
if ((shape.Area.IntersectsWith(model.Ball.Area)))
{
i = 0;
foreach (var e in model.Enemy)
{
i++;
if (shape == e)
{
ii = i;
}
}
}
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool coll = false;
foreach (var e in model.Enemy)
{
if ((e.Area.IntersectsWith(shape.Area)) && (shape != e))
{
coll = true;
}
}
if (shape.Area.Left < 0 || shape.Area.Right > Config.Width-40 || coll)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height/2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
return ii;
}
And finally AddEnemy:
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2+r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
List<T> (or IList and Enumerable) exposes some useful methods to compact code:
int itemIndex = list.IndexOf(item); // Gets the index of the item if found, otherwise returns -1
list.Remove(item); // Remove item if contained in collection
list.RemoveAll(item => item > 5); // Removes all items that satisfy a condition (replaces explicit iteration)
bool hasAnyMatch = list.Any(item => item > 5); // Returns true as soon as the first item satisfies the condition (replaces explicit iteration)
A simplified version, which should eliminate the flaw:
void timer_Tick(object sender, EventArgs e)
{
if (model.Enemy.Count < 3)
{
logic.AddEnemy();
}
logic.MoveBall();
model.Enemy.ForeEach(logic.MoveEnemy);
model.Enemy.RemoveAll(logic.IsCollidingWithBall);
}
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2 + r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
public bool IsCollidingWithBall(MyShape shape)
{
return shape.Area.IntersectsWith(model.Ball.Area);
}
public int MoveEnemy(MyShape shape)
{
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool hasCollision = model.Enemy.Any(enemy => enemy.Area.IntersectsWith(shape.Area)
&& enemy != shape);
if (hasCollision || shape.Area.Left < 0 || shape.Area.Right > Config.Width - 40)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height / 2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
}

dropdown error on device in codenameone

I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();

How to build a swipable intro screen?

A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.
What would be the best way to create one in Codename One - a Container with snapToGrid?
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).
public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");
private Label[] circles;
private int currentIndex = -1;
public Caroussel(int nbItems, boolean selectFirst) {
if (nbItems < 2 || nbItems > 50) {
throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
}
this.circles = new Label[nbItems];
setLayout(new BoxLayout(BoxLayout.X_AXIS));
for (int i = 0; i < nbItems; i++) {
circles[i] = new Label("", CIRCLE_EMPTY);
add(circles[i]);
}
if (selectFirst) {
select(0);
}
}
public void select(int index) {
if (index >= 0 && index <= circles.length) {
if (currentIndex > -1) {
circles[currentIndex].setIcon(CIRCLE_EMPTY);
}
circles[index].setIcon(CIRCLE);
currentIndex = index;
repaint();
}
}
public void selectNext() {
if (currentIndex <= circles.length) {
select(currentIndex + 1);
}
}
public void selectPrevious() {
if (currentIndex >= 1) {
select(currentIndex - 1);
}
}}
And
public class TutoDialog extends Dialog {
private Caroussel caroussel = null;
public TutoDialog(String title, Image... images) {
if (images == null) {
return;
}
this.caroussel = new Caroussel(images.length, true);
setTitle(title);
setAutoAdjustDialogSize(true);
getTitleComponent().setUIID("DialogTitle2");
setBlurBackgroundRadius(8.5f);
Tabs tabs = new Tabs();
tabs.setSwipeActivated(false);
tabs.setAnimateTabSelection(false);
int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
for (Image img : images) {
tabs.addTab("", new Label("", img.scaled(px1, px2)));
}
Container cButtons = new Container(new BorderLayout());
Button bSuivant = new Button("button.suivant");
Button bPrecedent = new Button("button.precedent");
Button bTerminer = new Button("button.terminer");
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
if (currentInd == 0) {
bPrecedent.setVisible(true);
}
if (currentInd + 1 <= tabs.getTabCount() - 1) {
if (caroussel != null)
caroussel.selectNext();
tabs.setSelectedIndex(currentInd + 1);
if (currentInd + 1 == tabs.getTabCount() - 1) {
bTerminer.setVisible(true);
bSuivant.setVisible(false);
cButtons.revalidate();
}
}
};
});
bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
tabs.setSelectedIndex(currentInd - 1);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.selectPrevious();
if (currentInd - 1 == 0) {
bPrecedent.setVisible(false);
cButtons.revalidate();
}
};
});
bTerminer.addActionListener(new ActionListener<ActionEvent>() {
#Override
public void actionPerformed(ActionEvent evt) {
tabs.setSelectedIndex(0);
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.select(0);
TutoDialog.this.dispose();
}
});
cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}
public static void showIfFirstTime(AbstractComponentController ctrl) {
if (ctrl == null) {
Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
return;
}
String key = getKey(ctrl);
if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
Preferences.set(key, true);
ctrl.getTutoDlg().show();
}
});
}
}
public static String getKey(AbstractComponentController ctrl) {
String key = "tuto" + ctrl.getClass().getSimpleName();
if (UserController.getCurrentUser() != null) {
key += "-" + UserController.getCurrentUser().getId();
}
return key;
}
public static boolean isAlreadyShown(AbstractComponentController ctrl) {
return Preferences.get(getKey(ctrl), false);
}
}
It's look like this :
OK - so that is my first attempt and I am pretty content with that:
private void showIntro() {
Display display = Display.getInstance();
int percentage = 60;
int snapWidth = display.getDisplayWidth() * percentage / 100;
int snapHeight = display.getDisplayHeight() * percentage / 100;
Dialog dialog = new Dialog(new LayeredLayout()) {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Tabs tabs = new Tabs();
tabs.setTensileLength(0);
tabs.hideTabs();
int[] colors = {
0xc00000,
0x00c000,
0x0000c0,
0x909000,
0x009090,
};
for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
Container containerElement = new Container() {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Style style = containerElement.getAllStyles();
style.setBgTransparency(0xff);
style.setBgColor(colors[colorIndex]);
tabs.addTab("tab" + tabs.getTabCount(), containerElement);
}
int tabCount = tabs.getTabCount();
Button[] buttons = new Button[tabCount];
Style styleButton = UIManager.getInstance().getComponentStyle("Button");
styleButton.setFgColor(0xffffff);
Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
buttons[tabIndex] = new Button(imageDot);
buttons[tabIndex].setUIID("Container");
final int tabIndexFinal = tabIndex;
buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
}
Container containerButtons = FlowLayout.encloseCenter(buttons);
dialog.add(tabs);
Button buttonWest = new Button("Skip");
buttonWest.setUIID("Container");
buttonWest.getAllStyles().setFgColor(0xffffff);
buttonWest.addActionListener(aActionEvent -> dialog.dispose());
Button buttonEast = new Button(">");
buttonEast.setUIID("Container");
buttonEast.getAllStyles().setFgColor(0xffffff);
buttonEast.addActionListener(aActionEvent -> {
int selectedIndex = tabs.getSelectedIndex();
if (selectedIndex < (tabs.getTabCount() - 1)) {
tabs.setSelectedIndex(selectedIndex + 1, true);
} else {
dialog.dispose();
}
});
Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
Style styleContainerSouth = containerSouth.getAllStyles();
styleContainerSouth.setMarginUnit(
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS);
styleContainerSouth.setMargin(2, 2, 2, 2);
dialog.add(containerSouth);
SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
if (buttonIndex == aNewSelectionIndex) {
buttons[buttonIndex].getAllStyles().setOpacity(0xff);
} else {
buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
}
}
buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
buttonEast.getParent().animateLayout(400);
};
tabs.addSelectionListener(selectionListener);
dialog.addShowListener(evt -> {
buttonEast.getParent().layoutContainer();
selectionListener.selectionChanged(-1, 0);
});
Command command = dialog.showPacked(BorderLayout.CENTER, true);
}

Image Viewer auto slide codenamone

How can i auto slide the imageViewer for instance in the interval of 3 seconds.
Or is there any other component that can do the auto swipe task.
ImageViewer imv = new ImageViewer();
DefaultListModel<Image> images = new DefaultListModel<Image>(new Image[]{a, thumbnail1, thumbnail2});
imv.setImage(images.getItemAt(0));
imv.setImageList(images);
imv.setSwipePlaceholder(Image.createImage(100, 100));
Declare this global static variable:
private static int slideIndex = 0;
//And this UITimer
UITimer t;
And then try out below code
final ImageViewer imv = new ImageViewer();
final DefaultListModel<Image> images = new DefaultListModel<Image>(new Image[]{a, thumbnail1, thumbnail2});
imv.setImage(images.getItemAt(0));
imv.setImageList(images);
imv.setSwipePlaceholder(Image.createImage(100, 100));
Runnable r = new Runnable() {
public void run() {
if (slideIndex < images.getSize()) {
slideIndex++;
} else {
slideIndex = 0;
}
Image nextImage = (Image) images.getItemAt(slideIndex);
if (nextImage != null) {
imv.setImage(nextImage);
}
}
};
if (t == null) {
t = new UITimer(r);
}
if (t != null) {
t.schedule(3000, true, f); //3 seconds
}

How do i remove the milliseconds from my timer

I am making this game for school and I am trying to add a timer to levels. I have the timer working but not the way I want it to. It refreshes and it has milliseconds. I have searched every website for an answer but I can only find with dates and times or how do display them. I need the exact opposite.
package GameState;
import Main.GamePanel;
import TileMap.*;
import Entity.*;
import Entity.Enemies.*;
import Audio.AudioPlayer;
//timer imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Level1State extends GameState {
private TileMap tileMap;
private Background bg;
private static int cnt;
private Player player;
private ArrayList<Enemy> enemies;
private ArrayList<Explosion> explosions;
private HUD hud;
private AudioPlayer bgMusic;
public Level1State(GameStateManager gsm) {
this.gsm = gsm;
init();
}
public void init() {
tileMap = new TileMap(30);
tileMap.loadTiles("/Tilesets/grasstileset.gif");
tileMap.loadMap("/Maps/level1-1.map");
tileMap.setPosition(0, 0);
tileMap.setTween(1);
bg = new Background("/Backgrounds/grassbg1.2.jpg", 0.1);
player = new Player(tileMap);
player.setPosition(100, 100);
populateEnemies();
explosions = new ArrayList<Explosion>();
hud = new HUD(player);
bgMusic = new AudioPlayer("/Music/level1-1.mp3");
bgMusic.play();
}
private void populateEnemies() {
enemies = new ArrayList<Enemy>();
Slugger s;
Point[] points = new Point[] {
new Point(200, 100),
new Point(860, 200),
new Point(1525, 200),
new Point(1680, 200),
new Point(1800, 200)
};
for(int i = 0; i < points.length; i++) {
s = new Slugger(tileMap);
s.setPosition(points[i].x, points[i].y);
enemies.add(s);
}
}
public void update() {
// update player
player.update();
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety()
);
// set background
bg.setPosition(tileMap.getx(), tileMap.gety());
// attack enemies
player.checkAttack(enemies);
// update all enemies
for(int i = 0; i < enemies.size(); i++) {
Enemy e = enemies.get(i);
e.update();
if(e.isDead()) {
enemies.remove(i);
i--;
explosions.add(
new Explosion(e.getx(), e.gety()));
}
}
// update explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).update();
if(explosions.get(i).shouldRemove()) {
explosions.remove(i);
i--;
}
}
}
public void draw(final Graphics2D g) {
// draw bg
bg.draw(g);
// draw tilemap
tileMap.draw(g);
// draw player
player.draw(g);
// draw enemies
for(int i = 0; i < enemies.size(); i++) {
enemies.get(i).draw(g);
}
// draw explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).setMapPosition(
(int)tileMap.getx(), (int)tileMap.gety());
explosions.get(i).draw(g);
}
// draw hud
hud.draw(g);
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
}
public void keyPressed(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(true);
if(k == KeyEvent.VK_RIGHT) player.setRight(true);
if(k == KeyEvent.VK_UP) player.setUp(true);
if(k == KeyEvent.VK_DOWN) player.setDown(true);
if(k == KeyEvent.VK_W) player.setJumping(true);
if(k == KeyEvent.VK_E) player.setGliding(true);
if(k == KeyEvent.VK_R) player.setScratching();
if(k == KeyEvent.VK_F) player.setFiring();
}
public void keyReleased(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(false);
if(k == KeyEvent.VK_RIGHT) player.setRight(false);
if(k == KeyEvent.VK_UP) player.setUp(false);
if(k == KeyEvent.VK_DOWN) player.setDown(false);
if(k == KeyEvent.VK_W) player.setJumping(false);
if(k == KeyEvent.VK_E) player.setGliding(false);
}
}
this is the part i need help with:
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
Can anyone help me? I just can't get it to stop refreshing and it won't remove the milliseconds either.
Thank you in advance
P.S.
I have a feeling the first second runs way slower than the others.
P.P.S.: i have looked at "how to implement timers" but none of those worked and I found this one on a website that doesn't return an error.

Resources