TableView with different objects (javafx) - object

Im currently developing a application for watching who is responsible for different Patients, however i havent been able to solve how to fill a table with different object types.
Below is my code for my TableView controller. The TableView will end up with four different object typs, all will be retrieved from a database.
I want my table to hold Patient objects, User objects (responsible) and a RelationManager object.
Below is my code, if you need more of the code, please let me know :-).
package fird.presentation;
import fird.Patient;
import fird.RelationManager;
import fird.User;
import fird.data.DAOFactory;
import fird.data.DataDAO;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author SimonKragh
*/
public class KMAMainFrameOverviewController implements Initializable {
#FXML
private TextField txtCPRKMAMainFrame;
#FXML
private TableColumn<Patient, String> TableColumnCPR;
#FXML
private TableColumn<Patient, String> TableColumnFirstname;
#FXML
private TableColumn<Patient, String> TableColumnSurname;
#FXML
private TableColumn<User, String> TableColumnResponsible;
#FXML
private TableColumn<RelationManager, String> TableColumnLastEdited;
#FXML
private TableView<RelationManager> tblPatients;
#FXML
private Button btnShowHistory;
#FXML
private TableColumn<?, ?> TableColumnDepartment;
/**
* Initializes the controller clas #FXML private Button btnShowHistory;
*
* #FXML private TableColumn<?, ?> TableColumnDepartment; s.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// Start of logic for the KMAMainFrameOverviewController
DataDAO dao = DAOFactory.getDataDao();
TableColumnCPR.setCellValueFactory(new PropertyValueFactory<Patient, String>("CPR"));
TableColumnFirstname.setCellValueFactory(new PropertyValueFactory<Patient, String>("Firstname"));
TableColumnSurname.setCellValueFactory(new PropertyValueFactory<Patient, String>("Surname"));
TableColumnResponsible.setCellValueFactory(new PropertyValueFactory<User, String>("Responsible"));
TableColumnLastEdited.setCellValueFactory(new PropertyValueFactory<RelationManager, String>("Last Edited"));
ObservableList<RelationManager> relationData = FXCollections.observableArrayList(dao.getAllActiveRelations());
tblPatients.setItems(relationData);
tblPatients.getColumns().addAll(TableColumnCPR, TableColumnFirstname, TableColumnSurname, TableColumnResponsible, TableColumnLastEdited);
System.out.println(tblPatients.getItems().toString());
}
}
relationData is a RelationManager object returned. This object contains a User object, a Patient object and a Responsible object.
Best,
Simon.

The exact details of how you do this depend on your requirements: for example, for a given RelationManager object, do the User, Patient, or Responsible objects associated with it ever change? Do you need the table to be editable?
But the basic idea is that each row in the table represents some RelationManager, so the table type is TableView<RelationManager>. Each column displays a value of some type (call it S), so each column is of type TableColumn<RelationManager, S>, where S might vary from one column to the next.
The cell value factory is an object that specifies how to get from the RelationManager object to an observable value of type S. The exact way you do this depends on how your model classes are set up.
If the individual objects associated with a given RelationManager never change (e.g. the Patient for a given RelationManager is always the same), then it's pretty straightforward. Assuming you have the usual setup for Patient:
public class Patient {
private StringProperty firstName = new SimpleStringProperty(...);
public StringProperty firstNameProperty() {
return firstName ;
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
// etc etc
}
then you can just do
TableColumn<RelationManager, String> firstNameColumn = new TableColumn<>("First Name");
firstNameColumn.setCellValueFactory(new Callback<CellDataFeatures<RelationManager,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<RelationManager, String> data) {
return data.getValue() // the RelationManager
.getPatient().firstNameProperty();
}
});
If you are not using JavaFX properties, you can use the same fallback that the PropertyValueFactory uses, i.e.:
TableColumn<RelationManager, String> firstNameColumn = new TableColumn<>("First Name");
firstNameColumn.setCellValueFactory(new Callback<CellDataFeatures<RelationManager,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<RelationManager, String> data) {
return new ReadOnlyStringWrapper(data.getValue().getPatient().getFirstName());
}
});
but note that this won't update if you change the name of the patient externally to the table.
However, none of this will work if the patient object associated with the relation manager is changed (the cell will still be observing the wrong firstNameProperty()). In that case you need an observable value that changes when either the "intermediate" patient property or the firstNameProperty change. JavaFX has a Bindings API with some select(...) methods that can do this: unfortunately in JavaFX 8 they spew out enormous amounts of warnings to the console if any of the objects along the way are null, which they will be in a TableView context. In this case I would recommend looking at the EasyBind framework, which will allow you to do something like
firstNameColumn.setCellValueFactory( data ->
EasyBind.select(data.getValue().patientProperty())
.selectObject(Patient::firstNameProperty));
(EasyBind requires JavaFX 8, so you if you get to use it, you also get to use lambda expressions and method references :).)
In either case, if you want the table to be editable, there's a little extra work to do for the editable cells in terms of wiring editing commits back to the appropriate call to set a property.

Related

Is there a way to pass list of enums to step in cucumber 4.x and java

let's say I have example enum class
public enum Name { FIRST_NAME, LAST_NAME;}
and I have a such step
Then followed name types are listed:
| FIRST_NAME |
| LAST_NAME |
in which I want to pass List like
#Then("^followed name types are listed:$")
public void followedNameTypesAreListed(List<Name> nameTypes){...}
I'm currently migrating to cucumber 4.x and what i figured out is that i can register custom DataTableType like
typreRegistry.defineDataTableType(new DataTableType(Name.class,
(TableCellTransformer<Name>) Name::valueOf)
but doing it for every single enum class doesn't sound very efficient, isn't there any other way to handle list for any enum class?
One quick way to do this would be to us an object mapper as the default cell transformer. The object mapper will then be used in all situations where a cell is mapped to a single object and no existing data table type has been defined.
You could use jackson-databind for this.
In Cucumber v4:
package com.example.app;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.cucumber.core.api.TypeRegistry;
import io.cucumber.core.api.TypeRegistryConfigurer;
import java.util.Locale;
public class ParameterTypes implements TypeRegistryConfigurer {
private final ObjectMapper objectMapper = new ObjectMapper();
#Override
public Locale locale() {
return Locale.ENGLISH;
}
#Override
public void configureTypeRegistry(TypeRegistry typeRegistry) {
typeRegistry.setDefaultDataTableCellTransformer(objectMapper::convertValue);
}
}
And in v5:
package com.example.app;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.cucumber.java.DefaultDataTableCellTransformer;
import java.lang.reflect.Type;
public class DataTableSteps {
private final ObjectMapper objectMapper = new ObjectMapper();
#DefaultDataTableCellTransformer
public Object defaultTransformer(Object fromValue, Type toValueType) {
return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
}
}

Xpages: How to access database from CacheBean

I have a cacheBean called PCConfig in which I want to store references to databases, so I can access them in other Java methods.
Here is the relevant part of my cacheBean:
package com.scoular.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.XspOpenLogUtil;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewNavigator;
public class PCConfig implements Serializable {
private static final long serialVersionUID = 1L;
private static Database PCDataDB;
// #SuppressWarnings("unchecked")
private void initConfigData() {
try {
loadStatus();
loadGeoLocations();
loadModels();
loadDatabases();
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
public PCConfig() {
initConfigData();
}
//Getters
public static Database getPCDataDB() {
return PCDataDB;
}
public static void setPCDataDB(Database dataDB) {
PCDataDB = dataDB;
}
public static void loadDatabases() {
loadPCDataDB();
}
public static void loadPCDataDB() {
Session session = Factory.getSession();
PCConfig.PCDataDB = session.getDatabase(thisDB.getServer(),"scoApps\\PC\\PCData.nsf", false);
}
}
}
In a different java class I import the PCConfig class and try to use this method getPCDataDB(). I have also tried PCConfig.PCDataDB.
I always get the error null pointer exception.
What am I doing wrong?
public void loadByUnid(String unid) {
try {
Document doc = PCConfig.getPCDataDB().getDocumentByUNID(unid);
if (null == doc) {
System.out.println("Document not found");
} else {
loadValues(doc);
}
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
You call the static method getPCDataDB(). As it is static you don't need to instantiate the class. But, your private field Database PCDataDB is not initialized at this point. This only happens if you instantiate the class. That's why you get the null pointer exception.
I guess PCConfig is a managed bean. It would get instantiated automatically if you call a non-static method in SSJS. So, remove all static in your class and it should work. If you want to use the class in Java then instantiate the class before calling getPCDataDB():
PCConfig pcConfig = new PCConfig();
Document doc = pcConfig.getPCDataDB().getDocumentByUNID(unid);
It is not recommended to keep Domino objects as class fields (like your Database PCDataDB) as they are not serializable. They might get recycled over the time especially if the class object resides in a long life scope like application scope. It is better to keep the data itself in fields or in your case database's server name and path so that you can open the database again when you need it.
BTW private Database PCDataDB should be private Database pCDataDB. The convention is that only class names and interfaces start with a capital letter.
As Knut says, storing the database in your static class won't work. Normally you would need to store the server and the database path as separate variables. But since you're using the OpenNTF Domino API, you can take advantage of Database.getApiPath() , which returns a "metaReplicaID" - a combination of servername and replica ID. You can store that and you have a direct reference to where the database resides. You can then use session.getDatabase(metaReplicaID) to retrieve the database when required.

JavaFX Update progressbar in tableview from Task

I know Task has a method updateProgress, I would need to bind progressbar to task, however I cannot do that, as I do not have progressbar as an object.
My program has a TableView. Once user enters download url and clicks download new row created in the TableView. Row has some info and progressbar column. I then start a new thread - task. Where all download is being done and I need to update progress bar in that row somehow.
I tried binding SimpleDoubleProperty to the Task but it does not update progress bar...
James D solved this in Oracle JavaFX forum thread: Table cell progress indicator. I have just copied that solution into this answer.
The solution creates multiple tasks and monitors their progress via a set of progress bars in a TableView.
The original thread also includes a solution which uses ProgressIndicators in case you prefer those to ProgressBars.
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ProgressIndicator ;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ProgressBarTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ProgressBarTableCellTest extends Application {
#Override
public void start(Stage primaryStage) {
TableView<TestTask> table = new TableView<TestTask>();
Random rng = new Random();
for (int i = 0; i < 20; i++) {
table.getItems().add(
new TestTask(rng.nextInt(3000) + 2000, rng.nextInt(30) + 20));
}
TableColumn<TestTask, String> statusCol = new TableColumn("Status");
statusCol.setCellValueFactory(new PropertyValueFactory<TestTask, String>(
"message"));
statusCol.setPrefWidth(75);
TableColumn<TestTask, Double> progressCol = new TableColumn("Progress");
progressCol.setCellValueFactory(new PropertyValueFactory<TestTask, Double>(
"progress"));
progressCol
.setCellFactory(ProgressBarTableCell.<TestTask> forTableColumn());
table.getColumns().addAll(statusCol, progressCol);
BorderPane root = new BorderPane();
root.setCenter(table);
primaryStage.setScene(new Scene(root));
primaryStage.show();
ExecutorService executor = Executors.newFixedThreadPool(table.getItems().size(), new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
});
for (TestTask task : table.getItems()) {
executor.execute(task);
}
}
public static void main(String[] args) {
launch(args);
}
static class TestTask extends Task<Void> {
private final int waitTime; // milliseconds
private final int pauseTime; // milliseconds
public static final int NUM_ITERATIONS = 100;
TestTask(int waitTime, int pauseTime) {
this.waitTime = waitTime;
this.pauseTime = pauseTime;
}
#Override
protected Void call() throws Exception {
this.updateProgress(ProgressIndicator.INDETERMINATE_PROGRESS, 1);
this.updateMessage("Waiting...");
Thread.sleep(waitTime);
this.updateMessage("Running...");
for (int i = 0; i < NUM_ITERATIONS; i++) {
updateProgress((1.0 * i) / NUM_ITERATIONS, 1);
Thread.sleep(pauseTime);
}
this.updateMessage("Done");
this.updateProgress(1, 1);
return null;
}
}
}
Explanatory Text Based on Comment Questions
You only need to read this section if you are having difficulties understanding how the above code works and want to gain a deeper understanding of cell value and property connections.
There is no kind of binding here (at least I do not see).
The binding (or ChangeListener, which amounts to the same thing) is hidden behind the implementation of the PropertyValueFactory and the ProgressBarTableCell. Let's look at the relevant code:
TableColumn<TestTask, Double> progressCol = new TableColumn("Progress");
progressCol.setCellValueFactory(
new PropertyValueFactory<TestTask, Double>("progress")
);
progressCol.setCellFactory(
ProgressBarTableCell.<TestTask> forTableColumn()
);
The progressCol is defined to take a TestTask as the data row and extract a double value out of the test task property.
The cell value factory defines how the double value for the column is populated. It is defined based upon a PropertyValueFactory which takes the parameter "progress". This tells the property value factory to use JavaFX naming conventions and the Java reflection API to lookup relevant methods to retrieve the data from a TestTask instance. In this case it will invoke a method named progressProperty() on the TestTask instance to retrieve the ReadOnlyDoubleProperty reflecting the tasks progress.
As it states in it's documentation, the PropertyValueFactory is just short hand for the mess of code below, but the key fact is that it is returning an ObservableValue which the Table implementation can use to set the value of the cell as the cell changes.
TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>("First Name");
firstNameCol.setCellValueFactory(new Callback<CellDataFeatures<Person, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<Person, String> p) {
// p.getValue() returns the Person instance for a particular TableView row
return p.getValue().firstNameProperty();
}
});
OK, so now we have a cell's value being reflected to the double value of the task's progress whenever the task makes any progress. But we still need to graphically represent that double value somehow. This is what the ProgressBarTableCell does. It is a table cell which contains a progress bar. The forTableColumn method creates a factory which produces the ProgressBarTableCells for each non-empty row in the column and sets the progress bar's progress to match the cell value which has been linked to the task's progress property by the PropertyValueFactory.
Confusing in understanding the detailed implementation . . . sure. But these high level helper factories and cells take care of a lot of the low level linkage details for you so that you don't need to code them over and over and from a plain API usage point of view it is (hopefully) simple and logical.
Also there is no properties (like SimpleStringProperty etc.) so the question would be, what if I need like two more columns with SimpleStringProperty, how do I add them to this kind of TableView?
Use the PropertyValueFactory once again. Let's image you have a string property called URL, then you can add the columns like this:
TableColumn<TestTask, Double> urlCol = new TableColumn("URL");
urlCol.setCellValueFactory(
new PropertyValueFactory<TestTask, Double>("url")
);
Note we only needed to set the cell value factory, this is because the default cell factory for the column will return a cell containing a label which directly displays the string value of the cell.
Now for the above to work correctly we need a method on TestTask which provides a url for the task, for example:
final ReadOnlyStringWrapper url = new ReadOnlyStringWrapper();
public TestTask(String url) {
this.url.set(url);
}
public ReadOnlyStringProperty urlProperty() {
return url.getReadOnlyProperty()
}
Note that the naming convention is really important here, it must be urlProperty() it can't be anything else or the PropertyValueFactory won't find the property value accessor.
Note for these purposes, a simple String value with a getUrl() would have worked just as well as a property as a PropertyValueFactory will work with a getter as well as a property method. The only advantage of using a property method is that it allows the table value data to update automatically based on property change events, which is not possible with a straight getter. But here because the url is effectively final and doesn't change for a given task, it doesn't make a difference whether a getter or property method is provided for this file from the task.

xe:objectData - Object has been removed or recycled

I use an xe:objectData as a datasource for a xp:dataTable. objectData1 uses some Java code to retrieve all documents from a view that match a key ( username ). The Java code looks like this:
package com.isatweb.cois;
import static com.ibm.xsp.extlib.util.ExtLibUtil.getCurrentDatabase;
import static com.ibm.xsp.extlib.util.ExtLibUtil.getCurrentSession;
import java.io.Serializable;
import lotus.domino.Database;
import lotus.domino.Name;
import lotus.domino.Session;
import lotus.domino.View;
import lotus.domino.ViewEntryCollection;
public class ObjectDataVisits implements Serializable {
private static final long serialVersionUID = 1L;
ViewEntryCollection vec = null;
public ObjectDataVisits(){
try {
this.update();
} catch (Exception e) {
System.out.print(e);
}
}
public void update() {
try {
Database _db = getCurrentDatabase();
Session _session = getCurrentSession();
Name nam = _session.createName(_session.getEffectiveUserName());
String username = nam.getAbbreviated().replace(" ", "#").replace("/", "#").toUpperCase();
View view = _db.getView("vw_visit_open");
this.vec = view.getAllEntriesByKey(username);
} catch (Exception e) {
System.out.print(e);
}
}
public ViewEntryCollection getVisits(){
return this.vec;
}
}
The XPage has the following code
When I first load the page, the data is read from the wiew and the dataTable displays the NoteIDs of all matching documents.
When I refresh the page using the button, I get an "Object has been removed or recycled" error.
Can anyone pls. show me what I'm doing wrong? ( and perhaps, how to do it right )
The problem is, that Notes objects are not serializable. During the partial refresh the getVisits() method is executed before the update() method. The ViewEntryCollection is a references to a view, and this view is already recycled.
If you just want to store some note id's then you could store them in a Vector instead. Otherwise you have to call your update() method in your getVisits() method everytime.

How do I get input from a user using j2me canvases? is this even possible?

I am currently trying to learn J2ME and build a connect four game (some of you might know this as 'four in a row'). I've More or less got all of the aspects of my game working, apart from one thing that is driving me mad! This is of course getting the text from the user!
For the two player mode of the game I want to be able to allow each player to enter their name. I am struggling to find a working example of text input that doesn't use the main Midlet.
For example the examples on java2x.com just use a single midlet (no classes or canvases or anything).
As it stands my application's main midlet start method simply opens a main menu class:
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
public void startApp() {
MainMenu mm = new MainMenu();
showScreen(mm);
}
public static void showScreen(Displayable screen) {
Display.getDisplay(instance).setCurrent(screen);
}
public void pauseApp() {
}
public static void quitApp() {
instance.notifyDestroyed();
}
public void destroyApp(boolean unconditional) {
}
}
The main menu class is as follows:
package view;
import javax.microedition.lcdui.*;
import lang.*;
import model.*;
import midlet.Main;
public class MainMenu extends List implements CommandListener {
private Command ok = new Command(StringDefs.currDefs.getString("TEXT_OK"), Command.OK, 1);
public MainMenu() {
super(StringDefs.currDefs.getString("TEXT_TITLE"), List.IMPLICIT);
// we we add in the menu items
append(StringDefs.currDefs.getString("TEXT_PLAY1"), null);
append(StringDefs.currDefs.getString("TEXT_PLAY2"), null);
append(StringDefs.currDefs.getString("TEXT_HIGHSCORETABLE"), null);
append(StringDefs.currDefs.getString("TEXT_HELP"), null);
append(StringDefs.currDefs.getString("TEXT_QUIT"), null);
this.addCommand(ok);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == ok) {
int selectedItem = this.getSelectedIndex();
if (selectedItem != -1) {
switch (selectedItem) {
case 0:
GameBoard gameBoard = new model.GameBoard();
GameCanvasOnePlayer board = new GameCanvasOnePlayer(gameBoard);
Main.showScreen(board);
break;
case 1:
GameBoard gameBoardTwo = new model.GameBoard();
GameCanvasTwoPlayer GameCanvasTwoPlayer = new GameCanvasTwoPlayer(gameBoardTwo);
Main.showScreen(GameCanvasTwoPlayer);
break;
case 2:
HighScores hc = new HighScores();
midlet.Main.showScreen(hc);
break;
case 3:
Help he = new Help();
midlet.Main.showScreen(he);
break;
case 4:
QuitConfirmation qc = new QuitConfirmation();
midlet.Main.showScreen(qc);
break
}
}
}
}
}
When a two player game is selected (case 1 in the above switch) from this menu I would like two text boxes to appear so that I can get both player names and store them.
What would be the best way of going about this? is this even possible with canvases? And do you know where I can find a relevant example or at least something which may help?
You can either:
1. Make the user enter his input in an ugly Textbox (which takes the whole screen)
2. Use the textbox control I've written from scratch a long time ago which is available here
and looks something like this (3 Textfields shown):
I've got a solution! well sort of.
I can create a form without using the main midlet:
The following main class is part of a source package called midlet (much like in my project):
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
private static UsernameForm unameForm=new UsernameForm();
private static MIDlet instance;
public void startApp() {
instance=this;
showScreen(unameForm); // show user name form
}
public static String getUsername1() {
return(unameForm.getUsername1());
}
public static String getUsername2() {
return(unameForm.getUsername2());
}
public void pauseApp() {
}
public static void showScreen(Displayable d) {
Display.getDisplay(instance).setCurrent(d); // show next screen
}
public void destroyApp(boolean unconditional) {
}
}
The next bit of code is the username form class that is part of a source package called view:
package view;
import javax.microedition.lcdui.*;
public class UsernameForm extends Form implements CommandListener {
private String username1="";
private String username2="";
private TextField tfUsername1=new javax.microedition.lcdui.TextField("User 1","User1",40,TextField.ANY);
private TextField tfUsername2=new javax.microedition.lcdui.TextField("User 2","User2",40,TextField.ANY);
private Command cmdOK=new Command("OK",Command.OK,1);
public UsernameForm() {
super("User details");
append(tfUsername1);
append(tfUsername2);
addCommand(cmdOK);
setCommandListener(this);
}
public void commandAction(Command cmd,Displayable d) {
if (cmd==cmdOK) {
this.setUsername1(tfUsername1.getString());
this.setUsername2(tfUsername2.getString());
// TO DO, GO TO NEXT SCREEN
}
}
/**
* #return the username1
*/
public String getUsername1() {
return username1;
}
/**
* #param username1 the username1 to set
*/
public void setUsername1(String username1) {
this.username1 = username1;
}
/**
* #return the username2
*/
public String getUsername2() {
return username2;
}
/**
* #param username2 the username2 to set
*/
public void setUsername2(String username2) {
this.username2 = username2;
}
}
So it looks like there's no easy way of doing it using canvases, I think I am better of using 'ugly forms' instead as they should work whatever the device.
That's a really sticky situation. Basically you will need to use J2ME's input text widget (which by the way looks horrible). If you don't, you'll end up having to implement all the logic behind the different types of phone keyboards and you won't have access to the dictionary... Your canvas will basically only be capturing keystrokes, not text input...
Sorry.
Here you need to, implement custom Items, all you need to do is to extend the part of the canvas where to want the user/player to enter his/her name to the CustomItems, and implement the customItems predefined abstract methods, and write method for Key Strokes and that's available in the nokia forum. They have explained it pretty good. Check out the Nokia forum.

Resources