Exception in Application Cunstructor - exception

I want to write a code with javaFX (Snake game) but right now it's not complete yet because it doesn't consider game Over yet. I wrote this and it is not object oriented. When I sort it and try to make it object oriented, (exactly with last code that run correctly) it throws Exception in Application constructor.
the exception is :
Exception in Application constructor
Exception in thread "main" java.lang.NoSuchMethodException: Main_Snake.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1819)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
Someone said me to add :
public static void main(String[] args) {
launch(args);
}
After adding that, I get a new Exception:
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class Main_Snake
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:910)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(LauncherImpl.java:187)
at java.lang.Thread.run(Thread.java:747)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:426)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:822)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.StackOverflowError
at javafx.scene.Node.setTreeVisible(Node.java:8028)
at javafx.scene.Node.updateTreeVisible(Node.java:8021)
at javafx.scene.Node.<init>(Node.java:2372)
at javafx.scene.canvas.Canvas.<init>(Canvas.java:100)
at Main_Snake.<init>(Main_Snake.java:30)
at Snake.<init>(Main_Snake.java:164)
Can someone check my code please?
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Nadia on 1/5/2016.
*/
public class Main_Snake extends Application{
Canvas canvas = new Canvas(800, 600);
boolean goNorth = true, goSouth, goWest, goEast;
int x, y = 0; // marbut be apple
boolean j = false;
// int gm_ov = 0; // vase game over shodan
ArrayList<Integer> X = new ArrayList<Integer>();
ArrayList<Integer> Y = new ArrayList<>();
Snake snake = new Snake();
Apple apple = new Apple();
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane b = new BorderPane(canvas);
Scene scene = new Scene(b, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
//KeyBoard(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getText()) {
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
play(snake,apple);
}
public void play(Snake snake , Apple apple) {
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 40_000_000) { // payin avordane sor#
snake.pos_S(); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
apple.pos_A();
apple.random_Pos();
snake.Move(apple);
lastUpdate = now; // sor#
}
}
};
timer.start();
}
/* public void KeyBoard(Scene scene) {
}*/
}
class Apple extends Main_Snake {
public void random_Pos() {
if (j == false) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) (Math.random() * 790 + 1);
y = (int) (Math.random() * 590 + 1);
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*
inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide
*/
j = true;
}
}
public void pos_A() {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(x, y, 10, 10);
}
public void Point() {
if (X.get(0) == x && Y.get(0) == y) {
j = false;
}
}
}
class Snake extends Main_Snake {
Snake(){ //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
}
public void pos_S(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
gc.setFill(Color.BLACK);
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--)
gc.fillRect(X.get(i), Y.get(i), 10, 10);
}
public void Move(Apple apple){
int Px = X.get(X.size() - 1);
int Py = Y.get(Y.size() - 1);
for (int z = X.size() - 1 ; z > 0 ; z--){
X.remove(z);
X.add(z , X.get(z-1) ) ;
Y.remove(z);
Y.add(z , Y.get(z-1) ) ;
}
if (goNorth) {
Y.add(0 , Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0 , Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0 , X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0 , X.get(0) - 10);
X.remove(1);
}
apple.Point(); // emtiaz gerefte
if ( j == false) {
X.add(Px);
Y.add(Py);
}
if ( X.get(0) > 790 ){
X.remove(0);
X.add(0 , 0);
}
if ( X.get(0) < 0 ){
X.remove(0);
X.add(0 , 800);
}
if ( Y.get(0) > 590 ){
Y.remove(0);
Y.add(0 , 0);
}
if ( Y.get(0) < 0 ){
Y.remove(0);
Y.add(0 , 600);
}
}
}

