TextField.setConstraints null pointer exception - java-me

I have a TextField in a form:
private TextField cc1F = new TextField("", "", 250, TextField.ANY);
Once click button OK, then set cc1F field's Constraints to:
cc1F.setConstraints(TextField.UNEDITABLE);
then I am getting an exception:
java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultInputMethodHandler.setConstraints(+63)
at javax.microedition.lcdui.TextField$InputMethodClientImpl.setConstraints(+20)
at javax.microedition.lcdui.TextField.setConstraints(+37)
at com.zousys.j2me.zmail.gui.view.HeaderView.menuAction(+146)
.....................................
Anyone know this?

The example of code was tested with simulator WTK 3.0 and device Samsung Chat
http://www.gsmarena.com/samsung_ch#t_527-4096.php and the test passed. :)
I think that the problem is caused by device model or the object cc1F is null.
import java.io.UnsupportedEncodingException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TextFieldMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command cmdExit;
private Command cmdSetConstraints;
private Display display;
private TextField textField;
public TextFieldMIDlet() {
form = new Form("Testing constraints");
cmdExit = new Command("Exit",Command.EXIT, 1);
cmdSetConstraints = new Command("Set Constraints",Command.ITEM, 1);
textField = new TextField("", "", 250, TextField.ANY);
form.addCommand(cmdExit);
form.addCommand(cmdSetConstraints);
form.append(textField);
display = Display.getDisplay(this);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.notifyDestroyed();
} else if (c == cmdSetConstraints) {
try {
System.out.println("Set...");
if (textField.getConstraints() == TextField.UNEDITABLE) {
textField.setConstraints(TextField.ANY );
} else {
textField.setConstraints(TextField.UNEDITABLE );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Related

Implementing a pause and resume feature for JavaFX Tasks

I'm building a UI for a Simulator running in background. Since this Simulator may not hold for a long time, it of course has to be in a separate thread from the JavaFx Thread. I want to start, pause, resume and stop/terminate the Simulator when the corresponding button is clicked.
The service class that advances the simulator looks like this:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class SimulatorService extends Service<Void> {
private Simulator simulator;
private long cycleLengthMS = 1000;
private final AtomicBoolean simulatorStopped = new AtomicBoolean(false);
public SimulatorService(Simulator simulator){
this.simulator = simulator;
}
#Override
protected Task<Void> createTask() {
return new Task<>() {
#Override
protected Void call() {
System.out.println("Requested start of Simulator");
int state;
do {
// advance
state = simulator.nextStep();
try {
TimeUnit.MILLISECONDS.sleep(cycleLengthMS);
if(simulatorStopped.get()){
super.cancel();
}
} catch (InterruptedException e) {
return null;
}
}
while (state == 0 && !simulatorStopped.get());
return null;
}
};
}
#Override
public void start(){
if(getState().equals(State.READY)){
simulatorStopped.set(false);
super.start();
}
else if(getState().equals(State.CANCELLED)){
simulatorStopped.set(false);
super.restart();
}
}
#Override
public boolean cancel(){
if(simulatorStopped.get()){
simulatorStopped.set(true);
return false;
} else{
simulatorStopped.set(true);
return true; //if value changed
}
}
}
The Simulator starts the Service if a button on the GUI is pressed:
import javafx.application.Platform;
import java.util.concurrent.atomic.AtomicInteger;
public class Simulator {
Model model;
private final SimulatorService simulatorService;
public Simulator(Model model){
this.model = model;
simulatorService = new SimulatorService(this);
}
public int nextStep(){
final AtomicInteger res = new AtomicInteger(0);
Platform.runLater(new Thread(()-> {
res.set(model.nextStep());
}));
return res.get();
}
public boolean stopSimulationService() throws IllegalStateException{
return simulatorService.cancel();
}
public void startSimulationService() throws IllegalStateException{
simulatorService.start();
}
}
Parts of the window are redrawn if a observed value in the model changes:
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public class Model {
private final IntegerProperty observedValue = new SimpleIntegerProperty(0);
public int nextStep() {
observedValue.set(observedValue.get() + 1);
return observedValue.get() > 500000 ? 1 : 0;
}
public int getObservedValue() {
return observedValue.get();
}
public IntegerProperty observedValueProperty() {
return observedValue;
}
public void setObservedValue(int observedValue) {
this.observedValue.set(observedValue);
}
}
The redraw happens in another class:
import javafx.beans.value.ChangeListener;
public class ViewController {
private View view;
private Simulator simulator;
private Model model;
public ViewController(Simulator simulator) {
this.simulator = simulator;
this.view = new View();
setModel(simulator.model);
view.nextStep.setOnMouseClicked(click -> {
simulator.nextStep();
});
view.startSim.setOnMouseClicked(click -> {
simulator.startSimulationService();
});
view.stopSim.setOnMouseClicked(click ->{
simulator.stopSimulationService();
});
}
public View getView() {
return view;
}
private final ChangeListener<Number> observedValueListener = (observableValue, oldInt, newInt) -> {
view.updateView(newInt.intValue());
};
public void setModel(Model m) {
this.model = m;
m.observedValueProperty().addListener(observedValueListener);
}
}
The corresponding view:
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
public class View extends BorderPane {
Button nextStep = new Button("next step");
Button startSim = new Button("start");
Button stopSim = new Button("stop");
GridPane buttons = new GridPane();
Text num = new Text();
public View(){
buttons.add(nextStep,0,0);
buttons.add(startSim,0,1);
buttons.add(stopSim,0,2);
buttons.setAlignment(Pos.BOTTOM_LEFT);
setCenter(buttons);
setTop(num);
}
public void updateView(int num){
this.num.setText("" + num);
}
}
Main:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
ViewController c = new ViewController(new Simulator(new Model()));
Scene scene = new Scene(c.getView(),200,200);
stage.setScene(scene);
stage.show();
}
}

j2me sprite not working

First, I'm sorry for my bad English. I'm a newbie J2ME
I wrote the below code after i watched some tutorial but it not working. I don't know what happen with it.
AnimationCanvas.java
package example;
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
public class AnimationCanvas extends GameCanvas implements Runnable {
private Sprite ca;
private int frameWidth = 14;
private int frameHeight = 14;
private boolean playing = true;
private int a=1;
public AnimationCanvas(){
super(true);
try {
ca = new Sprite(Image.createImage("ca.png"), frameWidth, frameHeight);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void start() {
Thread runner = new Thread(this);
runner.start();
}
public void run(){
while (playing){
drawDisplay(getGraphics());
try{
Thread.sleep(10);
} catch(Exception e){}
}
}
public void drawDisplay(Graphics g){
g.setColor(0x000000);
g.fillRect(0,0,getWidth(),getHeight());
ca.setFrame(1);
ca.paint(g);
flushGraphics();
}
public void stop(){
playing=false;
}
}
and AnimationMidlet.java
package example;
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class AnimationMidlet extends MIDlet {
private Display display;
private AnimationCanvas canvas;
public AnimationMidlet() throws IOException {
display = Display.getDisplay(this);
canvas = new AnimationCanvas();
}
private void initialize() {
// write pre-initialize user code here
// write post-initialize user code here
}
public void startMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void resumeMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}
public Display getDisplay() {
return Display.getDisplay(this);
}
public void startApp() {
if(canvas!=null){
display.setCurrent(canvas);
canvas.start();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
canvas.stop();
}
}
and the output
Running in the identified_third_party security domain
java.io.IOException
Uncaught exception java/lang/NullPointerException.
at javax.microedition.lcdui.ImmutableImage.getImageFromStream(Image.java:968)
at javax.microedition.lcdui.ImmutableImage.(Image.java:939)
at javax.microedition.lcdui.Image.createImage(Image.java:313)
at example.AnimationCanvas.(AnimationCanvas.java:25)
at example.AnimationMidlet.(AnimationMidlet.java:25)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
Thanks for your reading!

To Hide JavaFx fxml or JavaFx swing application to System Tray

I want to develop a client app for website .
I want the app to reside in system tray when minimised.
I dont know how to accomplish this task .
Is their any example for this type of operation.
The key here is to set the implicit exit to false Platform.setImplicitExit(false);
Also is important to show and hide the stage in a new thread.
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.hide();
}
});
Next, the whole code:
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.imageio.ImageIO;
/**
*
* #author alvaro
*/
public class TrayTest extends Application {
private boolean firstTime;
private TrayIcon trayIcon;
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
createTrayIcon(stage);
firstTime = true;
Platform.setImplicitExit(false);
Scene scene = new Scene(new Group(), 800, 600);
stage.setScene(scene);
stage.show();
}
public void createTrayIcon(final Stage stage) {
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
java.awt.Image image = null;
try {
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
image = ImageIO.read(url);
} catch (IOException ex) {
System.out.println(ex);
}
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
hide(stage);
}
});
// create a action listener to listen for default action executed on the tray icon
final ActionListener closeListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
System.exit(0);
}
};
ActionListener showListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(showListener);
popup.add(showItem);
MenuItem closeItem = new MenuItem("Close");
closeItem.addActionListener(closeListener);
popup.add(closeItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Title", popup);
// set the TrayIcon properties
trayIcon.addActionListener(showListener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
}
}
public void showProgramIsMinimizedMsg() {
if (firstTime) {
trayIcon.displayMessage("Some message.",
"Some other message.",
TrayIcon.MessageType.INFO);
firstTime = false;
}
}
private void hide(final Stage stage) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (SystemTray.isSupported()) {
stage.hide();
showProgramIsMinimizedMsg();
} else {
System.exit(0);
}
}
});
}
}
As far as I know it will be possible in JFX 8. Right now the best solution is to embed your application into AWT and hide the AWT window itself.

