Eclipse Java KeyEvent.VK_LEFT (NOT WORKING) - keycode

This is some code that should create a oval that can be controlled via arrow keys.
I have done lots of research but I haven't been able to find a solution to my problem.
I am using Eclipse Mars with the Java language. Here is my code.
package com.game;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends Applet implements KeyListener, Runnable {
public int x,y;
public boolean up,down,left,right;
public Image offscreen;
public Graphics d;
public void init(){
setSize(854,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(854,480);
d = offscreen.getGraphics();
this.addKeyListener(new Game());
}
public void run(){
while(true)
{
System.out.println("X: " + x);
System.out.println("Y: " + y);
if(left == true){
x--;
}
if(right == true){
x++;
}
if(up == true){
y--;
}
if(down == true){
y++;
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Right key pressed");
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Left key pressed");
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = false;
}
}
public void paint (Graphics g){
d.clearRect(0, 0, 854, 480);
d.drawOval(x, y, 20, 20);
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
}
When running this code, pressing arrow keys is not doing anything.

Related

variable not getting updated as expected in Java

I am learning Java and have encountered an unexpected problem:
variable i is getting updated in mouse listener but updated value is not getting passed back to main program. But if I uncomment Thread.sleep(1) block everything is back to normal.
Here is the program:
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends Frame
implements MouseListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
static int i=0;//State variable
public MouseEventDemo()
{
addMouseListener(this);
addWindowListener(new MyWindowAdapter());
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
i=1;
msg = "Click received. i= "+i;
mouseX = me.getX();
mouseY = me.getY();
repaint();
}
public void mouseMoved(MouseEvent me)
{
}
public void mouseDragged(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
// Display msg in the window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
public static void main(String[] args)
{
MouseEventDemo appwin = new MouseEventDemo();
appwin.setSize(new Dimension(300, 300));
appwin.setTitle("MouseEventDemo");
appwin.setVisible(true);
while (true)
{
if(i==1)
{
System.out.println("Value of i is: "+i);
i=0;
}
/*
try
{
Thread.sleep(1);
}
catch(Exception e)
{
System.out.println(e);
};
*/
}
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
This program behaves not like I have expected, but with Thread.sleep(1) it changes it behaviour

How to determine the state of the GPS in BlackBerry?

i want to know how determine the state of the GPS, soo if the state is different to AVAILABLE i don't create the Listener to save battery.
But in execution always enter for the else create the LocationListener and not for the if.
Here is my code
public class UpdateGPS extends Thread{
public void run(){
while (true){
try{
getGPS();
sleep(30000); //Update GPS for each 30secs
}
catch(Exception e){}
}
}
}
public void getGPS() {
String state = "RUNNING";
BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);
try {
locationProvider = LocationProvider.getInstance(myCriteria);
if (locationProvider != null) {
if (locationProvider.getState() != locationProvider.AVAILABLE) {
state= "STOP";
}
else {
locationProvider.setLocationListener(
new LocationListenerImplementacion(),valor_reintento, -1, -1);
}
}
}
catch(Exception e) {}
}
private class LocationListenerImplementacion implements LocationListener {
public void locationUpdated(LocationProvider provider,Location location) {
if (location.isValid()) {
//GET DATA
}
else {}
public void providerStateChanged(LocationProvider provider, int newState){
}
}

Get Camera captured images and create bitmap image

How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.
ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}
try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}

Launch the video recorder from BlackBerry app

Are there any APIs to launch the video recording app? I want to invoke the video recorder through my app, record a video, then save that video to the server.
ApplicationManager.getApplicationManager().launch("net_rim_bb_videorecorder");
This will help you open the application. If you want to start recording, you may need to simulate a key input.
btw: CameraArguments(ARG_VIDEO_RECORDER) is introduced since jde4.7, so it's not compatible with the previous OS's. So the previous method is better.
Finally find the solution from BB docs .
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.lang.*;
import javax.microedition.media.*;
import java.io.*;
import javax.microedition.media.control.*;
public class VideoRecordingDemo extends UiApplication
{
public static void main(String[] args)
{
VideoRecordingDemo app = new VideoRecordingDemo();
app.enterEventDispatcher();
}
public VideoRecordingDemo()
{
pushScreen(new VideoRecordingDemoScreen());
}
private class VideoRecordingDemoScreen extends MainScreen
{
private VideoRecorderThread _recorderThread;
public VideoRecordingDemoScreen()
{
setTitle("Video recording demo");
addMenuItem(new StartRecording());
addMenuItem(new StopRecording());
}
private class StartRecording extends MenuItem
{
public StartRecording()
{
super("Start recording", 0, 100);
}
public void run()
{
try
{
VideoRecorderThread newRecorderThread = new VideoRecorderThread();
newRecorderThread.start();
_recorderThread = newRecorderThread;
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class StopRecording extends MenuItem
{
public StopRecording()
{
super("Stop recording", 0, 100);
}
public void run()
{
try
{
if (_recorderThread != null)
{
_recorderThread.stop();
}
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class VideoRecorderThread extends Thread implements javax.microedition.media.PlayerListener
{
private Player _player;
private RecordControl _recordControl;
VideoRecorderThread()
{
}
public void run()
{
try
{
_player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=video/3gpp");
_player.addPlayerListener(this);
_player.realize();
VideoControl videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl( "RecordControl" );
Field videoField = (Field) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
try
{
videoControl.setDisplaySize( Display.getWidth(), Display.getHeight() );
}
catch( MediaException me )
{
// setDisplaySize is not supported
}
add(videoField);
_recordControl.setRecordLocation("file:///store/home/user/VideoRecordingTest.3gpp" );
_recordControl.startRecord();
_player.start();
}
catch( IOException e )
{
Dialog.alert(e.toString());
}
catch( MediaException e )
{
Dialog.alert(e.toString());
}
}
public void stop()
{
if (_player != null)
{
_player.close();
_player = null;
}
if (_recordControl != null)
{
_recordControl.stopRecord();
try
{
_recordControl.commit();
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
_recordControl = null;
}
}
public void playerUpdate(Player player, String event, Object eventData)
{
Dialog.alert("Player " + player.hashCode() + " got event " + event + ": " + eventData);
}
}
}
}

Adding Editfield to Popup screen

I have created my own custom popup screen to which now I am trying to add a editfield , everything seems to be fine but the problem is that I am not able to write anything in the edit field
class sveetIt extends PopupScreen implements FieldChangeListener, DialogClosedListener {
Hashtable pitemData;
ButtonField sveetNowlabelField;
ButtonField sveetLaterlabelField;
WatingScreen watingScreen;
long scheduledTime;
Dialog updateDialog;
public sveetIt() {
super(new MyCustimGridFieldManager());
LabelField messageLabelField = new LabelField("Enter your Sveet Message:",Field.FIELD_HCENTER) {
protected void paint(Graphics graphics) {
graphics.setColor(Color.YELLOWGREEN);
super.paint(graphics);
}
};
EditField sveetTexteditField= new EditField(null, "Sveet Message", 50, EditField.FIELD_HCENTER
| EditField.FIELD_VCENTER
| EditField.NON_SPELLCHECKABLE | EditField.NO_NEWLINE);
VerticalFieldManager buttonVFManager = new VerticalFieldManager(VerticalFieldManager.FIELD_HCENTER);
HorizontalFieldManager hfManager = new HorizontalFieldManager();
sveetNowlabelField = new ButtonField("Sveet Now");
sveetLaterlabelField = new ButtonField("Sveet Later");
sveetNowlabelField.setChangeListener(this);
sveetLaterlabelField.setChangeListener(this);
add(messageLabelField);
add(sveetTexteditField);
hfManager.add(sveetNowlabelField);
hfManager.add(sveetLaterlabelField);
buttonVFManager.add(hfManager);
add(buttonVFManager);
}
public boolean isEditable() {
return true;
}
protected boolean keyChar(char c, int status, int time) {
boolean retVal = false;
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
retVal = super.keyChar(c, status, time);
}
return retVal;
}
public void fieldChanged(Field field, int context) {
if (sveetNowlabelField == field) {
//Here directly starts uploading file
beginUpload();
} else if (sveetLaterlabelField == field) {
// first picks up time when to upload
scheduledTime = getScheduleTime();
if(scheduledTime!=1L) {
//now begins uploading file
beginUpload();
}
}}
class SubscribingThread extends StoppableThread {
int network = 50;
public void run() {
}
}
public void beginUpload() {
try {
watingScreen = new WatingScreen("Uploading Sveet...");
/*
* UiApplication.getUiApplication().invokeAndWait( new Runnable() {
* public void run() { Ui.getUiEngine().pushScreen(watingScreen); }
* });
*/
BaseScreen.pushScreen(watingScreen);
Thread thread = new Thread(new Runnable() {
public void run() {
uploadToServer();
}
});
thread.start();
// uploadToServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private long getScheduleTime() {
scheduledTime = 0;
final DateTimePicker datePick = DateTimePicker.createInstance();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Calendar currentCalendar = datePick.getDateTime();
datePick.setMinimumDate(currentCalendar);
datePick.doModal();
Calendar cal = datePick.getDateTime();
if (cal.after(currentCalendar)) {
Date date = cal.getTime();
Dialog.alert("You selected " + date.toString());
scheduledTime = date.getTime();
} else {
Dialog.alert("Invalid date selection");
scheduledTime = 1L;
}
}
});
System.out.println("date in MilliSeconds is:" + scheduledTime);
return scheduledTime;
}
public void uploadToServer() {
} public void dialogClosed(Dialog arg0, int arg1) {
}
}
class MyCustimGridFieldManager extends VerticalFieldManager {
public MyCustimGridFieldManager() {
super(VERTICAL_SCROLL | USE_ALL_WIDTH | FIELD_HCENTER);
}
protected void paint(Graphics gr) {
super.paint(gr);
}
}
try this:
protected boolean keyChar(char c, int status, int time) {
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
}
return super.keyChar(c, status, time);
}
Try adding Field.EDITABLE to your style for the EditField.

Resources