When you start the application, it creates an instance of Main_Snake (since that is the Application class.
Your Main_Snake class has a field (instance variable) called snake of type Snake, which is initialized inline to a new Snake instance:
public class Main_Snake extends Application {
Snake snake = new Snake();
// ...
}
Your Snake class is a subclass of Main_Snake (why?):
public class Snake extends Main_Snake { ... }
This means it inherits all the fields and methods of Main_Snake. So when you create a new Snake instance, it initializes all the fields defined in Snake, as well as all the fields inherited from Main_Snake. In particular, it creates a new object called snake of type Snake (since that field is defined in the superclassMain_Snake).
So, so far we have:
JavaFX creates a Main_Snake at startup. As part of the process of creating Main_Snake, a Snake is created (since Main_Snake has a Snake).
As part of the process of creating a Snake, a new Snake is created (the one Snake inherits from Main_Snake).
As part of the process of creating that Snake object (which, remember inherits from Main_Snake), a new Snake is created.
As part of the process of creating that Snake object (which, remember inherits from Main_Snake), a new Snake is created.
And I think by now you start to see the problem...
I can't really tell you how to fix this, as I have no real idea why you want Snake to be a subclass of Main_Snake. But you can't both have Main_Snake initializing a new Snake, and Snake a subclass of Main_Snake.

Related

Libgdx clickable object?

Can someone explain me how to detect a click on an object? I have already seen an answer to this question but it does not work.
public class TiledMapActor extends Actor {
private TiledMap tiledMap;
private TiledMapTileLayer tiledLayer;
private TiledMapTileLayer.Cell cell;
public TiledMapActor(TiledMap tiledMap, TiledMapTileLayer tiledLayer, TiledMapTileLayer.Cell cell) {
this.tiledMap = tiledMap;
this.tiledLayer = tiledLayer;
this.cell = cell;
}
}
public class TiledMapClickListener extends ClickListener {
private TiledMapActor actor;
public TiledMapClickListener(TiledMapActor actor) {
this.actor = actor;
}
#Override
public void clicked(InputEvent event, float x, float y) {
System.out.println(actor.cell + " has been clicked.");
}
}
public class TiledMapStage extends Stage {
private TiledMap tiledMap;
public TiledMapStage(TiledMap tiledMap) {
this.tiledMap = tiledMap;
for (MapLayer layer : tiledMap.getLayers()) {
TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer; //THE ERROR IS IN THIS LINE
createActorsForLayer(tiledLayer);
}
}
private void createActorsForLayer(TiledMapTileLayer tiledLayer) {
for (int x = 0; x < tiledLayer.getWidth(); x++) {
for (int y = 0; y < tiledLayer.getHeight(); y++) {
TiledMapTileLayer.Cell cell = tiledLayer.getCell(x, y);
TiledMapActor actor = new TiledMapActor(tiledMap, tiledLayer, cell);
actor.setBounds(x * tiledLayer.getTileWidth(), y * tiledLayer.getTileHeight(), tiledLayer.getTileWidth(),
tiledLayer.getTileHeight());
addActor(actor);
EventListener eventListener = new TiledMapClickListener(actor);
actor.addListener(eventListener);
}
}
}
}
Stage stage = new TiledMapStage(tiledMap);
Gdx.input.setInputProcessor(stage);
I have tried it with this code but I get this error message:
com.badlogic.gdx.maps.MapLayer cannot be cast to com.badlogic.gdx.maps.tiled.TiledMapTileLayer
I do not understand how select which object is clickable
As you already found out, the problem is your casting here:
for (MapLayer layer : tiledMap.getLayers()) {
TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;
Looks like the layers are not of type TiledMapTileLayer - or at least not all of them. (Afaik there are also ObjectLayers in a TiledMap) The simplest thing to get your code running again would ab an instanceof check:
for (MapLayer layer : tiledMap.getLayers()) {
if (layer instanceof TiledMapTileLayer) {
TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;
createActorsForLayer(tiledLayer);
}

Add custom wms layer to codename one Mapcontainer

I am building an android GPS app with Codename one. I use com.codename1.googlemaps.MapContainer to create a Google map;
In my app is use tabs to create different "pages".
Code:
cnt = new MapContainer();
t.addTab("Tab3", cnt);
And for my current location I use:
try {
Coord position = new Coord(lat,lng);
cnt.clearMapLayers();
cnt.setCameraPosition(position);
cnt.addMarker(EncodedImage.create("/maps-pin.png"), position, "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// stuff todo...
}
});
} catch(IOException err) {
// since the image is iin the jar this is unlikely
err.printStackTrace();
}
I like to add a wms layer to the Google Maps. Is this possible? I can't find in codenameone a command addLayer. If yes, do you have a code snippet how to do this?
If it is not possiple, can I use openlayers in my codename one app? Can you give me a code snippet to do this?
Edit
I started to create an native file to "catch"the addtileoverlay from google maps api. The layer I want to use is a xyz layer, so I think I can use a urltileprovider from the googlemap api
I made the native code for the tileoverlay but the tileoverlay doesn't appear. Is it because i didn't get a link with the mapcontainer.
I am little bit stuck. I tried to build from scratch with the googmaps example but the mapcompnent is not anymore used.
package com.Bellproductions.TalkingGps;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.TileOverlay;
import com.codename1.impl.android.AndroidNativeUtil;
import java.util.Locale;
import java.net.MalformedURLException;
public class SeamarksImpl {
private GoogleMap mapInstance;
private TileOverlay m;
TileProvider provider;
public boolean isSupported() {
return true;
}
public long addTilelayer (){
final String URL_FORMAT = "http://t1.openseamap.org/seamark/{z}/{x}/{y}.png";
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
provider = new UrlTileProvider(256, 256) {
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
try {
y = (1 << zoom) - y - 1;
return new URL(String.format(Locale.US, URL_FORMAT, zoom, x, y ));
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}
TileOverlayOptions tileopt = new TileOverlayOptions().tileProvider(provider);
public void addlayer() {
m = mapInstance.addTileOverlay(tileopt);
}
};
}
});
long p = 1;
return p;}
}
My seamarks.java file has this code to bind with the native interface
import com.codename1.system.NativeInterface;
/**
*
* #author Hongerige Wolf
*/
public interface Seamarks extends NativeInterface {
public void addTilelayer ();
}
In the mainactivity java file i have the statements
public Seamarks seamark;
public void init(Object context) {
seamark = (Seamarks)NativeLookup.create(Seamarks.class);
}
public void start() {
seamark.addTilelayer();
}
Update
I created a new googlemaps.CN1lib. But the xyz layer is not showing on the googlemaps. I used native code tot use the Tileoverlay feature and tried to add tileoverlay in the same way as Markers.
In the InternalNativeMapsImpl file i changed
private void installListeners() {
/*
if (mapInstance == null) {
view = null;
System.out.println("Failed to get map instance, it seems google play services are not installed");
return;
}*/
view.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mapInstance = googleMap;
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
String tileLayer= "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
//String s = String.format(Locale.US, tileLayer , zoom, x, y);
String s = tileLayer + "/" + zoom + "/" + x + "/" + reversedY + ".png";
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
mapInstance.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
Long val = listeners.get(marker);
if (val != null) {
MapContainer.fireMarkerEvent(InternalNativeMapsImpl.this.mapId, val.longValue());
return true;
}
return false;
}
});
mapInstance.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
MapContainer.fireMapChangeEvent(InternalNativeMapsImpl.this.mapId, (int) position.zoom, position.target.latitude, position.target.longitude);
}
});
mapInstance.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireTapEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireLongPressEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setMyLocationEnabled(showMyLocation);
mapInstance.getUiSettings().setRotateGesturesEnabled(rotateGestureEnabled);
}
});
}
Secondly i added a addTilexyz method also in the same way as addMarkers
public long addTilexyz(final String Turl) {
uniqueIdCounter++;
final long key = uniqueIdCounter;
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
// Tileurl = "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, Turl , zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
});
return key;
}
In the InternalNativeMaps file i added te method
public long addTilexyz(String Turl);
And in the Mapcontainer file i added
public MapObject addTilexyz(String Turl) {
if(internalNative != null) {
MapObject o = new MapObject();
Long key = internalNative.addTilexyz(Turl);
o.mapKey = key;
markers.add(o);
return o;
} else {
}
MapObject o = new MapObject();
return o;
}
I am puzzeled what is wrong with the code. I wonder if the commands
Long key = internalNative.addTilexyz(Turl);
and
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
put the tileoverlay on the googlemap. Or is the tileurl wrong. http://t1.openseamap.org/seamark/z/x/y.png is correct.
We don't expose layers in the native maps at this time, you can fork the project and just add an API to support that to the native implementations.

