J2me synchronization of methods - java-me

I initializing a variable in my startApp method and after I do so I call a thread to check the whole run time of the app what is the current screen (canvas) and activating it's thread
import java.io.IOException;
import java.io.InputStream;
import zuma.core.MyGameCanvas;
import zuma.core.Game;
import zuma.gui.LevelSelectionMenu;
import zuma.gui.MainMenu;
import javax.microedition.lcdui.Display;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.midlet.*;
import zuma.util.AudioManager;
public class Midlet extends MIDlet implements Runnable{
private static Display display;
private static Game game;
private static MainMenu mainMenu;
private static LevelSelectionMenu levelSelectionMenu;
private static MyGameCanvas myGameCanvas;
private Thread t;
/**
* Specifies what happens when starting the application.
*/
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(getMainMenu());
t = new Thread(this);
t.start();
}
/**
* Specifies what happens when pausing the application.
*/
public void pauseApp() {
}
/**
* Specifies what happens when exiting the application.
* #param unconditional
*/
public void destroyApp(boolean unconditional) {
//game.getLevelsRecordStore().closeRecordStore();
notifyDestroyed();
}
/**
*
* #return the display.
*/
public static Display getDisplay() {
return display;
}
/**
*
* #return the game.
*/
public static Game getGame() {
if (game == null) { //|| game.getLevels() == null) {
game = new Game();
}
return game;
}
/**
*
* #return the mainMenu.
*/
public static synchronized MainMenu getMainMenu() {
if (mainMenu == null) {
mainMenu = new MainMenu();
}
return mainMenu;
}
/**
*
* #return the levelSelectionMenu.
*/
public static LevelSelectionMenu getLevelSelectionMenu() {
if (levelSelectionMenu == null) {
levelSelectionMenu = new LevelSelectionMenu(getGame());
}
return levelSelectionMenu;
}
/**
*
* #return the myGameCanvas.
*/
public static MyGameCanvas getMyGameCanvas() {
if (myGameCanvas == null) {
myGameCanvas = new MyGameCanvas();
}
return myGameCanvas;
}
/**
* Starts the thread of the current display.
*/
public synchronized void run() {
while (true) {
if (display.getCurrent().equals(mainMenu)) {
if (mainMenu.getT() == null || !mainMenu.getT().isAlive()) {
mainMenu.init();
}
if (getMainMenu().isQuitRequest()) {
destroyApp(true);
}
}
else if (display.getCurrent().equals(levelSelectionMenu)) {
if (levelSelectionMenu.getT() == null || !levelSelectionMenu.getT().isAlive()) {
levelSelectionMenu.init();
}
}
else if (display.getCurrent().equals(myGameCanvas)) {
if (myGameCanvas.getT() == null || !myGameCanvas.getT().isAlive()) {
myGameCanvas.init(game.getLevels()[game.getChosenLevel()]);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
Now as you can see I first init the variable mainMenu in this line
display.setCurrent(getMainMenu());
and only then call run method, but somehow SOMETIMES it gives me null pointer exception on this line
if (display.getCurrent().equals(mainMenu))
so somehow the thread is getting called even before the mainMenu is being created and I have no idea how, what I tried is making the run method and the getMainMenu methos synchronized but it didnt work, can anyone help me ?

The thread is not getting called before the main menu is created. After setCurrent is called, there is actually a delay before the displayable is made visible. The doc says: "The setCurrent() method returns immediately, without waiting for the change to take place. Because of this delay, a call to getCurrent() shortly after a call to setCurrent() is unlikely to return the value passed to setCurrent()."

Related

Read specific sheet using spring batch?

What is the way of reading a specific sheet from an Excel file using spring-batch-excel?
Specifically, I want to parse different sheets within an Excel file in a different manner, using a org.springframework.batch.item.excel.poi.PoiItemReader.
I can't see how to do this with the PoiItemReader, in that is appears to read each sheet in the document. Is there a way to handle sheets differently in the row mapper perhaps? Is it possible without writing a custom POI reader?
No way with out writing custom reader
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.batch.extensions.excel.Sheet;
import org.springframework.lang.Nullable;
public class PoiSheet implements Sheet {
private final DataFormatter dataFormatter = new DataFormatter();
private final org.apache.poi.ss.usermodel.Sheet delegate;
private final int numberOfRows;
private final String name;
private FormulaEvaluator evaluator;
/**
* Constructor which takes the delegate sheet.
* #param delegate the apache POI sheet
*/
PoiSheet(final org.apache.poi.ss.usermodel.Sheet delegate) {
super();
this.delegate = delegate;
this.numberOfRows = this.delegate.getLastRowNum() + 1;
this.name = this.delegate.getSheetName();
}
/**
* {#inheritDoc}
*/
#Override
public int getNumberOfRows() {
return this.numberOfRows;
}
/**
* {#inheritDoc}
*/
#Override
public String getName() {
return this.name;
}
/**
* {#inheritDoc}
*/
#Override
#Nullable
public String[] getRow(final int rowNumber) {
final Row row = this.delegate.getRow(rowNumber);
return map(row);
}
#Nullable
private String[] map(Row row) {
if (row == null) {
return null;
}
final List<String> cells = new LinkedList<>();
final int numberOfColumns = row.getLastCellNum();
for (int i = 0; i < numberOfColumns; i++) {
Cell cell = row.getCell(i);
CellType cellType = cell.getCellType();
if (cellType == CellType.FORMULA) {
cells.add(this.dataFormatter.formatCellValue(cell, getFormulaEvaluator()));
}
else {
cells.add(this.dataFormatter.formatCellValue(cell));
}
}
return cells.toArray(new String[0]);
}
/**
* Lazy getter for the {#code FormulaEvaluator}. Takes some time to create an
* instance, so if not necessary don't create it.
* #return the {#code FormulaEvaluator}
*/
private FormulaEvaluator getFormulaEvaluator() {
if (this.evaluator == null) {
this.evaluator = this.delegate.getWorkbook().getCreationHelper().createFormulaEvaluator();
}
return this.evaluator;
}
#Override
public Iterator<String[]> iterator() {
return new Iterator<String[]>() {
private final Iterator<Row> delegateIter = PoiSheet.this.delegate.iterator();
#Override
public boolean hasNext() {
return this.delegateIter.hasNext();
}
#Override
public String[] next() {
return map(this.delegateIter.next());
}
};
}
}
Excel Reader
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.batch.extensions.excel.AbstractExcelItemReader;
import org.springframework.batch.extensions.excel.Sheet;
import org.springframework.core.io.Resource;
public class ExcelSheetItemReader <T> extends AbstractExcelItemReader<T> {
private Workbook workbook;
private InputStream inputStream;
private int sheetIndex = 0;
#Override
protected Sheet getSheet(final int sheet) {
return new PoiSheet(this.workbook.getSheetAt(sheetIndex));
}
#Override
protected int getNumberOfSheets() {
return 1;
}
#Override
protected void doClose() throws Exception {
super.doClose();
if (this.inputStream != null) {
this.inputStream.close();
this.inputStream = null;
}
if (this.workbook != null) {
this.workbook.close();
this.workbook = null;
}
}
/**
* Open the underlying file using the {#code WorkbookFactory}. Prefer {#code File}
* based access over an {#code InputStream}. Using a file will use fewer resources
* compared to an input stream. The latter will need to cache the whole sheet
* in-memory.
* #param resource the {#code Resource} pointing to the Excel file.
* #param password the password for opening the file
* #throws Exception is thrown for any errors.
*/
#Override
protected void openExcelFile(final Resource resource, String password) throws Exception {
try {
File file = resource.getFile();
this.workbook = WorkbookFactory.create(file, password, false);
}
catch (FileNotFoundException ex) {
this.inputStream = resource.getInputStream();
this.workbook = WorkbookFactory.create(this.inputStream, password);
}
this.workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
}
public int getSheetIndex() {
return sheetIndex;
}
public void setSheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
}
}
Another example can be found here

How do I implement JavaFX in existing WindowBuilder project ?

I am trying to get my head around the JavaFX stuff...
My program is a WindowBuilder based Gui, and I want a JavaFX graph, and a JavaFX live video-feed displayed in my app.
How do I implement it in my code? I have tried this, but I couldn't get it runnning.
The data feed isnt the problem. I just need to view it inside my JFrame as small squares...
Confused now :(
Here is my code: (I am sorry that it is a tad long, but I blame the examplecode from JavaFX :p
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Canvas;
import java.awt.SystemColor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import javax.swing.UIManager.*;
/**
* #author
*
*/
public class MyClientApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static final String BufferedWriter = null;
JFrame frame;
private JTextField textFieldUsername;
/**
* Create the application.
*/
public MyClientApp(BufferedWriter serverDataOut, BufferedReader serverDataIn) {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #param serverDataOut
*
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// Nimbus Theme not avaliable
}
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("*********** My Program ***********");
frame.setBounds(320, 130, 730, 570);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Canvas canvasTemp = new Canvas();
canvasTemp.setBackground(SystemColor.window);
canvasTemp.setBounds(6, 277, 380, 255);
frame.getContentPane().add(canvasTemp);
Canvas canvasLevel = new Canvas();
canvasLevel.setBackground(SystemColor.window);
canvasLevel.setBounds(6, 10, 380, 255);
frame.getContentPane().add(canvasLevel);
}
public JFrame frame() {
return frame;
}
}
And here is the main file to get it running for you guys... :
Client.java
import java.io.IOException;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
MyClientApp window = new MyClientApp(null, null);
window.frame.setVisible(true);
}
}
The code I want to implement is:
AdvancedLineChartSample.java (from JavaFX)
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.util.Duration;
/**
* An advanced line chart with a variety of actions and settable properties.
*
* #see javafx.scene.chart.LineChart
* #see javafx.scene.chart.Chart
* #see javafx.scene.chart.NumberAxis
* #see javafx.scene.chart.XYChart
*/
public class AdvancedLineChartSample extends Application {
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
}
protected LineChart<Number, Number> createChart() {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<Number,Number> lc = new LineChart<Number,Number>(xAxis,yAxis);
// setup chart
lc.setTitle("Temp Chart");
xAxis.setLabel("tid");
yAxis.setLabel("temp");
// add starting data
XYChart.Series<Number,Number> series = new XYChart.Series<Number,Number>();
series.setName("Dataset 1");
series.getData().add(new XYChart.Data<Number,Number>(20d, 50d));
series.getData().add(new XYChart.Data<Number,Number>(40d, 80d));
series.getData().add(new XYChart.Data<Number,Number>(50d, 90d));
series.getData().add(new XYChart.Data<Number,Number>(70d, 30d));
series.getData().add(new XYChart.Data<Number,Number>(170d, 122d));
lc.getData().add(series);
return lc;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
and the StreamingMediaPlayer.java (from JavaFX):
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.animation.ParallelTransition;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
/**
* A media player with controls for play, pause, stop, seek, and volume. This media player is playing media via HTTP Live Streaming, also known as HLS.
*
* #see javafx.scene.media.MediaPlayer
* #see javafx.scene.media.Media
*/
public class StreamingMediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/JavaRap/prog_index.m3u8";
private MediaPlayer mediaPlayer;
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
mediaPlayer.setAutoPlay(true);
PlayerPane playerPane = new PlayerPane(mediaPlayer);
playerPane.setMinSize(480, 360);
playerPane.setPrefSize(480, 360);
playerPane.setMaxSize(480, 360);
// getStylesheets().add("ensemble/samples/media/OverlayMediaPlayer.css");
root.getChildren().add(playerPane);
}
public void play() {
Status status = mediaPlayer.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED) {
return;
}
if (status == Status.PAUSED || status == Status.STOPPED || status == Status.READY) {
mediaPlayer.play();
}
}
#Override public void stop() {
mediaPlayer.stop();
}
static class PlayerPane extends BorderPane {
private MediaPlayer mp;
private MediaView mediaView;
private final boolean repeat = false;
private boolean stopRequested = false;
private boolean atEndOfMedia = false;
private Duration duration;
private Slider timeSlider;
private Label playTime;
private Slider volumeSlider;
private HBox mediaTopBar;
private HBox mediaBottomBar;
private ParallelTransition transition = null;
#Override protected void layoutChildren() {
if (mediaView != null && getBottom() != null) {
mediaView.setFitWidth(getWidth());
mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
}
super.layoutChildren();
if (mediaView != null) {
mediaView.setTranslateX((((Pane)getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
mediaView.setTranslateY((((Pane)getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
}
}
#Override protected double computeMinWidth(double height) {
return mediaBottomBar.prefWidth(-1);
}
#Override protected double computeMinHeight(double width) {
return 200;
}
#Override protected double computePrefWidth(double height) {
return Math.max(mp.getMedia().getWidth(), mediaBottomBar.prefWidth(height));
}
#Override protected double computePrefHeight(double width) {
return mp.getMedia().getHeight() + mediaBottomBar.prefHeight(width);
}
#Override protected double computeMaxWidth(double height) { return Double.MAX_VALUE; }
#Override protected double computeMaxHeight(double width) { return Double.MAX_VALUE; }
public PlayerPane(final MediaPlayer mp) {
this.mp = mp;
setId("player-pane");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() { };
mvPane.setId("media-pane");
mvPane.getChildren().add(mediaView);
setCenter(mvPane);
mediaTopBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaTopBar, Pos.CENTER);
mediaBottomBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaBottomBar, Pos.CENTER);
mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
updateValues();
}
});
mp.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
mp.pause();
stopRequested = false;
}
}
});
mp.setOnReady(new Runnable() {
public void run() {
duration = mp.getMedia().getDuration();
updateValues();
}
});
mp.setOnEndOfMedia(new Runnable() {
public void run() {
if (!repeat) {
stopRequested = true;
atEndOfMedia = true;
}
}
});
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
// Time label
Label timeLabel = LabelBuilder.create()
.text("Time")
.minWidth(Control.USE_PREF_SIZE)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(timeLabel);
// Time slider
timeSlider = SliderBuilder.create()
.id("media-slider")
.minWidth(240)
.maxWidth(Double.MAX_VALUE)
.build();
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position
if (duration != null) {
mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
}
updateValues();
}
}
});
HBox.setHgrow(timeSlider, Priority.ALWAYS);
mediaTopBar.getChildren().add(timeSlider);
// Play label
playTime = LabelBuilder.create()
.prefWidth(130)
.minWidth(50)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(playTime);
// Volume label
Label volumeLabel = LabelBuilder.create()
.text("Vol")
.textFill(Color.WHITE)
.minWidth(Control.USE_PREF_SIZE)
.build();
mediaTopBar.getChildren().add(volumeLabel);
// Volume slider
volumeSlider = SliderBuilder.create()
.id("media-slider")
.prefWidth(120)
.maxWidth(Region.USE_PREF_SIZE)
.minWidth(30)
.build();
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
}
});
volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
}
}
});
mediaTopBar.getChildren().add(volumeSlider);
setTop(mediaTopBar);
final EventHandler<ActionEvent> backAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.seek(Duration.ZERO);
}
};
final EventHandler<ActionEvent> stopAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.stop();
}
};
final EventHandler<ActionEvent> playAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.play();
}
};
final EventHandler<ActionEvent> pauseAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.pause();
}
};
final EventHandler<ActionEvent> forwardAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Duration currentTime = mp.getCurrentTime();
mp.seek(Duration.seconds(currentTime.toSeconds() + 5.0));
}
};
mediaBottomBar = HBoxBuilder.create()
.id("bottom")
.spacing(0)
.alignment(Pos.CENTER)
.children(
ButtonBuilder.create()
.id("back-button")
.text("Back")
.onAction(backAction)
.build(),
ButtonBuilder.create()
.id("stop-button")
.text("Stop")
.onAction(stopAction)
.build(),
ButtonBuilder.create()
.id("play-button")
.text("Play")
.onAction(playAction)
.build(),
ButtonBuilder.create()
.id("pause-button")
.text("Pause")
.onAction(pauseAction)
.build(),
ButtonBuilder.create()
.id("forward-button")
.text("Forward")
.onAction(forwardAction)
.build()
)
.build();
setBottom(mediaBottomBar);
}
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration. greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
}
if (!volumeSlider.isValueChanging()) {
volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
}
}
});
}
}
private static String formatTime(Duration elapsed, Duration duration) {
int intElapsed = (int)Math.floor(elapsed.toSeconds());
int elapsedHours = intElapsed / (60 * 60);
if (elapsedHours > 0) {
intElapsed -= elapsedHours * 60 * 60;
}
int elapsedMinutes = intElapsed / 60;
int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;
if (duration.greaterThan(Duration.ZERO)) {
int intDuration = (int)Math.floor(duration.toSeconds());
int durationHours = intDuration / (60 * 60);
if (durationHours > 0) {
intDuration -= durationHours * 60 * 60;
}
int durationMinutes = intDuration / 60;
int durationSeconds = intDuration - durationHours * 60 * 60 - durationMinutes * 60;
if (durationHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
}
}
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args);
}
}
I'm sorry about the long code. Its just the samplecode from JavaFX. You find it here, and here.
That should be quite easy to solve. Let me explain it with the chart example that you've shown.
Add an instance of JFXPanel to your JFrame. In your examples, all components are added to a Stage, which is the JavaFX class to represent a window. So you don't need it here. Instead, you add the components that you want to use to the JFXPanel. See also here (function initAndShowGUI) how to do it.
In the init function of the example, a Scene is created as well as the chart itself. What you have to do to let the chart be shown is not much more than that - create a Scene, fill it with content and pass it to the JFXPanel that you already created.
With a minimum effort you can make your chart example run: Make sure that AdvancedLineChartSample.java is in your build path and that the function createChart is somehow accessible from your JFrame. Then add the chart to your code with something similar to the following snippet.
Group root=new Group();
Scene scene=new Scene(root);
myJFXPanel.setScene(scene);
root.getChildren().add(createChart());
This is just a very quick and dirty solution to run your example without any beautiful code and also I didn't test it. But hopefully it gives you a basic understanding of what's going on to encourage further experiments. By my own experience I can tell you that from this step on, there's a lot of fun to come with JavaFX 2.

