Validation in swt text - text

I would like to validate numbers input in text box.
I want the user to input only integer, decimal in the box between a maximum and minimum values.
How can I make sure of this?
Thank you.

Use a VerifyListener as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});

You can register a ModifyListener with the text control and use it to validate the number.
txt.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent event) {
String txt = ((Text) event.getSource()).getText();
try {
int num = Integer.parseInt(txt);
// Checks on num
} catch (NumberFormatException e) {
// Show error
}
}
});
You could also use addVerifyListener to prevent certain characters being entered. In the event passed into that method there is a "doit" field. If you set that to false it prevents the current edit.

Integer validation in SWT
text = new Text(this, SWT.BORDER);
text.setLayoutData(gridData);
s=text.getText();
this.setLayout(new GridLayout());
text.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
});

If you only want to allow Integer values you could use a Spinner instead of a text field.
For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing. Such partial expressions will give a NumberFormatException for Double.parseDouble(partialExpression)
Also see my answer at following related question:
How to set a Mask to a SWT Text to only allow Decimals

1.create a utill class implement verify listener
2.override verifytext method
3.implement your logic
4.create a object of utill class where you want to use verify listener (on text)
5.text.addverifylistener(utillclassobject)
Example :-
1. utill class:-
public class UtillVerifyListener implements VerifyListener {
#Override
public void verifyText(VerifyEvent e) {
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
2.use of verifylistener in other class
public class TestVerifyListenerOne {
public void createContents(Composite parent){
UtillVerifyListener listener=new UtillVerifyListener();
textOne = new Text(composite, SWT.BORDER);
textOne .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textOne .addVerifyListener(listener)
textTwo = new Text(composite, SWT.BORDER);
textTwo .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textTwo .addVerifyListener(listener);
}
}

text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
Text text = (Text) e.getSource();
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isValid = true;
try {
if(! "".equals(newS)){
Float.parseFloat(newS);
}
} catch (NumberFormatException ex) {
isValid = false;
}
e.doit = isValid;
}
});

Related

text assigned to String attribute does not store properly

