am new here. i have a slight problem; PLease look at the following code and tell me if am doing something wrong because the image is not displaying. i have made it really small so it should fit but its not displaying. i have images displaying in other screens but this main midlet would not. Here is the code:
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* #author jay
*/
public class WShop extends MIDlet implements CommandListener {
/* Declare display variables*/
private Form mainForm;
private Display display;
private Command OK,Exit,wView, mView, myView;
/* */
Categories categories = new Categories(this);
Image image;
public WShop() {
/* initialize Screen and Command buttons that will
be used when the application starts in the class constructor*/
mainForm = new Form("Wind Shopper");
OK = new Command("OK", Command.OK, 2);
Exit = new Command("Exit", Command.EXIT, 0);
wview= new Command("wview", Command.OK, 0);
mview= new Command("mview", Command.OK, 0);
try {
/* retrieving the main image of the application*/
image = Image.createImage("/main.png");
} catch (IOException ex) {
ex.printStackTrace();
}
mainForm.addCommand(OK);
mainForm.addCommand(Exit);
mainForm.addCommand(wView);
mainForm.addCommand(mView);
mainForm.setCommandListener(this);
}
public void startApp() {
/* checks to see if the display is currently empty
and then sets it to the current screen */
if (display == null) {
display = Display.getDisplay(this);
}
display.setCurrent(mainForm);
}
/* paused state of the application*/
public void pauseApp() {
}
/* Destroy Midlet state*/
public void destroyApp(boolean unconditional) {
}
Thanks in advance.
Looks to me like you forgot to Form.append() your Image to your form.
Related
I work on a LWUIT project that aims to computerize an Arabic book . That means each page of the
mentioned book accessed by a specific button
returns
To do that I created a form , array of buttons, and a textarea.
The setText( ) method of textarea widget is used to involve each page of the book
How?
When a button pressed
the setText( ) changes it's string according to the content of the
required page
returns
At the end of the project a problem of formatting faces me .
The book page's contents (Strings ) are unformatted.
returns
to solve the problem I tried a LWUIT HtmlComponent instead of textArea in order to format using
html tags , but it takes much of memory
(at least it cost more than 700 kb for an application).
So I wouldn't be able include all the pages of the book by this way.
returns
This my first trial
import javax.microedition.midlet.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.*;
public class Arabic_Lang extends MIDlet {
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form main_form = new com.sun.lwuit.Form();
final com.sun.lwuit.Form f = new com.sun.lwuit.Form();
final com.sun.lwuit.TextArea txt1 = new com.sun.lwuit.TextArea();
f.addComponent(txt1);
final com.sun.lwuit.Button l[]= new com.sun.lwuit.Button [3];
final com.sun.lwuit.Button inter = new com.sun.lwuit.Button("inter");
final com.sun.lwuit.Form jjj8 = new com.sun.lwuit.Form();
jjj8.setTitle( "اللغة العربية");
jjj8.getStyle().setBgColor(0x006699);
jjj8.setScrollableX(true);
int i;
for(i=0;i<3;i++)
{
l[i] =new com.sun.lwuit.Button();
l[i].getStyle().setBgColor(0xFFF66);
main_form.addComponent(l[i]);
main_form.setScrollable (true);
main_form.setScrollableX(false);
}
l[0].setText("");
l[0].getStyle().setBgColor(0xffff00);
l[0].setText("arabic");
l[1].setText("arabic");
l[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
}
});
l[1].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
f.show();
}
});
jjj8.addComponent(inter);
inter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
main_form.show();
}
}
);
jjj8.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
returns
And this is my trial to use htmlComponent
returns
import com.sun.lwuit.layouts.*;
import javax.microedition.midlet.*;
public class HelloLWUITMidlet3 extends MIDlet
{
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form form = new com.sun.lwuit.Form("");
final com.sun.lwuit.html.HTMLComponent htmlC = new com.sun.lwuit.html.HTMLComponent( );
htmlC.setRTL(true);
htmlC.setBodyText("هذه لغة عربية","UTF-8" );
form.addComponent(htmlC);
BorderLayout bl = new BorderLayout();
form.setScrollable(true);
form.show( );
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
Store the pages of the book as HTML files in your src dir (in the jar root) and load them directly into the HTMLComponent as is shown in the LWUITDemo.
I'm trying to make my code neater by using multiple classes for my applications
form options. Currently I keep getting null pointer exceptions when trying to setCurrent.
Here is my main class the error starts in my command listener when I call the other class.
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class CalFrontEnd extends MIDlet implements CommandListener {
private Display display;
private List list = new List("Please Select a Option", List.IMPLICIT);
private List Blist = new List("Please Select a Browsing Option", List.IMPLICIT);
private Command select = new Command("Select", Command.SCREEN, 1);
private Command exit = new Command("Exit", Command.EXIT, 2);
private Command save = new Command("Save,", Command.SCREEN, 2);
private DateField calendar;
Alert alert;
//
//
//
public CalFrontEnd() {
display = Display.getDisplay(this);
list.append("Select Date", null);
list.append("Add Events", null);
list.append("Remove Events", null);
list.append("Browse Events", null);
list.addCommand(select);
list.addCommand(exit);
list.setCommandListener(this);
}
//
//Start Application Method
//
public void startApp() {
display.setCurrent(list);
}
//
//Pause Application Method
//
public void pauseApp() {
}
//
//Destroy Application Method
//
public void destroyApp(boolean unconditional) {
}
//
//Method creates form which contains calendar
//
/*public void selectDate()
{
calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
Form cform = new Form("Calendar");
cform.append(calendar);
cform.addCommand(exit);
display.setCurrent(cform);
}*/
//
//Method creates form which contains adding events
//
public void AddEvents()
{
TextBox aeText = new TextBox("Add Event","", 256, 0);
display.setCurrent(aeText);
}
//
//Method creates form which contains removing events
//
public void RemoveEvents()
{
Form reform = new Form("Remove Event");
reform.append(calendar);
display.setCurrent(reform);
}
//
//Method creates form which contains removing events
//
public void BrowseEvents()
{
Blist.append("Monthly", null);
Blist.append("Daily", null);
Blist.addCommand(select);
Blist.addCommand(exit);
Blist.setCommandListener(this);
display.setCurrent(Blist);
}
//
//but it's better practice to make each form a different class extending CommandListener and it's own commandAction. And leave the display public static in MIDlet class
//...
public void commandAction(Command command, Displayable displayable) {
if (displayable == list) {
if (command == List.SELECT_COMMAND) {
switch (list.getSelectedIndex()) {
case 0: // select date
SelectDate.BuildCalendar(); //Error Here
break;
case 1: //add events
AddEvents();
break;
}
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
}
And here is the class that is being called.
public class SelectDate
{
private static DateField calendar;
private static Form form = new Form("derb");
private static Command select = new Command("Select", Command.SCREEN, 1);
private static Command exit = new Command("Exit", Command.EXIT, 2);
private static Command save = new Command("Save,", Command.SCREEN, 2);
private static Display display;
public static void BuildCalendar()
{
calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
form.append(calendar);
form.addCommand(exit);
display.setCurrent(form);
}
}
The NullPointerException happens because display in SelectDate class is null.
To fix that, you can for example drop it from there and instead, add to method parameters:
// ...
public static void BuildCalendar(Display display) // added parameter
Then, when you invoke above method from CalFrontEnd, pass the instance of display there:
// ...
SelectDate.BuildCalendar(display); //Error will go away
In my J2ME app, I have some forms, and some threads running on background. If in any of these threads I decide to display a message box or notification bar on top of the app, I have the problem of not knowing in which form I am, therefore I don't know which form to show after the messagebox or notification bar is hidden.
Does anyone have any suggestions?
You can get current form that is already displaying with "Display.getCurrent()".For example this canvas is a SplashScreen that get current form before displays in the screen:
import javax.microedition.lcdui.Canvas;
/* */ import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
/* */ import javax.microedition.lcdui.Graphics;
/* */ import javax.microedition.lcdui.Image;
public class StaticSplashScreen extends Canvas
implements Runnable {
private HelloMIDlet mainMidlet;
private boolean isSplashOver;
private long currentTime;
private long previousTime;
private Form currentForm;
public StaticSplashScreen(HelloMIDlet mid) {
this.mainMidlet = mid;
currentForm = (Form) this.mainMidlet.getDisplay().getCurrent();
this.previousTime = System.currentTimeMillis();
new Thread(this).start();
}
protected void paint(Graphics g) {
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0, 0, 0);
g.drawString("In the name of God", 40, 70, 0);
}
public void run() {
while (!this.isSplashOver) {
this.currentTime = System.currentTimeMillis();
if (this.currentTime - this.previousTime >= 10000L) {
this.isSplashOver = true;
}
}
this.mainMidlet.getDisplay().setCurrent(currentForm);
}
}
In this midlet you can see two forms with some commands.When you press "help" in each form,method() calls and SplashScreen diplays and after 10 seconds you can see the form that launched it again:
public class HelloMIDlet extends MIDlet implements CommandListener {
...
public void commandAction (Command command, Displayable displayable) {
...
if (command == helpCommand) {
method ();
}
...
}
public Form getForm () {
if (form == null) {
form = new Form ("Welcome");
form.addCommand (getHelpCommand());
form.setCommandListener (this);
}
return form;
}
public void method () {
if (true) {
StaticSplashScreen sss = new StaticSplashScreen(this);
this.getDisplay().setCurrent(sss);
} else {
}
}
public Form getForm1 () {
if (form1 == null) {
form1 = new Form ("form1");
form1.addCommand (getHelpCommand ());
form1.setCommandListener (this);
}
return form1;
}
}
A ticker is an object that provides scrolling text across the top of the display. A Ticker is associated with the display, not with the screen. You place a Ticker on a screen using the Screen.setTicker(Ticker t) method, as shown in the code below.
You can associate the same Ticker object with multiple screens, however. The implementation renders the Ticker on some constant portion of the display, in this case at the top of the display. Ticker is not an Item. Its derivation directly from java.lang.Object gives you a clue as to why a Ticker can be tied to the display and not to a screen. It doesn't need to be derived from Item, because it really is not something that is placed in a Form.
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Ticker;
import javax.microedition.lcdui.Form;
/**
This class demonstrates use of the Ticker MIDP UI
component class.
#see javax.microedition.lcdui.Gauge
*/
public class TickerDemo extends Form
implements CommandListener
{
private String str =
"This text keeps scrolling until the demo stops...";
private Ticker ticker = new Ticker(str);
private Command back = new Command("Back", Command.BACK, 1);
private static Displayable instance;
/**
Constructor.
*/
public TickerDemo()
{
super("Ticker demo");
instance = this;
addCommand(back);
setTicker(ticker);
setCommandListener(this);
}
...
}
Hope this will help you. Thanks
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 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).