Dialling a phone number by platformrequest

I have tried for two days to write a code that dial a phone number , but I failed
I have written a midlet and a form called main as a Displayable the form contains a textfield and
command .
When the application starts up the form should appears and calls the dialed number written in
textField when the command pressed.
the dialing process didn't work with me .
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Displayable.*;
import javax.microedition.lcdui.Form.*;
import javax.microedition.midlet.MIDlet;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class DiallNumber extends MIDlet implements CommandListener
{
String num;
private Form main;
private Command call,dial;
private TextField phoneField;
Display display;
public DiallNumber()
{
main = new Form("main");
phoneField = new TextField("label","",10,phoneField.PHONENUMBER);
call = new Command("call",call.OK,0);
main.append(phoneField);
main.addCommand(call);
num=this.phoneField.getString().trim();
main.setCommandListener(this);
}
/**}
* From MIDlet. Called when the MIDlet is started.
*/
public void startApp()
{
// The initial display is the first form
display = Display.getDisplay(this);
display.setCurrent(main);
}
public void call( String number) {
try {
platformRequest("tel:"+number);
} catch (ConnectionNotFoundException ex) {
// TODO: Exception handling
}
}
public void commandAction(Command c, Displayable d){
if(d==main)
{
if(c==call)
call(""+num);
}
}
public void pauseApp()
{
// No implementation required
}
/*
* /
*/
/**
* From MIDlet. Called to signal the MIDlet to terminate.
*
* #param unconditional
* whether the MIDlet has to be unconditionally terminated
*/
public void destroyApp(boolean unconditional)
{
// No implementation required
}
/**
* From CommandListener. Called by the system to indicate that a command has
* been invoked on a particular displayable.
*
* #param command
* the command that was invoked
* #param displayable
* the displayable where the command was invoked
*/
}
My log trace
Copying 1 file to C:\Users\ELHADI\Documents\NetBeansProjects\DiallNumber2\dist\nbrun5217990045006831680
Copying 1 file to C:\Users\ELHADI\Documents\NetBeansProjects\DiallNumber2\dist\nbrun5217990045006831680
Jad URL for OTA execution: http://localhost:8082/servlet/org.netbeans.modules.mobility.project.jam.JAMServlet/C%3A/Users/ELHADI/Documents/NetBeansProjects/DiallNumber2/dist//DiallNumber2.jad
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49320/DiallNumber2.jad
[WARN] [rms ] javacall_file_open: _wopen failed for: C:\Users\ELHADI\javame-sdk\3.0\work\0\appdb\_delete_notify.dat
I have solved the problem
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Displayable.*;
import javax.microedition.lcdui.Form.*;
import javax.microedition.midlet.MIDlet;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class DiallNumber extends MIDlet
{
private Display display;
private MIDlet midlet;
Form f = new form("f");
/**}
* From MIDlet. Called when the MIDlet is started.
*/
public void startApp()
{
display = Display.getDisplay(this);
display.setCurrent(f);
}
public void pauseApp()
{
// No implementation required
}
/*
* /
*/
/**
* From MIDlet. Called to signal the MIDlet to terminate.
*
* #param unconditional
* whether the MIDlet has to be unconditionally terminated
*/
public void destroyApp(boolean unconditional)
{
// No implementation required
}
class form extends Form implements CommandListener
{
private Command call;
private TextField phoneField;
private String n;
public form(String title )
{
super(title);
call =new Command("call",call.OK,0);
this.phoneField =new TextField("number","",20,phoneField.PHONENUMBER);
addCommand(call);
append(this.phoneField);
this.setCommandListener(this);
}
public void commandAction(Command c,Displayable d)
{
if(c==call)
{
try
{
n=phoneField.getString().trim();
platformRequest("tel:"+n);
}
catch(javax.microedition.io.ConnectionNotFoundException e)
{e.printStackTrace();}
}
}
}
}