lwuit video component never stops

i'm using lwuit videocomponent to play video.
import com.sun.lwuit.Button;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.VideoComponent;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.plaf.Border;
import com.sun.lwuit.table.TableLayout;
import javax.microedition.midlet.*;
public class vtestMidlet extends MIDlet implements ActionListener{
private Image back;
public void startApp() {
Display.init(this);
loginform();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void loginform()
{
Form login=new Form();
Button save;
save=new Button("Save");
login.addComponent(save);
login.getSelectedStyle().setBgColor(0xff0000);
login.getUnselectedStyle().setBgColor(0xff0000);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
videoform();
}
});
login.setTransitionOutAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 200));
login.show();
}
void videoform()
{
final Form videoplayer;
final VideoComponent vc;
Button home;
try{
videoplayer=new Form();
TableLayout layout2 = new TableLayout(10,1);
videoplayer.setLayout(layout2);
vc = VideoComponent.createVideoPeer("http://localhost/md.3gp");
home=new Button("Home");
vc.start();
videoplayer.getUnselectedStyle().setBgImage(back);
videoplayer.getSelectedStyle().setBgImage(back);
home.getUnselectedStyle().setBgColor(0x4673aa);
home.getSelectedStyle().setBgColor(0x4673aa);
home.getUnselectedStyle().setFont(Font.createSystemFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN, Font.SIZE_MEDIUM));
home.getSelectedStyle().setFont(Font.createSystemFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD, Font.SIZE_MEDIUM));
home.getUnselectedStyle().setFgColor(0xffffff);
home.getSelectedStyle().setFgColor(0xffffff);
home.getSelectedStyle().setBorder(Border.createEmpty());
home.getUnselectedStyle().setBorder(Border.createEmpty());
home.getSelectedStyle().setPadding(3, 3, 6, 6);
home.getUnselectedStyle().setPadding(3, 3, 6, 6);
videoplayer.addComponent(vc);
videoplayer.addComponent(home);
videoplayer.setTransitionOutAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 200));
home.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
vc.stop();
loginform();
}
});
videoplayer.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent arg0) {
}
}
My problem is when switch back to another Form (i.e loginform) from Form that displays video (i.e videoform ) , the video plays on top of the loginform. find the screenshot below.
This is because your video component is not stopping correctly.
Try adding:
VideoComponent vc;
Player player;
vc = VideoComponent.createVideoPeer("http://localhost/md.3gp");
player = (Player) vc.getNativePeer();
player.realize();
vc.start();
and in action listener:
player.stop();
vc.stop();
player.close();
loginform();