I have assigned a text from a txt file to three attributes, but whenever I call any of those attributes with a Get Method to another class, the value displayed is "null".
Furthermore, I have confirmed that these values are displayed in the method leerArchivo (whenever I use a println for m_linea1-2-3).
Please Help.
public class ArchivoCasillas
{
String m_linea1;
String m_linea2;
String m_linea3;
public void crearArchivo()
{
try
{
FileWriter fw = new FileWriter("ReglasDelTablero.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(fw);
bw.write("<7,0> , <0,0>");
bw.newLine();
bw.write("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>");
bw.newLine();
bw.write("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>");
bw.close();
}
catch(IOException e)
{
System.out.println("error");
}
}
public void leerArchivo()
{
String linea;
int i = 1;
try
{
FileReader fr = new FileReader("ReglasDelTablero.txt");
BufferedReader br = new BufferedReader(fr);
Tablero serpientesEscaleras = new Tablero();
while( (linea = br.readLine() ) != null)
{
switch(i)
{
case 1: m_linea1 = linea;
break;
case 2: m_linea2 = linea;
break;
case 3: m_linea3 = linea;
break;
}
i++;
}
br.close();
}
catch(IOException e)
{
}
}
public String getM_linea1()
{
return m_linea1;
}
}
Problem solved. It was a conceptual problem on my part. I created an Object in another class, but I never called the leerArchivo method with that object, therefore, the value of the attributes was null. Leaving an answer in case it's useful for someone in the future, as I didn't get a reply.

How to avoid java.util.NoSuchElementException

The code below is giving me the error java.util.NoSuchElementException right after I Ctrl+Z
to indicate that the user input is complete. By the looks of it seems as if it does not know how to just end one method without messing with the other scanner object.
I try the hasNext method and I ended up with an infinite loop, either way is not working. As a requirement for this assignment I need to be able to tell the user to use Ctrl+Z or D depending on the operating system. Also I need to be able to read from a text file and save the final tree to a text file please help.
/* sample input:
CSCI3320
project
personal
1 HW1
1 HW2
1 2 MSS.java
2 p1.java
*/
import java.util.Scanner;
import java.util.StringTokenizer;
public class Directory {
private static TreeNode root = new TreeNode("/", null, null);
public static void main(String[] args) {
userMenu();
System.out.println("The directory is displayed as follows:");
root.listAll(0);
}
private static void userMenu(){ //Displays users menu
Scanner userInput = new Scanner(System.in);//Scanner option
int option = 0;
do{ //I believe the problem is here since I am not using userInput.Next()
System.out.println("\n 1. add files from user inputs ");
System.out.println("\n 2. display the whole directory ");
System.out.println("\n 3. display the size of directory ");
System.out.println("\n 0. exit");
System.out.println("\n Please give a selection [0-3]: ");
option = userInput.nextInt();
switch(option){
case 1: addFileFromUser();
break;
case 2: System.out.println("The directory is displayed as follows:");
root.listAll(0);
break;
case 3: System.out.printf("The size of the directory is %d.\n", root.size());
break;
default:
break;
}
}while( option !=0);
userInput.close();
}
private static void addFileFromUser() {
System.out.println("To terminate inp1ut, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) { //hasNext being used Crtl Z is required to break
addFileIntoDirectory(input); // out of the loop.
}
input.close();
}
private static void addFileIntoDirectory(Scanner input) {
String line = input.nextLine();
if (line.trim().equals("")) return;
StringTokenizer tokens = new StringTokenizer(line);
int n = tokens.countTokens() - 1;
TreeNode p = root;
while (n > 0 && p.isDirectory()) {
int a = Integer.valueOf( tokens.nextToken() );
p = p.getFirstChild();
while (a > 1 && p != null) {
p = p.getNextSibling();
a--;
}
n--;
}
String name = tokens.nextToken();
TreeNode newNode = new TreeNode(name, null, null);
if (p.getFirstChild() == null) {
p.setFirstChild(newNode);
}
else {
p = p.getFirstChild();
while (p.getNextSibling() != null) {
p = p.getNextSibling();
}
p.setNextSibling(newNode);
}
}
private static class TreeNode {
private String element;
private TreeNode firstChild;
private TreeNode nextSibling;
public TreeNode(String e, TreeNode f, TreeNode s) {
setElement(e);
setFirstChild(f);
setNextSibling(s);
}
public void listAll(int i) {
for (int k = 0; k < i; k++) {
System.out.print('\t');
}
System.out.println(getElement());
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
t.listAll(i+1);
t = t.getNextSibling();
}
}
}
public int size() {
int s = 1;
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
s += t.size();
t = t.getNextSibling();
}
}
return s;
}
public void setElement(String e) {
element = e;
}
public String getElement() {
return element;
}
public boolean isDirectory() {
return getFirstChild() != null;
}
public void setFirstChild(TreeNode f) {
firstChild = f;
}
public TreeNode getFirstChild() {
return firstChild;
}
public void setNextSibling(TreeNode s) {
nextSibling = s;
}
public TreeNode getNextSibling() {
return nextSibling;
}
}
}
Exception Details:
/*Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Directory.userMenu(Directory.java:36)
at Directory.main(Directory.java:21)*/
Your problem is this line:
option = userInput.nextInt(); //line 24
If you read the Javadoc, you will find that the nextInt() method can throw a NoSuchElementException if the input is exhausted. In other words, there is no next integer to get. Why is this happening in your code? Because you this line is in a loop once that first iteration completes (on the outer while loop) your initial input selection has been consumed. Since this is a homework, I am not going to write the code. But, if you remove the loop, you know this works at least once. Once you try to loop, it breaks. So I will give you these hints:
Change the do/while to a while loop.
Prompt the user once outside the loop.
Recreate the prompt and recapture the user input inside the loop.
For example, the code below can be used for the basis of your outer loop.
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Guess the secret number: (Hint: the secret number is 1)");
int guess = input.nextInt();
while (guess != 1) {
System.out.println("Wrong guess. Try again: ");
guess = input.nextInt();
}
System.out.println("Success");
input.close();
}
}
The reason why this works is because I don't reuse the same, exhausted, scanner input object to get the next integer. In your example, the initial input is inside the loop. The second time around, that input has already been consumed. Follow this pattern and you should be able to complete your assignment.

I'm getting Resource Leaks