Not able to capture an image using Nokia Mobile but in Computer application works fine?

I am making an application in which user will be able to use camera, capture and save that image to C drive, and i am also able to perform all these when i use this application with my PC.
But whenever i use this application in mobile Like Nokia C2-01,02,03 i am only to view camera but not able to capture an image in short capture is not working while i use Mobile to run this App.
My Midlet code is below please see the problem and support me to capture image via Mobile also:-
public class CaptureAndSaveImage extends MIDlet implements CommandListener {
private Display display;
// Form where camera viewfinder is placed
private Form cameraForm;
// Command for capturing image by camera and saving it.
// Placed in cameraForm.
private Command cmdCapture;
// Command for exiting from midlet. Placed in cameraForm.
private Command cmdExit;
// Player for camera
private Player player;
// Video control of camera
private VideoControl videoControl;
// Alert to be displayed if error occurs.
private Alert alert;
/**
* Constructor.
*/
public CaptureAndSaveImage() {
InitializeComponents();
}
/**
* Initializes components of midlet.
*/
private void InitializeComponents() {
display = Display.getDisplay(this);
if(checkCameraSupport() == false) {
showAlert("Alert", "Camera is not supported!", null);
return;
}
try {
createCameraForm();
createCamera();
addCameraToForm();
startCamera();
} catch(IOException ioExc) {
showAlert("IO error", ioExc.getMessage(), null);
} catch(MediaException mediaExc) {
showAlert("Media error", mediaExc.getMessage(), null);
}
}
/**
* Creates and returns form where the camera control will be placed.
*/
private void createCameraForm() {
// Create camera form
cameraForm = new Form("Camera");
// Create commands for this form
cmdCapture = new Command("Capture", Command.OK, 0);
cmdExit = new Command("Exit", Command.EXIT, 0);
// Add commands to form
cameraForm.addCommand(cmdCapture);
cameraForm.addCommand(cmdExit);
// Set midlet as command listener for this form
cameraForm.setCommandListener(this);
}
/**
* Check camera support.
* #return true if camera is supported, false otherwise.
*/
private boolean checkCameraSupport() {
String propValue = System.getProperty("supports.video.capture");
return (propValue != null) && propValue.equals("true");
}
/**
* Creates camera control and places it to cameraForm.
* #throws IOException if creation of player is failed.
* #throws MediaException if creation of player is failed.
*/
private void createCamera() throws IOException, MediaException {
player = Manager.createPlayer("capture://video");
player.realize();
player.prefetch();
videoControl = (VideoControl)player.getControl("VideoControl");
}
/**
* Adds created camera as item to cameraForm.
*/
private void addCameraToForm() {
cameraForm.append((Item)videoControl.
initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null));
}
/**
* Start camera player
* #throws IOException if starting of player is failed.
* #throws MediaException if starting of player is failed.
*/
private void startCamera() throws IOException, MediaException {
if(player.getState() == Player.PREFETCHED) {
player.start();
}
}
/**
* Saves image captured by camera.
*/
private void captureAndSaveImage() {
FileConnection file = null;
OutputStream outStream = null;
try {
if(checkPngEncodingSupport() == false) {
throw new Exception("Png encoding is not supported!");
}
// Capture image
byte[] capturedImageData =
videoControl.getSnapshot("encoding=png");
// Get path to photos folder.
String dirPhotos = System.getProperty("fileconn.dir.photos");
if(dirPhotos == null) {
throw new Exception("Unable get photos folder name");
}
String fileName = dirPhotos + "CapturedImage.png";
// Open file
file = (FileConnection)Connector.open(fileName,
Connector.READ_WRITE);
// If there is no file then create it
if(file.exists() == false) {
file.create();
}
// Write data received from camera while making snapshot to file
outStream = file.openOutputStream();
outStream.write(capturedImageData);
showAlert("Info", "Image is saved in " + fileName, cameraForm);
} catch(IOException ioExc) {
showAlert("IO error", ioExc.getMessage(), cameraForm);
} catch(MediaException mediaExc) {
showAlert("Media error", mediaExc.getMessage(), cameraForm);
} catch(Exception exc) {
showAlert("Error", exc.getMessage(), cameraForm);
} finally {
// Try to close file
try {
if(outStream != null) {
outStream.close();
}
if(file != null) {
file.close();
}
} catch(Exception exc) {
// Do nothing
}
}
}
/**
* Checks png encoding support
* #return true if png encoding is supported false otherwise.
*/
private boolean checkPngEncodingSupport() {
String encodings = System.getProperty("video.snapshot.encodings");
return (encodings != null) && (encodings.indexOf("png") != -1);
}
/**
* From MIDlet.
* Signals the MIDlet that it has entered the Active state.
*/
public void startApp() {
if ( videoControl != null ) {
display.setCurrent(cameraForm);
}
}
/**
* From MIDlet.
* Signals the MIDlet to enter the Paused state.
*/
public void pauseApp() {
// TODO: pause player if it is running.
}
/**
* Performs exit from midlet.
*/
public void exitMIDlet() {
notifyDestroyed();
}
/**
* Shows alert with specified title and text. If next displayable is not
* specified then application will be closed after alert closing.
* #param title - Title of alert.
* #param message - text of alert.
* #param nextDisp - next displayable. Can be null.
*/
private void showAlert(String title, String message, Displayable nextDisp) {
alert = new Alert(title);
alert.setString(message);
alert.setTimeout(Alert.FOREVER);
if(nextDisp != null) {
display.setCurrent(alert, nextDisp);
} else {
display.setCurrent(alert);
alert.setCommandListener(this);
}
}
/**
* From MIDlet.
* Signals the MIDlet to terminate and enter the Destroyed state.
*/
public void destroyApp(boolean unconditional) {
if(player != null) {
player.deallocate();
player.close();
}
}
/**
* From CommandListener.
* Indicates that a command event has occurred on Displayable displayable.
* #param command - a Command object identifying the command.
* #param displayable - the Displayable on which this event has occurred.
*/
public void commandAction(Command command, Displayable displayable) {
// Handles "Capture image" command from cameraForm
if(command == cmdCapture) {
captureAndSaveImage();
}
// Handles "exit" command from forms
if(command == cmdExit) {
exitMIDlet();
}
// Handle "ok" command from alert
if(displayable == alert) {
exitMIDlet();
}
}
}
Maybe you should try to capture an OutOfMemoryError (better to catch Throwable which will catch it too instead of an Exception) in try-catch block at captureAndSaveImage()
Also you might want to see fileName to make sure it tries to save in proper directory
showAlert("fileName", fileName, this);
// Open file
In Your creatCamera method at where you are Creating Player with the use of manager class jst try Capture Mode instead of Video mode.
player = Manager.createPlayer("capture://image");
I have gone through same problem in nokia-c1.
And
byte[] capturedImageData = videoControl.getSnapshot(null);
by passing null argument in getSnapshot method you will get in return a default supported image formate of your device.