LWUIT and kXML Parser

Uncaught exception: java.lang.Error: Static initializer: java.lang.NullPointerException, 0
- java.lang.Class.throwError(), bci=57
- java.lang.Class.initialize(), bci=221
- com.sun.lwuit.Component.<init>(), bci=5
- com.sun.lwuit.Container.<init>(), bci=1
- com.sun.lwuit.Form.<init>(), bci=8
- com.sun.lwuit.Form.<init>(), bci=1
- com.midlet.RSSMidlet.<init>(), bci=11
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=9
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=4
- com.sun.midp.appmanager.SelectorBase.run(), bci=33
- java.lang.Thread.run(), bci=11
Coding:
package com.midlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
//import com.sun.lwuit.list.ListModel;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class RSSMidlet extends MIDlet implements ActionListener{
public Vector feedVector;
public String rssFeed;
private Command cmdSelect;
private Command cmdExit;
private Form form1 = new Form("Feeds List");
// private Form form2 = new Form("Feed Description");
// private Vector feed_Title;
private List resultList;
// private List feedTitle;
public RSSModel model = new RSSModel();
class ReadXML extends Thread{
public void run(){
try{
rssFeed = "http://www.rottentomatoes.com/syndication/rss/top_news.xml";
HttpConnection httpConnection = (HttpConnection) Connector.open(rssFeed);
KXmlParser parser = new KXmlParser();
parser.setInput(new InputStreamReader(httpConnection.openInputStream()));
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, null);
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "channel");
readXMLData(parser);
parser.require(XmlPullParser.END_TAG, null, "channel");
}
parser.require(XmlPullParser.END_TAG, null, "rss");
parser.next();
parser.require(XmlPullParser.END_DOCUMENT, null, null);
}catch(Exception e){
}
}
}
public RSSMidlet() {
// TODO Auto-generated constructor stub
Display.init(this);
Resources r;
try{
r = Resources.open("/LWUITtheme.res");
UIManager.getInstance().setThemeProps(r.getTheme("LWUITDefault"));
}catch(IOException e){
//e.printStackTrace();
}
resultList = new List();
for(int i=0; i<feedVector.size();i++){
model = (RSSModel) feedVector.elementAt(i);
resultList.addItem(model.getTitle().toString());
}
form1.addComponent(BorderLayout.CENTER,resultList);
form1.addCommand(cmdExit);
form1.addCommand(cmdSelect);
form1.setScrollable(true);
//form1.addCommandListener((ActionListener) this);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
new ReadXML().start();
}
public void readXMLData(KXmlParser parser) throws IOException, XmlPullParserException{
while(!"item".equals(parser.getName()) ){
/** Check if document doesn't include any item tags */
if( parser.next() == XmlPullParser.END_DOCUMENT )
throw new IOException("No items in RSS feed!");
}
parser.require(XmlPullParser.START_TAG, null, "item");
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.require(XmlPullParser.START_TAG, null, null);
String name = parser.getName();
String text = parser.nextText();
//System.out.println ("<"+name+">"+text);
if(name.equals("pubDate")){
model.setPubDate(text);
}else if(name.equals("title")){
model.setTitle(text);
}else if(name.equals("link")){
model.setLink(text);
}else if(name.equals("description")){
model.setDescription(text);
}
parser.require(XmlPullParser.END_TAG, null, name);
}
feedVector.addElement(model);
parser.require(XmlPullParser.END_TAG, null, "item");
}
public void actionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
if(evt.getCommand() == cmdExit){
notifyDestroyed();
}else if(evt.getCommand() == cmdSelect){
}
}
}
This is my codes. I can't seem to get LWUIT running with kXML. There is a forum post that says that I need to initialize graphics objects after the Display.init(this) line. But where that line should lie? Please assist me...
The Display.init(your_midlet) is responsible for initializing the Display for LWUIT, no need to do it yourself. Only restriction is, you have to initialize the Display BEFORE you use any Form.
Move the line
form1 = new Form("Feeds List")
after the line
Display.init(this);
so you initialize the Form in the Constructor after initializing the Display!

Resources