Whenever I run this code, it works pretty smoothly, until the while loop runs through once. It will go back and ask for the name again, and then skip String b = sc.nextLine();, and print the next line, instead.
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
Also, I'm trying to create this program in a way that I can ask three questions (like someone's Name, Gender, and Age, maybe more like race and whatnot), and then bring all of those answers back. Like, at the very end, say, "So, your name is + name +, you are + gender +, and you are + age + years old? Yes/No." Something along those lines. I know there's a way to do it, but I don't know how to save those responses anywhere, and I can't grab them since they only occur in the instance of the method.
Don't try to scan text with nextLine() AFTER using nextInt() with the same scanner! It may cause problems. Open a scanner method for ints only...it's recommended.
You could always parse the String answer of the scanner.
Also, using scanner this way is not a good practice, you could organize questions in array an choose a loop reading for a unique scanner instantiation like this:
public class a {
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
static Scanner sc ;
static public void main(String [] argv) {
Name();
}
static public void Name() {
sc = new Scanner(System.in);
String[] questions = {"Name?","Age","Sex?"};//
int a = 0;
System.out.println(questions[a]);
while (sc.hasNext()) {
input = sc.next();
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine " + InputName
+ " so you are " + Age + " years old and " + Sex + "." );
Age = null;
Sex = null;
InputName = null;
System.out.println("Loop again?");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
}
}
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
}
}
}
Pay attention on the global variables, wich stores your info until you set them null or empty...you could use them to the final affirmation.
Hope this helps!
Hope this helps!

How to edit data with dynamic TableView with dynamic column in JAVAFX

Today This is the demo to show data from CSV for DAT file without make custom class on tableView in JavaFX 2.0. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.
On my research about the editable on tableView we must have a custom class and implement it to tableView to show as this demo ==> http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
But in this case I can not do it because we don't know how many column example with csv file or .dat file.... I want to do editable on this tableView in this case by add TextField into TableCell. How does it do without make custom class (because you do not how many column ...), and if it must make custom class then how about the design of custom class for this case?
Could you please help me?
private void getDataDetailWithDynamic() {
tblView.getItems().clear();
tblView.getColumns().clear();
tblView.setPlaceholder(new Label("Loading..."));
// #Override
try {
File aFile = new File(txtFilePath.getText());
InputStream is = new BufferedInputStream(new FileInputStream(aFile));
Reader reader = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(reader);
final String headerLine = in.readLine();
final String[] headerValues = headerLine.split("\t");
for (int column = 0; column < headerValues.length; column++) {
tblView.getColumns().add(
createColumn(column, headerValues[column]));
}
// Data:
String dataLine;
while ((dataLine = in.readLine()) != null) {
final String[] dataValues = dataLine.split("\t");
// Add additional columns if necessary:
for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
tblView.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
tblView.getItems().add(data);
}
} catch (Exception ex) {
System.out.println("ex: " + ex.toString());
}
for(int i=0; i<tblView.getColumns().size(); i++) {
TableColumn col = (TableColumn)tblView.getColumns().get(i);
col.setPrefWidth(70);
}
}
private TableColumn createColumn(
final int columnIndex, String columnTitle) {
TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
System.out.println("event cell");
EditingCellData cellExtend = new EditingCellData();
return cellExtend;
}
};
column.setText(title);
column.setCellValueFactory(cellFactory);
return column;
}
Thanks for your reading.
This is the best way to resolve it ==> https://forums.oracle.com/message/11216643#11216643
I'm really thank for your reading about that.
Thanks

J2ME Login and Search Record Store