Trying to create a embedded web page on black berry and cannot set starting url

I’m trying to make an embedded web page on my blackberry app, and I'm having trouble setting the starting URL.
I can only set the URL when I do it from a callback from a TextField. When I try to do it after I push the new screen on, the app no longer works (it does nothing when you try to run it.
The code that works is the following:
protected boolean keyChar(char key, int status, int time)
{
if ( key == Characters.ENTER )
{
Application.getApplication().invokeLater( new Runnable()
{
public void run() {
//progressBar.reset("", 0, 100, 0);
browserField.requestContent(locationBar.getText().trim());
}
});
return true;
}
return super.keyChar(key, status, time);
}
When I try to set it automatically after everything is created, nothing happens when I run the app.
Code snippet
public MyApp()
{
pushScreen(new BrowserFieldScreen());
// if I have this here, the app will not open
Application.getApplication().invokeLater( new Runnable()
{
public void run() {
gBrowserField.requestContent("http://google.com");
}
});
}
The complete program:
package mypackage;
import java.util.Enumeration;
import java.util.Hashtable;
import net.rim.device.api.browser.field.ContentReadEvent;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldListener;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.GaugeField;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import org.w3c.dom.Document;
/**
* BrowserField2ProgressTracker
* - A BrowserField2 Mini-browser application that keeps track of page-loading progress
* and displays progress information to the user.
*/
public class MyApp extends UiApplication {
static BrowserField gBrowserField;
public static void main(String[] args){
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new BrowserFieldScreen());
/*
if I have this hear, the ap will not open
Application.getApplication().invokeLater( new Runnable() {
public void run() {
gBrowserField.requestContent("http://google.com");
}
});
}
*/
}
/**
* BrowserFieldScreen
* - A screen that contains a location bar, a progress bar, and a browser field
*/
class BrowserFieldScreen extends MainScreen {
// The location bar where URL will be typed in
private TextField locationBar;
// The BrowserField
private BrowserField browserField;
public BrowserFieldScreen() {
// progressTracker = new BrowserFieldLoadProgressTracker(10f);
createGUI();
}
private void createGUI() {
VerticalFieldManager mainManager = new VerticalFieldManager(Field.USE_ALL_WIDTH | Field.USE_ALL_HEIGHT | Manager.VERTICAL_SCROLLBAR | Manager.HORIZONTAL_SCROLLBAR );
locationBar = new TextField() {
protected boolean keyChar(char key, int status, int time) {
if ( key == Characters.ENTER ) {
Application.getApplication().invokeLater( new Runnable() {
public void run() {
//progressBar.reset("", 0, 100, 0);
browserField.requestContent(locationBar.getText().trim());
}
});
return true;
}
return super.keyChar(key, status, time);
}
};
locationBar.setBackground(BackgroundFactory.createSolidBackground(Color.BEIGE));
locationBar.setText("http://google.com");
browserField = new BrowserField();
MyApp.gBrowserField=browserField;
mainManager.add(locationBar);
mainManager.add(browserField);
add(mainManager);
}
}
I don't think you can call invokeLater() until your app, theApp has enter the main event thread. Which is done by calling theApp.enterEventDispatcher()
instead try changing your BrowserFieldScreen constructor to:
public BrowserFieldScreen() {
// progressTracker = new BrowserFieldLoadProgressTracker(10f);
createGUI();
browserField.requestContent("http://google.com");
}

Resources