Libgdx On Collision error

I have tried to set up my own class for handling collisions but it just seems to output the error below. The program opens fine it only outputs the error when the ball and spike collide. Thanks
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.alexcz.mariobros.Tiles.HandleCollisions.ballSpike(HandleCollisions.java:20)
at com.alexcz.mariobros.Tools.WorldContactListener.beginContact(WorldContactListener.java:41)
at com.badlogic.gdx.physics.box2d.World.beginContact(World.java:982)
public class HandleCollisions {
Character player;
World world;
public HandleCollisions(Character player, World world) {
this.player = player;
this.world = world;
}
public void ballSpike(){
player.hitSpike();
System.out.println("collided");
}
}
public class WorldContactListener implements ContactListener {
public World world;
public Character player;
public HandleCollisions handleCollisions;
public WorldContactListener(Character player,World world) {
world = this.world;
player = this.player;
handleCollisions = new HandleCollisions(player, world);
}
#Override
public void beginContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
if(fixtureA.getUserData() == "ball" || fixtureB.getUserData() == "ball"){
Fixture ball = fixtureA.getUserData() == "head" ? fixtureA : fixtureB;
Fixture object = ball == fixtureA ? fixtureB : fixtureA;
if(object.getUserData() instanceof InteractiveTileObject)
{
((InteractiveTileObject)object.getUserData()).hit();
handleCollisions.ballSpike();
}
}
}
Here's your issue:
world = this.world; // this.world is null
player = this.player; // this.player is null
should be:
this.world = world;
this.player = player;
since this is your instance, that's how you would assign your class variables.
I'd guess that this is why your handleCollisions is null, and throwing a java.lang.NullPointerException when it executes handleCollisions.ballSpike().
Here's where a debug inspector comes in handy.