I'm new to J2ME and I'm taking a class where we use it. I created a simple travel reservation MIDlet using choice groups text fields etc. I then added a Record Store to capture this information. I now have a user login that only requires a user name, but i don't know how to verify that the user name is in the Record Store, so instead I accept any one as long as the Textfield for the user name is not empty. My first question is how would I verify that the user exist, I already can create an account. The second question is how can I search a record store not by id but say using a string within a certain range for each row of the Record store.
Here is my code so far:
$import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
/**
* #author XayBlu
*/
public class tripMe extends MIDlet implements CommandListener {
Form startForm, airForm, trainForm, cruiseForm, autoForm, Ext, Pass,home,login, create;
Command Exit, Trip, Cinfo, AutC,AiC,CrC, info,Tme,trainC, logC,signC, createC, prev, newTrip, Home;
ChoiceGroup trans,hCAP, passCNT,airT,airC,AuC,AuT,CrL,CcabT,Tseat,TOP;
Display Xdisplay;
TextField Eneed, uName, uName2;
Alert Final, FinalT, Sucess, nope;
DateField dDate, rDate;
Date d,r;
Image [] image;
String details =" ",tt="", Trav, Rdate, Ddate, extraA, Pcount,specialA, TT,AIR2, AIR,AUTO,AUTO2,CRUISE,CRUISE2,TRAIN,TRAIN2, USERS="USERS";
String op[] = {"Air","Auto","Cruise","Train"}; //Array Items for Choice Groups
String ep[] = {"Wheel Chair","Baby Seat","Extended Seatbelt","Extra Pillows","Oxygen Tank","GPS"};
String count[] = {"1","2","3","4","5","6","7","8"};
String AL []= {"American Airlines","Delta","US Airways","South West Airlines","United Airlines"};
String Rental [] = {"Alamo","Avis","Budget","Enteprise","Dollar","Hertz"};
String CL [] = {"Carnival","Norwegian","Royal Caribbean","Celebrity X","MSC"};
String CT [] = {"Compact","Standard","Full","SUV","Luxury","Sports"};
String Cabin [] = {"Suite","Ocean Balcony","Standard","Economy"};
String tCAB[] = {"Standard Seat","Sleeper Cart"};
String Toptions[] ={"Extra Luggage room","Salad Buffet","Wifi Access","Extra Blanket"};
RecordStore usr,itt;
RecordEnumeration recEnum = null;
RecordFilter filter = null;
int Umax=5;
int tran1 =6;
String last;
Byte [] data = new Byte[Umax];
/* NEW COMMANDS FOR FLEXIBLE USER INPUT TO RECORD STORES */
public void writeRecord(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void writeInfo(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, tran1, rec.length);
}catch (Exception e){}
}
public void updateRecord(String str){
try{
usr.setRecord(1, str.getBytes(), 0, str.length());
}catch (Exception e){}
}
public void deleteRecord(){
try{
usr.deleteRecord(1);
}catch (Exception e){}
}
public void closeRecord(){
try{
usr.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(USERS);
}catch (Exception e){}
}
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
usr = RecordStore.openRecordStore(USERS, true );
}
catch (Exception e)
{
System.out.print("Could not open record store");
}
}
public void readRecords()
{
try
{
// Intentionally make this too small to test code below
byte[] recData = new byte[5];
int len;
for (int i = 1; i <= usr.getNumRecords(); i++)
{
if (usr.getRecordSize(i) > recData.length)
recData = new byte[usr.getRecordSize(i)];
len = usr.getRecord(i, recData, 0);
home.append(new String(recData,0,len));
// System.out.println("Record #" + i + ": " + new String(recData, 0, len));
// System.out.println("------------------------------");
}
}
catch (Exception e)
{
nope = new Alert("Sorry no match!",null,null,AlertType.INFO);
nope.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(nope, login);
}
}
}
class Filter implements RecordFilter {
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String search) {
this.search = search.toLowerCase();
}
public void filterClose() {
try {
if (inputstream != null) {
inputstream.close();
}
if (datainputstream != null) {
datainputstream.close();
}
} catch (Exception error) {
}
}
}
public tripMe (){
try{ //Initializing individual images for Choice Group Icons
Image car = Image.createImage("/car2.png");
Image plane = Image.createImage("/plane2.png");
Image train = Image.createImage("/train2.png");
Image cruise = Image.createImage("/cruise2.png");
image = new Image[] {plane,car,cruise,train}; //Initializing Image array for ChoiceGroup
}
catch (java.io.IOException err) {System.out.print("Could not load pics"); } //Throws exception if pic cannot be found
startForm = new Form("Get Away Today"); //Initialization of forms
Pass = new Form ("Passenger Information");
airForm = new Form("Low Prices!");
autoForm = new Form("Find the best car for you");
Ext = new Form("Itinerary Details");
Ext.setTicker(new Ticker("Enjoy Your Vacation"));
cruiseForm = new Form("Sail Away Today");
trainForm = new Form("Chuuu- Chuuu");
login = new Form("Sign up Today");
home = new Form("Welcome Back");
create = new Form("Create an account");
trans = new ChoiceGroup("Select travel type",ChoiceGroup.EXCLUSIVE,op,image); //Transport tation choice group initialized with corresponding string and image array
Exit = new Command("Exit", Command.EXIT,1);//Adding necessary commands
Trip = new Command("Go", Command.SCREEN,2);//Adding go command which allows you to select travel type
signC = new Command("Sign up",Command.SCREEN,2);
logC = new Command("Log in",Command.SCREEN,2);
createC = new Command("OK",Command.SCREEN,2);
prev = new Command("History",Command.SCREEN,2);
newTrip = new Command("Reservations",Command.SCREEN,2);
Home = new Command("Log out",Command.SCREEN,1);
hCAP = new ChoiceGroup("Extra Assistance", ChoiceGroup.MULTIPLE,ep,null);//Passenger Info items
passCNT = new ChoiceGroup("Number of Passengers:",ChoiceGroup.POPUP,count,null);
rDate = new DateField("Return Date",DateField.DATE_TIME);//Could not get the DateField to return string date value
dDate = new DateField("Departure Date",DateField.DATE_TIME);
Eneed = new TextField("Special Needs","",50,TextField.ANY);
uName = new TextField("User Name","",5,TextField.ANY);
uName2 = new TextField("User Name","",5,TextField.ANY);
info = new Command("Next",Command.SCREEN,2);
AiC = new Command("Complete",Command.SCREEN,2);//Air travel option items
airT = new ChoiceGroup("Choose Airline", ChoiceGroup.POPUP,AL,null);//Airline selection
airC = new ChoiceGroup("Select Class",ChoiceGroup.EXCLUSIVE);//Economy or first cass?
airC.append("First Class", null);//Adding elements to Choice Group
airC.append("Economy", null);
AuC = new ChoiceGroup("Choose rental company", ChoiceGroup.POPUP,Rental,null);//Auto travel option items
AuT = new ChoiceGroup("Select Vehicle Type", ChoiceGroup.EXCLUSIVE, CT,null);//Choicegroup for Vehicle type
AutC = new Command("Drive away", Command.SCREEN,2);//Adding drive away command to form
CrL = new ChoiceGroup("Select Cruise Line Comp.", ChoiceGroup.POPUP,CL,null);//Cruise option Items, Cruise line choicegroup
CcabT = new ChoiceGroup("Select Cabin Type", ChoiceGroup.EXCLUSIVE,Cabin,null);//Cabin type choice group
CrC = new Command("Cruise", Command.SCREEN,2);//Cruise form command being added
trainC = new Command("Track!", Command.SCREEN,2);//Train option items, Train form command
Tseat = new ChoiceGroup("Seat Type", ChoiceGroup.EXCLUSIVE,tCAB,null);//Choicegroup for train seat type
TOP = new ChoiceGroup("Extra Options", ChoiceGroup.POPUP,Toptions,null);//Train extra options choice group
/* Appending Items to necessary Forms*/
create.append(uName2);
create.addCommand(createC);
create.setCommandListener(this);
home.addCommand(prev);
home.addCommand(newTrip);
home.setCommandListener(this);
login.append(uName);
login.addCommand(logC);
login.addCommand(signC);
login.setCommandListener(this);
startForm.append(trans);
startForm.addCommand(Exit);
startForm.addCommand(Trip);
startForm.setCommandListener(this);
Pass.append(dDate);
Pass.append(rDate);
Pass.append(hCAP);
Pass.append(passCNT);
Pass.append(Eneed);
Pass.addCommand(info);
Pass.setCommandListener(this);
airForm.append(airT);
airForm.append(airC);
airForm.addCommand(AiC);
airForm.setCommandListener(this);
autoForm.addCommand(AutC);
autoForm.append(AuC);
autoForm.append(AuT);
autoForm.setCommandListener(this);
cruiseForm.addCommand(CrC);
cruiseForm.append(CrL);
cruiseForm.append(CcabT);
cruiseForm.setCommandListener(this);
trainForm.addCommand(trainC);
trainForm.append(Tseat);
trainForm.append(TOP);
trainForm.setCommandListener(this);
Ext.addCommand(Exit);
Ext.addCommand(Home);
Ext.setCommandListener(this);
}
public void startApp() {
Xdisplay= Display.getDisplay(this);
Xdisplay.setCurrent(login);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable displayable){
try {
usr = RecordStore.openRecordStore(USERS, false);
} catch (Exception e) {
Sucess = new Alert("Error","Could not open Record Strore",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
if(c==signC)
{
Xdisplay.setCurrent(create);
}
else if(c == newTrip)
{
Xdisplay.setCurrent(startForm);
}
else if(c == prev)
{
try {
String record = "";
for (int i = 1; i < usr.getNextRecordID(); i++) {
record = new String(usr.getRecord(i));
}
home.append(record);
} catch (Exception e) {
home.append("Could not retrieve data");
try {
usr.closeRecordStore();
RecordStore.deleteRecordStore(USERS);
} catch (Exception x) {
}
}
try {
usr.closeRecordStore();
} catch (Exception e) {
}
}
else if(c==createC)
{
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
if(!"".equals(uName2.getString()))
{
writeRecord(uName2.getString());
}
Sucess = new Alert("Welcome to the mile high club","Hello:"+uName2.getString(),null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
else if (c == logC)
{
if(!"".equals(uName.getString()))
{
String name = uName.getString();
byte[] data = name.getBytes();
Xdisplay.setCurrent(home);
}
else
{
Sucess = new Alert("Please enter user name!","Invalid user name",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
}
else if(c==Trip)
{
tt +="Travel Mode: "+ trans.getString(trans.getSelectedIndex())+"\n";
if(trans.isSelected(0))
{
TT="A"; //Sets the type of travel based on choicegroup user selection
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(1))
{
TT="B";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(2))
{
TT="C";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(3))
{
TT="D";
Xdisplay.setCurrent(Pass);
}
}
else if (c == info)
{
for(int i = 0; i < hCAP.size(); i++) //Checks to see what items are selected in a ChoiceGrou
{
if(hCAP.isSelected(i))
{
details += hCAP.getString(i)+","; //If item is selected then it is appended to the string details
}
}
Rdate = rDate.getDate().toString();
Ddate = dDate.getDate().toString();
tt+= "Departure Date: "+ Ddate.substring(0, 10)+"\n";
tt+= "Return Date: "+ Rdate.substring(0, 10)+"\n";
Pcount = passCNT.getString(passCNT.getSelectedIndex()); //Gets passenger count from choicegroup of integers
specialA = Eneed.getString();
Final = new Alert("Your travel details: \n","Requested Devices:"+details+"\nPassenger Count: "+Pcount+
"\nSpecific Request: "+specialA,null,AlertType.INFO); //Appends string for alert
Final.setTimeout(Alert.FOREVER);
if("A".equals(TT)){ //Directs user to form based on travel type choice
Xdisplay.setCurrent(Final,airForm);
}
else if("B".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, autoForm);
}
else if ("C".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, cruiseForm);
}
else if ("D".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, trainForm);
}
}
else if(c==AiC)
{
AIR = airT.getString(airT.getSelectedIndex());//Retrieves selected item from choicegroup
tt+="Company: "+AIR+"\n";
AIR2 = airC.getString(airC.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Flight Details: \n","Airline Company:"+AIR+"\nSeat Class: "+AIR2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Airline Carrier: "+AIR+"\nSeat Type: "+AIR2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT,Ext);
}
else if (c == AutC)
{
AUTO = AuC.getString(AuC.getSelectedIndex());//Retrieves selected item from choicegroup
tt += "Company: "+AUTO+"\n";
AUTO2 = AuT.getString(AuT.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Auto Details: \n","Car Rental Company:"+AUTO+"\nVehicle Class: "+AUTO2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Rental Company: "+AUTO+"\nVehicle Class: "+AUTO2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == CrC)
{
CRUISE = CrL.getString(CrL.getSelectedIndex());
tt += "Company: "+CRUISE+"\n";
CRUISE2 = CcabT.getString(CcabT.getSelectedIndex());
FinalT = new Alert("Cruise Details: \n","Cruise Line Company:"+CRUISE+"\nCabin Type:"+CRUISE2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Cruise Line Company: "+CRUISE+"\nCabin Type: "+CRUISE2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == trainC)
{
TRAIN = Tseat.getString(Tseat.getSelectedIndex());
TRAIN2 = TOP.getString(TOP.getSelectedIndex());
FinalT = new Alert("Train Details: \n","Train Seat Type:"+TRAIN+"\nExtra Amenities:"+TRAIN2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Train Seat Type: "+TRAIN+"\nExtra Amenities: "+TRAIN2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if(c == Home)
{
home.deleteAll();
Xdisplay.setCurrent(login);
}
else if(c==Exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Resources