displaying image in j2me application - java-me

How do I create and display an image in j2me application?
And in which folder can I put that image in my application?

This link has exactly what you are looking for to get started.
Basically, to create the image, you call upon Image.createImage();
Image img = Image.createImage("/imageName.png");
If it is in a sub-folder in the Jar:
Image img = Image.createImage("/subDir/imageName.png");
To display the image, you need to paint it to a Canvas through a Graphics instance that is tied to the Canvas (better visualized in the link above).
public void paint(Graphics g) {
...
g.drawImage(img, 0, 0, Graphics.TOP | Graphics.LEFT);
....
}
You could also use the Graphics.drawRegion function, but here is a link to the JavaDocs for J2ME for you to look through to see what is best for your needs.

To draw an Image on a JavaME MIDlet you need a Canvas to paint it on to. You can do as follow:
Firs you have to place the original image file inside your package (usually inside "res" or one of his subdirectories).
Secondly you need to create a class extending Canvas and implement the paint method:
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class MyCanvas extends Canvas {
private Image image;
public MyCanvas(){
try {
image = Image.createImage("picture.png");
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paint(Graphics g) {
g.drawImage(image, 10, 10, Graphics.TOP | Graphics.LEFT);
}
}
Now you need to create an instance of this class and tell the MIDlet di display it, for example:
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MyMIDlet extends MIDlet {
public MyMIDlet(){
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Display.getDisplay(this).setCurrent(new MyCanvas());
}
}
Remember that this way the Canvas will be painted only one time and if you change something, you need to call the repaint() method.

This source code builds on previously posted comments:
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ImageLoader extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
public ImageLoader() {
mForm = new Form("Connecting...");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
}
public void startApp() {
if (mDisplay == null) mDisplay = Display.getDisplay(this);
mDisplay.setCurrent(mForm);
Thread t = new Thread(this);
t.start();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT)
notifyDestroyed();
}
public void run() {
FileConnection fc = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
fc = (FileConnection)Connector.open("file:///root1/i.PNG");
int length = (int)fc.fileSize();//possible loss of precision may throw error
byte[] data = null;
if (length != -1) {
data = new byte[length];
in = new DataInputStream(fc.openInputStream());
in.readFully(data);
}
else {
int chunkSize = 512;
int index = 0;
int readLength = 0;
in = new DataInputStream(fc.openInputStream());
data = new byte[chunkSize];
do {
if (data.length < index + chunkSize) {
byte[] newData = new byte[index + chunkSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
readLength = in.read(data, index, chunkSize);
index += readLength;
} while (readLength == chunkSize);
length = index;
}
Image image = Image.createImage(data, 0, length);
ImageItem imageItem = new ImageItem(null, image, 0, null);
mForm.append(imageItem);
mForm.setTitle("Done.");
fc = (FileConnection)Connector.open("file:///root1/x.PNG");
if(!fc.exists()){
try{
fc.create();
}catch(Exception ce){System.out.print("Create Error: " + ce);}
}
out = new DataOutputStream(fc.openOutputStream());
out.write(data);
}
catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
mForm.append(stringItem);
mForm.setTitle("Done.");
}
finally {
try {
if (in != null) in.close();
if (fc != null) fc.close();
}
catch (IOException ioe) {}
}
}
}
The code is modified from the link Fostah provided here.
It opens an image, displays it, then saves it as x.PNG instead of i.PNG using FileConnection. The tricky thing to watch for is where the file is being saved/loaded from. If your using J2meWTK with Netbeans, then the folder will be displayed in the output window when you run the mobile app. The folder will be something like temp.DefaultColorPhone/filesystem/root1 . That is where you will have to have an image. I'm not sure how to have the temp environment created with the image by default. That means you have to start the mobile app, check where the temp root1/ is located, in your IDE, then drop the image into the folder, then proceed with running the ImageLoader application. I'll try to find out how to automate this by posting a question. Also, Start with a small image, 50x50 (bigger images may cause problems).

Related

IOException loading PNG image