calling a Timer from inside an ActionListener in Java

I have created a (2nd) Timer in Java but rather than adding the arguements (int, action) when creating the Timer, I am trying to initialize the Timer inside an actionlistener.
The reason is that the int [in the timers arguement] is created within the actionlistener.
When i do this though, the Timer cant be found.
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;
public class mainGui extends JFrame {
public mainGui()
{
final ActionListener timerActionEvent = new ActionListener() {
public void actionPerformed( ActionEvent evt ) {
//Start a task here
Timer myTimer2 = (Timer)evt.getSource();
//myTimer2.stop();
BluetoothScan( myTimer2 );
}
};
final ActionListener timerDurationActionEvent = new ActionListener() {
public void actionPerformed( ActionEvent evt ) {
//Create a method to stop both timers at the bottom of this class
Timer myTimer3 = (Timer)evt.getSource();
StopTimers( myTimer3 );
}
};
final Timer timerDuration;
final Timer myTimer = new Timer( 5000, timerActionEvent );
/*
* Start All ActionListeners // ItemListeners
*/
ActionListener btnScanAction = new ActionListener() {
//Action listener for reading data from db
public void actionPerformed( ActionEvent e ) {
int roomID = 0;
int lecturer = 0;
int unit;
int roomIDIndex;
int lectIDIndex;
int yearIDIndex;
int unitIDIndex;
String[] roomArray;
String[] lecturerArray;
String[] unitArray = null;
int durationIndex;
String DURATION;
int durationInt;
//System.out.println(unitArray.length);
durationIndex = durCB.getSelectedIndex();
DURATION = itemDuration[durationIndex];
durationInt = Integer.parseInt( DURATION );
//User Selected Duration converted to Milliseconds
int durationMilliSec = (int)(durationInt * 60000);
ArrayList<String[]> unitYear = null;
//Store the index ID of the JComboBox Selections
roomIDIndex = roomCB.getSelectedIndex();
lectIDIndex = lectCB.getSelectedIndex();
unitIDIndex = unitCB.getSelectedIndex();
yearIDIndex = yearCB.getSelectedIndex();
switch( yearIDIndex )
{
case 1:
unitYear = Units1;
break;
case 2:
unitYear = Units2;
break;
case 3:
unitYear = Units3;
break;
case 4:
unitYear = UnitsMasters;
break;
}
//Get the Array contents at index location
roomArray = rooms.get( roomIDIndex );
lecturerArray = Lecturers.get( lectIDIndex );
unitArray = unitYear.get( unitIDIndex );
if( unitArray == null ) {
System.out.println( "Please select a unit" );
System.exit( 0 );
}
roomID = Integer.parseInt( roomArray[0] );
lecturer = Integer.parseInt( lecturerArray[0] );
unit = Integer.parseInt( unitArray[0] );
populateComboBoxes pcb = new populateComboBoxes();
pcb.LabSessionInfo( roomID, lecturer, unit );
myTimer.start();
//HERE IS MY PROBLEM
timerDuration( durationMilliSec, timerDurationActionEvent ).start();
}
};
}
public void BluetoothScan( Timer myTimer ) {
BluetoothDeviceDiscovery scan = new BluetoothDeviceDiscovery();
try {
myTimer.stop();
scan.main();
} catch( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myTimer.start();
};
public void StopTimers( Timer timerDuration ) {
timerDuration.stop();
//myTimer.stop();
}
}
The problem lies at the bottom of the btnScanAction ActionListener when creating the Timer timerDuration(durationMilliSec, timerDurationActionEvent).start();
its a problem with not being able to see the created Timer from within the ActionListener. Does anyone know of a possible way round this, still keeping the timerDuration(durationMilliSec, timerDurationActionEvent).start(); In the ActionListener??
Thanks a lot guys
timerDuration(durationMilliSec, timerDurationActionEvent).start();
Doesn't make any sence here. Java expects method call here.
If you want to start new Timer() here, then write
Timer timer = new TimerTask() {
// code here
}.start();

ActionScript compilation error: The name of definition 'Main' does not reflect the location of this file

Can someone tell me what I am doing wrong with this?
I have a movie clip called turret that is on the screen and is instanced as Turret,
I have a movie clip called bullet and that is in the library exported for AS "bullet" no quotes.
Here is the website http://wonderfl.net/c/du34
My frame (main) class is called du34
My code for du34 is:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
[SWF(width=1000, height=1000, framerate=24)]
public class Main extends Sprite
{
private static const SCREEN_WIDTH: int = 1000
private static const SCREEN_HEIGHT: int = 1000
private var turret: Turret = null
private var me: MouseEvent = null
private var trigger: Boolean = false
private var bullets: Array = []
public function Main():void
{
graphics.beginFill(0x0)
graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
graphics.endFill()
turret = new Turret(SCREEN_WIDTH / 2, SCREEN_HEIGHT)
turret.addEventListener(Turret.ADD_BULLET, onAddBullet)
addChild(turret)
addEventListener(Event.ENTER_FRAME, onEnterFrame)
stage.addEventListener(MouseEvent.MOUSE_DOWN, function(): void { trigger = true } )
stage.addEventListener(MouseEvent.MOUSE_UP, function(): void { trigger = false } )
}
private var nextAddBullet: Bullet = null;
private function onAddBullet(e: BulletEvent): void {
nextAddBullet = new Bullet(turret.x + e.pos, turret.y, mouseX, mouseY)
}
private var frameProcessing: Boolean = false
private function onEnterFrame(e: Event): void {
if (frameProcessing) return
frameProcessing = true
if (null != nextAddBullet) {
bullets.push(nextAddBullet)
addChild(nextAddBullet)
nextAddBullet = null
}
turret.frameAction(trigger)
var i: int
for (i = 0; i < bullets.length; i++) {
var bullet: Bullet = bullets[i]
if (null != bullet) {
if (bullet.frameAction()) {
removeChild(bullet)
bullets[i] = null
}
}
}
i = bullets.length
while (0 < i--) {
if (null == bullets[i]) bullets.splice(i, 1)
}
frameProcessing = false
}
}
}
import flash.events.Event
import flash.display.Sprite
import flash.geom.Point
class BulletEvent extends Event {
private var _pos: int = 0
public function get pos(): int { return _pos }
public function BulletEvent(type:String, pos: int, bubbles:Boolean = false, cancelable:Boolean = false) {
super(type, bubbles, cancelable);
_pos = pos;
}
}
// 弾丸
class Bullet extends Sprite {
private var t: Point
private var d: Point
private static const BULLET_SIZE: int = 3
public function Bullet(_x: int, _y: int, _tx: int, _ty: int): void {
graphics.beginFill(0xFFFFFF)
graphics.drawEllipse(-BULLET_SIZE/2, -BULLET_SIZE/2, BULLET_SIZE, BULLET_SIZE)
graphics.endFill()
x = _x
y = _y
t = new Point(_tx, _ty)
d = t.subtract(new Point(x, y))
d.normalize(10)
frameAction()
}
public function frameAction(): Boolean {
x += d.x
y += d.y
var cx: Boolean = (0 <= d.x) ? t.x <= x : x <= t.x;
var cy: Boolean = (0 <= d.y) ? t.y <= y : y <= t.y;
return (cx && cy)
}
}
// 砲身
class Barrel extends Sprite {
private static const BARREL_LENGTH: int = 20
private var _pos: int = 0
private var _loading: int = 0
public function get pos(): int { return _pos }
public function loading(): Boolean { return 0 < _loading }
public function Barrel(pos: int = 0) { _pos = pos }
public function frameAction(): void {
if (0 < _loading) _loading -= 2
var d: Point = new Point(mouseX, mouseY)
d.normalize(BARREL_LENGTH - _loading)
graphics.clear()
graphics.lineStyle(2, 0xc0c0c0)
graphics.moveTo(_pos, 0)
graphics.lineTo(d.x + _pos, d.y)
}
public function shot(): void {
_loading = 8
}
}
// 砲塔
class Turret extends Sprite {
public static const ADD_BULLET: String = "addBullet"
private static const SIZE: int = 25
private var barrels: Array = []
private var actionIndex: int = 0
private var _loading: int = 0
public function Turret(_x: int, _y: int): void {
x = _x
y = _y
barrels.push(new Barrel(-3))
barrels.push(new Barrel(0))
barrels.push(new Barrel(+3))
for each (var barrel: Barrel in barrels) addChild(barrel)
var armor: Sprite = new Sprite()
with (addChild(armor)) {
graphics.beginFill(0xe0e0e0)
graphics.drawEllipse(-SIZE/2, -SIZE/2, SIZE, SIZE)
graphics.endFill()
}
}
public function loading(): Boolean { return 0 < _loading }
public function shot(): void {
if (loading()) return
actionIndex = (actionIndex + 1) % barrels.length
var barrel: Barrel = barrels[actionIndex]
if (barrel.loading()) return
barrel.shot()
_loading = 3;
dispatchEvent(new BulletEvent(ADD_BULLET, barrel.pos))
}
public function frameAction(trigger: Boolean): void {
if (0 < _loading) _loading -= 1
if (trigger) shot()
for each (var barrel: Barrel in barrels) barrel.frameAction()
}
}
I keep getting the compiled error
5008: The name of definition 'Main' does not reflect the location of this file. Please change the definition's name inside this file, or rename the file.du34.as
Follow the advice in the error. Rename the Main class inside the package definition to du34 (or whatever the AS3 file is called), or rename the file it is in to Main. The class and filename have to match:
ActionScript 3.0 allows you to include multiple classes in one source file, but only one class in each file can be made available to code that is external to that file. In other words, only one class in each file can be declared inside a package declaration. You must declare any additional classes outside your package definition, which makes those classes invisible to code outside that source file. The name of the class declared inside the package definition must match the name of the source file.
Do you need more semicolons ? It seems a lot of semicolons are missing.
Perhaps changing the class name might help.
In actionscript under normal uses you need one class per "as" file.
The "as" file needs to be named the same as the class.
Class names should be named with a captial first letter ex:MyClass
All class files need to be included in a package.
A package structure needs to reflex the director it is in relation to the source fla/mxml files
In your sample code you supplied you have 5 classes and you need 5 "as" files
The following example assumes the package/class is in the same directory as your FLA
saved off as Main.as
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
[SWF(width=1000, height=1000, framerate=24)]
public class Main extends Sprite
{
private static const SCREEN_WIDTH: int = 1000
private static const SCREEN_HEIGHT: int = 1000
private var turret: Turret = null
private var me: MouseEvent = null
private var trigger: Boolean = false
private var bullets: Array = []
public function Main():void
{
graphics.beginFill(0x0)
graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
graphics.endFill()
turret = new Turret(SCREEN_WIDTH / 2, SCREEN_HEIGHT)
turret.addEventListener(Turret.ADD_BULLET, onAddBullet)
addChild(turret)
addEventListener(Event.ENTER_FRAME, onEnterFrame)
stage.addEventListener(MouseEvent.MOUSE_DOWN, function(): void { trigger = true } )
stage.addEventListener(MouseEvent.MOUSE_UP, function(): void { trigger = false } )
}
private var nextAddBullet: Bullet = null;
private function onAddBullet(e: BulletEvent): void
{
nextAddBullet = new Bullet(turret.x + e.pos, turret.y, mouseX, mouseY)
}
private var frameProcessing: Boolean = false
private function onEnterFrame(e: Event): void
{
if (frameProcessing) return
frameProcessing = true
if (null != nextAddBullet) {
bullets.push(nextAddBullet)
addChild(nextAddBullet)
nextAddBullet = null
}
turret.frameAction(trigger)
var i: int
for (i = 0; i < bullets.length; i++) {
var bullet: Bullet = bullets[i]
if (null != bullet) {
if (bullet.frameAction()) {
removeChild(bullet)
bullets[i] = null
}
}
}
i = bullets.length
while (0 < i--) {
if (null == bullets[i]) bullets.splice(i, 1)
}
frameProcessing = false
}
}
}
you still need "as" files for BulletEvent, Bullet, Barrel, Turret
Try this.. Rename the Main class inside the package definition to du34. In the directory (same location with .fla) create folder name du34 and put du34.as into it.