I am currently working on a school J2ME project using Canvas and I am trying to get the Ping Pong ball app ready for tomorrow's exam, but when loading a PNG image with Image.createImage(url) I get an IOException (the image is in the right src file and it's 32x32 pixels)
This is my code:
public class BallGame extends GameCanvas implements Runnable {
private Image ballImg;
private Sprite ballSprite;
private String url="/ball.PNG";
private int ballX = getWidth() / 2;
private int ballY = getHeight() / 2;
public BallGame() {
super(false);
}
public void run() {
while (true) {
try {
updateScreen(getGraphics());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void start() {
try {
ballImg = Image.createImage(url);
} catch (IOException ex) {
System.out.println("*********");
ex.printStackTrace();
System.out.println("********************");
}
ballSprite = new Sprite(ballImg, 32, 32);
ballSprite.setRefPixelPosition(16, 16);
ballSprite.setPosition(ballX, ballY);
Thread runner = new Thread(this);
runner.start();
}
public void Createbackground(Graphics g) {
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
}
public void updateScreen(Graphics graphics) {
Createbackground(graphics);
ballSprite.setRefPixelPosition(ballX, ballY);
ballSprite.paint(graphics);
flushGraphics();
}
public void moveBall() {
}}
Looks to me like you have a wrong path or some problems with the ownership of the file. Check if some other program is editing it.
Have you tried adding a full absolute path?
Also have you tried using the "ball.png" image inside the same folder without folder paths like:
private String url="ball.PNG";
If that works it's definitely a path problem.
In my J2ME device version when I open a file my path starts like this:
String path_start="file:///a:/";

Trying to print a string character by character with delay between two character print

I've tried with code below. please guide me where i am wrong??? The desired output is like..
m(delay)e(delay)s(delay)s(delay)a(delay)g(delay)e.
import java.util.*;
import java.applet.*;
import java.awt.*;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends Applet implements Runnable {
Thread t;
//char msg[] ={"m","e","s","s","a","g","e"};
String str = "message";
Graphics bufferg;
Image buffer;
int counter=0,x=str.length(),i=0;;
public void init() {
//initializa the thread
t = new Thread(this);
t.start();
Dimension d = getSize();
buffer = createImage(d.width,d.height);
}
public void run() {
try {
while(true)
{
//requesting repaint
repaint();
if(counter==x)
{
Thread.sleep(200);
counter=0;
i=0;
}
else
{
Thread.sleep(400);
}
}
}
catch(Exception e) {
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(bufferg == null) {
Dimension d = getSize();
bufferg.setColor(Color.green);
g.setFont(new Font("Comic Sans MS",Font.BOLD,36));
bufferg.drawString(str.charAt(i)+"",20,20);
counter++;
i+=1;
//update screen
g.drawImage(buffer,0,0,this);
}
}
}
I am working on command prompt and its giving me bunch of different errors. I want to know why the errors occurring if anyone could explain me by trying it. Thanx in advance.
The problems I found include:
Use JApplet instead of Applet.
In the init method, create the buffer before starting the thread.
Update the buffer with the letters in the run method. The paint method just paints. No calculations.
Here's the working code. I formatted the code in Eclipse, an integrated development environment (IDE) for Java development.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends JApplet implements Runnable {
private static final long serialVersionUID = 1722008447683646619L;
Thread t;
String str = "message";
Image buffer;
#Override
public void init() {
Dimension d = getSize();
buffer = createImage(d.width, d.height);
// Initialize the thread
t = new Thread(this);
t.start();
}
#Override
public void run() {
int x = 40;
int y = 40;
for (int i = 0; i < str.length(); i++) {
Graphics g = buffer.getGraphics();
g.setFont(new Font("Comic Sans MS", Font.BOLD, 36));
g.setColor(Color.GREEN);
g.drawString("" + str.charAt(i), x, y);
g.dispose();
x += 40;
repaint();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
}

Getting phone hearing volume with Java ME

Is it possible to get the value of phobe in-call volume from java me midlet? Changing of the volume is not necessary.
Thanks.
AFAIK,
It is not possible to access the phone volume. But you can set your application volume or get the application.
Sample code for Controlling the volume of your application :
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Ticker;
import javax.microedition.media.*;
public class VolumeControlDemo extends MIDlet implements CommandListener {
private Display display;
private Command exit,incr,decr;
Form frm;
VolumeControl vc;
int vol;
Player player;
public VolumeControlDemo() {
display = Display.getDisplay(this);
}
public void startApp() {
frm=new Form("VolumeControlDemo Demo");
exit= new Command("Exit",Command.EXIT,1);
decr= new Command("Decrease",Command.EXIT,1);
incr= new Command("Increase",Command.EXIT,1);
frm.addCommand(exit);
frm.addCommand(decr);
frm.addCommand(incr);
frm.setCommandListener(this);
display.setCurrent(frm);
try {
// Creating player object
player = Manager.createPlayer("/demo.wav");
// Setting loop count
player.setLoopCount(-1);
// Start sound
player.start();
Control cs[];
// Getting Controls object
cs = player.getControls();
for (int i = 0; i < cs.length; i++) {
if (cs[i] instanceof VolumeControl)
// Getting volume control
vc=(VolumeControl)cs[i];
}
} catch (Exception e) {}
}
public void pauseApp() {
}
public void destroyApp(boolean un) {
}
public void commandAction(Command cmd,Displayable d) {
try {
if(decr) {
if(vol>0) vol--;
vc.setLevel(vol);
} else if() {
if(vol<99) vol--;
vc.setLevel(vol);
}
frm.appent("vol="+vc.getLevel());
}catch(Exception e){}
}
}

How to link an excel file with the application software using Java swing

I have to link an excel file with a application software which I am developing.The excel file will contain questionnaire for conducting surveys.I have this code which is only able to open a Jpanel to select the file.After I select the file nothing is happening.I wanted to be able to generate a template based on the questions that are in the excel file (like extracting the questions from the excel file and creating a template from it) and which I have to upload on the web later.could you please help me with this?
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class SelectFile extends JFrame{
public static void main(String[]args){
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Select File for Linking");
frame.setSize(400, 100);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
text.setBounds(20,20,120,20);
b.setBounds(150,20,80,20);
// b.setText("<html><font color='blue'><u>Select File</u></font></html>");
b.setHorizontalAlignment(SwingConstants.LEFT);
//b.setBorderPainted(false);
//b.setOpaque(false);
// b.setBackground(Color.lightGray);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new OnlyExt());
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
}
}
});
container.add(text);
container.add(b);
frame.setVisible(true);
}
}
class OnlyExt extends javax.swing.filechooser.FileFilter{
public boolean accept(File file) {
if (file.isDirectory()) return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".xls"));
}
public String getDescription() { return "Excel ( *.xls)"; }
}
Apache POI http://poi.apache.org/ provides an API for reading / writing Excel Files.
Look over this source for some tips.
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.EmptyBorder;
public class SelectFile {
public static void main(String[]args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("Select File for Linking");
// don't use null layouts.
//frame.setLayout(null);
// create a panel so we can add a border
JPanel container = new JPanel(new FlowLayout(3));
container.setBorder(new EmptyBorder(10,10,10,10));
frame.setContentPane(container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// instead call pack() after components are added
//frame.setSize(400, 100);
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
// irrelevant unless button stretched by layout
//b.setHorizontalAlignment(SwingConstants.LEFT);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
String desc = "Excel ( *.xls)";
String[] types = {".xls"};
fc.addChoosableFileFilter(
new FileNameExtensionFilter(desc, types));
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
try {
// 1.6+
Desktop.getDesktop().edit(file);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
container.add(text);
container.add(b);
frame.pack();
frame.setVisible(true);
}
});
}
}
BTW - The JFrame here would probably be better converted to a JDialog or JOptionPane.

How can I repaint part of screen on blackberry while connections run?

I have two questions.
The first is about updating the UI, the second is when I try to connect to the camera to get a mjpeg stream and run getResponseCode(), the app locks there. The MDS shows a lot of data transferring.
I have some classes like ....:
Http extends Thread {
public abstract String getUrl();
public abstract String getBase64Encode();
public abstract void onReturn(int responseCode, InputStream is,int lenght);
protected abstract void onError(Exception e);
}
CameraHttp extends Http and MjpegHttp extends CameraHttp.
http connects to a URL which is the jpeg or mjpeg camera adresses.
I have a Camera Class. It starts a connection with the overridden method mjpegconnection.go();
I also have a static bitmap on ViewCam screen which extends MainScreen.
After it starts:
url = getUrl();
queryString = encodeURL(queryString);
byte postmsg[] = queryString.getBytes("UTF-8");
httpConnection = (HttpConnection) Connector.open(url
+ ";deviceside=false", Connector.READ_WRITE);
httpConnection.setRequestMethod(HttpConnection.GET);
httpConnection.setRequestProperty("Authorization", getBase64Encode());
os = httpConnection.openDataOutputStream();
for (int i = 0; i < postmsg.length; i++) {
os.write(postmsg[i]);
}
{
if (!cancel) {
System.out.println(httpConnection.getURL()+
" *****"+httpConnection.getPort());
System.out.println("onreturn oncesi"
+ httpConnection.getResponseCode());
onReturn(httpConnection.getResponseCode(), httpConnection
.openInputStream(),(int) httpConnection.getLength());
System.out.println("onreturn sornrası");
}
os.close();
httpConnection.close();
}
} catch (Exception e) {
System.out.println("hata " + e.getMessage());
try {
httpConnection.close();
Thread.sleep(60);
} catch (Exception ie) {
}
onError(e);
}
After dosomething
// decides mjpeg-jpeg stream
// if it is mjpeg, direct to parser,
// else it sets image with setImage() and return to connection with go();
public void parse(InputStream is, int lenght) {
try {
if (!type.isMjpegStream()) {
setImage(is, lenght);
System.gc();
StaticVar.ActiveCam.setConnected(true);
} else {
if (parser == null) {
parser = new JpegParser(is, this);
} else {
parser.setInputSteam(is, this);
}
parser.parse();
is.close();
}
} catch (Exception e) {
}
}
and
public void setImage(InputStream is, int lenght) {
byte[] raw = new byte[lenght];
try {
is.read(raw);
currentImage = Bitmap.createBitmapFromBytes(raw, 0, raw.length, 1);
ViewCam.ViewCam=currentImage; //static var.
} catch (IOException e) {
System.out.println("catche***********");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How can I repaint the screen to show the bitmap?
And my ViewCam
public class ViewCam extends MainScreen {
Header header;
String headerString;
public static Bitmap ViewCam;// cam image shows
private static Thread My;// runs connection
void OnStart() {
My = new Thread() {
public void run() {
System.out.println("ONSTART");
StaticVar.ActiveCam.go();
};
};
My.start();
Bitmap bitmap = Bitmap.getBitmapResource("res/main.png");
Bitmap bmp2 = ResizeImage.resizeBitmap(bitmap, Display.getWidth(),
Display.getHeight());
Background bg = BackgroundFactory.createBitmapBackground(bmp2);
this.setBackground(bg);
this.getMainManager().setBackground(bg);
}
public ViewCam() {
StaticVar.ActiveCam.getIp();
OnStart();
headerString ="Cam View";
header = new Header("res/bartop.png", headerString, 0);
add(header);
ViewCam = Bitmap.getBitmapResource("res/spexco_splash.png");
ViewCam = ResizeImage.bestFit(ViewCam, Display.getWidth(), Display
.getHeight());
BitmapField bf = new BitmapField(ViewCam);
add(bf);
}
}
Try Screen.invalidate()
public void invalidate(int x, int y, int width, int height)
Invalidates a region of this screen.
This method marks a region of this screen as needing a repaint. The repainting is handled later by the main event dispatch thread.
Note: Any thread can safely invoke this method, and does not require to synchronize on the event lock.
Overrides:
invalidate in class Manager
Parameters:
x - Left edge of the region in ContentRect coordinates.
y - Top edge of the region in ContentRect coordinates.
width - Width (in pixels) of the region.
height - Height (in pixels) of the region.

Resources