Calling a method from another class in java - java

I am using BlueJ and i am trying to call a method from another class. To be more specific i am trying to complete the following.
When the download music button is pressed, if a suitable value has been entered for the display number:
The display number is used to get the gadget, cast as MP3, from the array list.
The method to download music in the MP3 class is called with the
download size entered.
Here is the gadgetshop class that builds the GUI and the place where i want to call the downloadMusic method. the method for the button is called downloadMusic.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
//Array List
private ArrayList<Gadget>gadgets;
public void actionPerformed(ActionEvent event)
{
if (command.equals("Download Music"))
{
downloadMusic();
}
}
public void addMp3()
{
MP3 mp3 = new MP3(getWeight(), getPrice(), getModel(), getSize(), getMemory());
gadgets.add(mp3);
}
public void displayAll()
{
for(Gadget gadget : gadgets)
{
gadget.print();
System.out.println();
}
}
public void downloadMusic()
{
}
public int getDisplay()
{
int gadgetDisplay = 0;
try
{
gadgetDisplay = Integer.parseInt(displayText.getText());
if (gadgetDisplay<= 0)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
return gadgetDisplay;
}
public String getDownload()
{
String gadgetDownload;
gadgetDownload = downloadText.getText();
return gadgetDownload;
}
}
This is the MP3 class
public class MP3 extends Gadget
{
private int memory;
public MP3(int theWeight, double thePrice, String theModel, String theSize, int theMemory)
{
super(theWeight,thePrice, theModel, theSize);
memory = theMemory;
}
public void downloadMusic(String music, int MusicSize)
{
if(MusicSize>memory)
//if statement saying if size is greater than memory then display the follwing statemnt saying there is not enough memory
{
System.out.println("Not Enough Memory");
}
else
// else statement opposite to the above statement saying if music size is less than or equal to the memory display the following statement
{
memory = memory - MusicSize;
System.out.println("Download Successfull. "+ "\nMusic Name: "+ music + "\nMemory Left: " + memory);
}
}

The "other class" (with the button) must have an instance of the class with the method you want to call. You could create an instance of MP3 in the constructor of GadgetShop and store it as an instance variable. Then in your button listener call
mp3Instance.downloadMusic("music", 42);

Related

Sharing GUI variables without static variables

Currently I have a GUI that has options for the user to select on how the program should run:
//Inside GUI.java, start button has clicked -> send all objects to Main class
private void startButtonClicked(MouseEvent e) {
Main.setMain(selectedObj.getItemAt(selectedObj.getSelectedIndex()));
Main.setOwnCar(userName.getText().trim());
Main.enableNaps(weSleep.isSelected());
Main.useOwnHouse(useOwnHouse.isSelected());
if (weSleep.isSelected()) {
Integer minSleep = (Integer) minVal.getValue();
Integer maxSleep = (Integer) maxVal.getValue();
Main.setSleepMinMax(minSleep, maxSleep);
}
setVisible(false);
}
When the start button is clicked I want to pass all the variables from the GUI into the main class. The only way I knew how to do it was to use getter/setters but they have to be static:
static void setSleepMinMax(int min, int max) {
sleepMin = min;
sleepMax = max;
Log("Sleeping debug: [min->" + min + "] [max->" + max + "]");
}
//Inside an infinite loop I have this which is at the top
//until the GUI is closed it does not start the rest of the program
if (gui.isVisible()) {
Log("Waiting for GUI vars");
return 1000;
}
if (!getOwnCar.isEmpty())
Log("Using " + ownerCarName);
Most say avoid static variables. What is the correct way if I am unable to use a constructor because my main class is always running and the GUI is just a window that can be opened to change variables on demand? Perhaps pass by reference similar to C++?
The design it's up to your side. You could pass also the object reference or use some standard design patterns (GOF - singleton).
You could look also at:
Singleton
import java.util.Random;
public class PassVar {
private int mainVar = 0;
private MyObj myobj;
public static void main(String[] args)
{
PassVar pv = new PassVar();
pv.new MyObj(pv);
System.out.println("value="+pv.mainVar);
pv.new ChangeValue(pv);
System.out.println("value="+pv.mainVar);
pv.new ChangeValue(pv);
System.out.println("value="+pv.mainVar);
pv.myobj = pv.new MyObj();
System.out.println("myobj_i="+pv.myobj.i);
pv.new MyObj(pv);
System.out.println("myobj_i="+pv.myobj.i);
pv.new MyObj(pv);
System.out.println("myobj_i="+pv.myobj.i);
}
public void setMainVar(int i)
{
mainVar = i;
}
class ChangeValue
{
ChangeValue(PassVar pv)
{
pv.setMainVar(new Random().nextInt() %100);
}
}
class MyObj
{
public int i=-1;
MyObj() {}
MyObj(PassVar pv)
{
i = 10+new Random().nextInt(10);
pv.myobj = this;
}
}
}
Output:
value=0
value=11 (random between -99 ... 99)
value=77
myobj_i=-1
//set obj.ref. in PassVar from MyObj
myobj_i=18 (random between 10 ... 19)
myobj_i=12
Write it to a property file and read it from there.So that when next time one uses it again he can have the previous values.

How to access Java array list data from another class

I'm trying to make a quiz in Java but I'm having trouble accessing the array list data from the tester class and therefore my question text isn't showing up. I have three classes; tester, quiz interface and quiz set up. I've been playing around with it for a while and I'm pretty sure I'm starting to make things worse so I thought I'd post on here.
The questions are added to the array list in the Tester file but I can't seem to access this in the set up class for this method:
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
Expected output was to take a random question from the array list and display the question text but instead nothing appears and it is blank.
I'm fairly new to Java and programming so any detailed answers are welcome! Thanks in advance.
import java.util.ArrayList;
public class QuizTester {
private static ArrayList<Question> questions; //declares arrayList to holds the questions
public static void main(String[] args) {
QuizSetUp theQuiz = new QuizSetUp();
questions = new ArrayList<Question>(); //constructor
questions.add(new FillInBlank("____________ is the ability of an object to take many forms.", "Polymorphism"));
questions.add(new FillInBlank("The process where one object acquires the properties of another is called __________", "inheritance"));
questions.add(new FillInBlank("The ___________ keyword is used by classes to inherit from interfaces", "implements"));
questions.add(new MultipleChoice("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?",
"Polymorphism", "Encapsulation", "Inheritance", "Construction", "Encapsulation"));
theQuiz.pickQuestion();
}
public ArrayList<Question> getQuestionList() {
return this.questions;
}
}
////////////////////////quiz set up file.
public class QuizSetUp {
private QuizInterface qi;
private QuizTester test;
//private ArrayList<Question> questions; //declares arrayList to holds the questions
private int counter = 1;
Random random;
int randIndex;
public QuizSetUp() {
setInterface();
//questions = new ArrayList<Question>(); //constructor
}
private enum QuAnswer { CORRECT,INCORRECT }
public void setInterface() {
qi = new QuizInterface();
test = new QuizTester();
//add action listeners to each of the buttons
ActionListener cl = new ClickListener();
qi.getNextBtn().addActionListener(cl);
qi.getStartQuizBtn().addActionListener(cl);
//allows users to press enter to start quiz rather than having to click quiz button
KeyListener ent = new KeyBoardListener();
qi.getUName().addKeyListener(ent);
qi.getUPassword().addKeyListener(ent);
}
public void pickQuestion() {
randQuestion();
setQuestion(randIndex);
//setAnswer("A", randIndex);
//setAnswer("B", randIndex);
//setAnswer("C", randIndex);
//setAnswer("D", randIndex);
//setCorrectAnswer(randIndex);
//qi.resetTimer();
}
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
//inner listener class for buttons
private class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == qi.getStartQuizBtn()) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
} else if (evt.getSource() == qi.getNextBtn()) {
counter++;
if (counter == 5) {
qi.getNextBtn().setText("Finish Quiz"); //changes next button text on final question
}
if (counter < 6) {
qi.getQuProgress().setText(counter + " of 5");
} else {
//shuffle to end panel
}
}
}
}
//inner listener class for key presses
private class KeyBoardListener implements KeyListener {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//method to validate input by user to log in
public void validateInput() {
//presence check on username
if (qi.getEnteredName().length() > 0) {
//presence check on password
if (qi.getEnteredPass().length > 0) {
//ensures password is at least 6 char long
if(qi.getEnteredPass().length > 5) {
qi.getCards().next(qi.getPanels()); //getPanels() == cardPanel
} else {
JOptionPane.showMessageDialog(null,
"Your password must be at least six characters long.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Your did not enter a password.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
}
After some alterations, I was able to get your code running. But I have to warn you, there are quite some changes:
QuizTester now only has a main method to start the program. It will initialize and fill the list with questions and then pass it to the QuizSetUp instance
I didn't have your Question class, so I reduced it to an ArrayList<String> (just to make sure, that the questions could be passed)
And I didn't hvae your QuizInterface class so I helped myself with a small implementation that would simply print out the question when a new question gets set
QuizInterface (small helper class)
public class QuizInterface {
private String text;
public QuizInterface() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
System.out.println("question text = "+this.text); // this is just to make sure it worked
}
}
QuizSetUp (heavily reduced)
public class QuizSetUp {
private QuizInterface qi;
private ArrayList<String> questions; // uncommented, it's needed now
private int counter = 1;
Random random;
int randIndex;
// I chose to pass the list with the constructor but the setQuestions() will do as well
public QuizSetUp(ArrayList<String> questions) {
this.questions = questions;
setInterface();
}
// NEW method – but it's not needed
public ArrayList<String> getQuestions() {
return questions;
}
// NEW method – but it's not needed
public void setQuestions(ArrayList<String> questions) {
this.questions = questions;
}
private enum QuAnswer {
CORRECT, INCORRECT
}
public void setInterface() {
qi = new QuizInterface();
// test = new QuizTester(); // this is no longer needed since QuizTester is only used to start the program
}
public void pickQuestion() {
randQuestion();
setQuestion(); // randIndex is already a global variable in this class, no need to pass with the method call
}
public void setQuestion() {
// QuizInterface has a new method now called "setText()"
// so here we access the list "questions" (it is already initialized, because we pass it to this class when constructing it)
// this.randIndex is global, so we can use it directly in this method as an index to the questions list (as you already did it)
qi.setText(this.questions.get(this.randIndex));
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
// .... the rest I left out here because it is not needed for this little test
}
QuizTester (only needs the main method)
public class QuizTester {
public static void main(String[] args) {
ArrayList<String> questions = new ArrayList<>(); //as you can see I replaced the List with a list of Strings (because I didn't have your Question class)
// so these are only strings...
questions.add("____________ is the ability of an object to take many forms.");
questions.add("The process where one object acquires the properties of another is called __________");
questions.add("The ___________ keyword is used by classes to inherit from interfaces");
questions.add("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?");
// here I create the QuizSetUp instance and pass the list right with the constructor
QuizSetUp theQuiz = new QuizSetUp(questions);
// if everything works out, calling this method
// should pick a new question, set it to the QuizInterface
// and the QuizInterface (the helper version I made) will print it out
theQuiz.pickQuestion();
}
}
Those three classes can compile as they are and when I ran the program I got this output
question text = The ___________ keyword is used by classes to inherit from interfaces
I know this is a lot different from what you have, the only big change I did was passing the newly create questions list directly to the QuizSetUp instance – so no accessing any static lists.
Looking at this line:
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
where is the getQuestionList() implemented? It looks like a method call, except that QuizSetUp doesn't declare a getQuestionList() method. It is in a different class.
Conclusion: the code that you've shown us in the question won't even compile.
I should point that this (in QuezSetup) is very bad style, dnd liable to cause confusion.
private static ArrayList<Question> questions;
public ArrayList<Question> getQuestionList() {
return this.questions;
}
While this.questions looks like it is referring to an instance variable, it is actually referring to a static variable. The this is misleading.

Weird error - doesn't do anything after breaking from menu

This is for coursework. I've built the whole program, and it does everything right, apart from this one thing.
I have a class called 'Schedule' this method is at the very end of schedule:
public void bookSeatMenu()
{ boolean leaveBookSeatMenu = false;
String seatBookingMenuStr;
int seatBookingMenuInt = 14;
boolean isInteger = false;
Scanner input = new Scanner(System.in);
System.out.println("Press 1 to add an individual booking, 2 to cancel a booked seat or 3 to go back");
seatBookingMenuStr = input.nextLine();
try {
seatBookingMenuInt = Integer.parseInt(seatBookingMenuStr);
isInteger = true;
}
catch (NumberFormatException e) {
}
switch (seatBookingMenuInt) {
case 1:
bookSeat();
break;
case 2:
cancelSeat();
break;
case 3:
leaveBookSeatMenu = true;
break;
default:
System.out.println("Invalid Choice");
} while (leaveBookSeatMenu == false);
}
I know you all know what a switch menu looks like, but I thought I'd throw it in there anyway, in case (pardon the pun) I'm going wrong here.
Moving on, I have the bookSeat method, this is where the user books a seat (which works fine). Then afterwards it displays the bookSeatMenu() just it displays the menu. But then it won't go back to the previous one.
public void bookSeat()
{
Scanner input = new Scanner(System.in);
boolean isSeatBooked = true;
showSeatPlan();
int seatNum = 0;
int rowNum = 90;
int columnNum = 16;
boolean isInt = false;
while (isSeatBooked == true)
{
System.out.println("Please pick column of a seat to book");
columnNum = input.nextInt();
System.out.println("Please pick row of a seat to book");
rowNum = input.nextInt();
seatNum = (columnNum + ((rowNum) * 15));
if (seats[seatNum] == false)
{
isSeatBooked = false;
}
else
{
System.out.println("This seat is already booked");
}
}
seats[seatNum] = true;
System.out.println("");
bookSeatMenu();
}
Now not for love nor money am I able to get it to go back to the previous menu after it's booked a seat.
Basically the process is:
Book a seat --> go to bookSeatMenu --> press 4 to go back --> Arrive at previous menu.
If I don't book a seat, the program will happily go back to the menu before hand, but after, it just keeps on going on to a new line in the command prompt, not doing anything else, no error etc.
I'm pretty tempted to say this might be a problem with BlueJ, although a bad workman blames his tools, and I don't wanna be 'that guy'
I also need to make a 'testing class' - having never used a 'testing class' before, and the assignment asking us to look in the 'textbook' which noone bothered to buy, I actually have no idea!
There's no switch...while so I assume your problem is as soon you do choose 3, you end up in while(true); which is an infinite loop.
correct pseudo-code:
do {
// read System.in
// handle menu options with your switch
} while(...)
By the way, design is bad IMHO, you should try to think about your model (in your case I would see something like Room, Seat, Scheduler, Menu) and make those object interact with each others :
public class Room {
private Seat[][] seats;
public String toString() {
// like showSeatPlan() using toString() of Seat
}
}
public class Seat {
private int row, column;
private boolean isBooked;
public void book() { /* ... */ }
public void cancel() { /* ... */ }
public String toString() { /* "X" or " " */ }
}
public final class Scheduler {
// "main class" with a "main" method
}
public class Menu {
private Room room;
public String toString() {
// print out menu
}
public void bookSeat() { /* ... */ }
public void cancelSeat() { /* ... */ }
}
(something like that)
For the test part, each class have a test class and each method have a test method, as an example, for Seat:
public class Seat {
public void book() {
if (this.isBooled) {
throw new CannotBookException("seats is taken!");
}
this.isBooled = true;
}
}
public class SeatTest {
#Test // when I book a seat, it's markedas booked.
public void testBook() {
final Seat seat = new Seat();
seat.book();
assertTrue(seat.isBooked)
}
#Test(expected = CannotBookException.class) // when I book an already booked seat, I get an exception.
public void testBookAlreadBooked() {
final Seat seat = new Seat();
// book the seat
seat.book();
assertTrue(seat.isBooked)
// try to book again
seat.book();
}
}

Java access a public variable outside a class, SecurityException: MIDlet not constructed by createMIDlet

I'm a newbie in java and I have a small problem. I want to access a variable in one class from another. I have three classes and I want to be able to access a variable in the main class to enable me read the array.
The error I am getting is
java.lang.SecurityException: MIDlet not constructed by createMIDlet
Please see the example below. Please bear in mind they're all in the same package.
package tungPackage;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import javax.microedition.midlet.MIDlet;
public class TungMidlet extends MIDlet implements ActionListener {
private Command back = new Command("Back");
private Command ok = new Command("Ok");
public ActionListener commandlistListener = new ActionListener() {
public void actionPerformed(ActionEvent cmd) {
// check which command cliked
if (cmd.getCommand() == back) {
// go back to previous form
mainForm.show();
} else if (cmd.getCommand() == ok) {
// go forward
}
}
};
private List list;
private Form mainForm;
private Label promptLabel;
private housesClass houseClassObject = new housesClass();
public int counter; //this is the variable I want to access in a class called calculate class object.
private int sumAmmt;
public TungMidlet tungMidletObject;
public calculateClass calculateClassObject;
public TungMidlet() {
Display.init(this);
}
private ActionListener applistListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(list.getSelectedIndex()==0){
counter++;
if (counter>5)
{
//check sum price.
sumAmmt = calculateClassObject.calculateSum();
Dialog x = new Dialog("info");
Label label = new Label("Maximum reached.");
Label label2 = new Label("Sum ammt = "+sumAmmt);
x.addComponent(label);
x.addComponent(label2);
x.addCommand(ok);
x.show();
}
else
{
//calculate the price
String info = houseClassObject.randomHouse();
Dialog x = new Dialog("info");
Label label = new Label(info);
x.addComponent(label);
x.addCommand(ok);
x.show();
}
}
}
};
public void startApp() {
//calculateClassObject = new calculateClass();
//sumAmmt = calculateClassObject.calculate(sumAmmt);
mainForm = new Form("Investment Categories");
promptLabel = new Label("choose category");
list = new List();
list.addItem("House");
list.addItem("Cars");
list.addItem("Schools");
list.addItem("Schools");
list.addItem("Supermarkets");
list.addItem("Stocks");
list.addItem("Land");
list.addActionListener(applistListener);
mainForm.addComponent(promptLabel);
mainForm.addComponent(list);
mainForm.addCommand(back);
mainForm.addCommandListener(commandlistListener);
mainForm.setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 1000));
mainForm.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
The class I want to access the "counter" variable using is shown below.
package tungPackage;
import java.util.Random;
public class housesClass {
public Random generator = new Random();
public String[] houseArray = new String[5];
public housesClass housesClassObject;
public calculateClass calcobj;// = new calculateClass();
public housesClass()
{
}
public String randomHouse() {
housesClassObject = new housesClass();
houseArray[0] = "Bungalow - 20,000,000 Shillings";
houseArray[1] = "Microhouse - 10,000,000 Shillings";
houseArray[2] = "Flat - 200,000,000 shillings";
houseArray[3] = "Garage apartment - 7,000,000 shillings";
houseArray[4] = "Studio apartment - 13,000,000 shillings";
int rnd = generator.nextInt(houseArray.length);
housesClassObject.housePrices(rnd);///noma
String house = houseArray[rnd];
return house;
}
void housePrices(int houseNumber) {
calcobj = new calculateClass();
TungMidlet tungmidobj = new TungMidlet();
int counter = tungmidobj.counter;
int[] housePriceArray = new int[5];
housePriceArray[0] = 20000000;
housePriceArray[1] = 10000000;
housePriceArray[2] = 200000000;
housePriceArray[3] = 7000000;
housePriceArray[4] = 13000000;
int price = housePriceArray[houseNumber];
calcobj.storePrice(counter,price);
}
}
The other supporting class is shown below.
package tungPackage;
public class calculateClass {
int[] storeArray = new int[5];
public calculateClass()
{
}
public void storePrice(int counter, int number2)
{
storeArray[counter] = number2;
}
public int calculateSum()
{
int sum =0;
for(int i=1; i<6; i++){
sum= sum+storeArray[i];
}
return sum;
}
}
Are you getting an error? It looks like your access code should work.
I can't seem to find anywhere that you actually initialise counter though, so maybe your problem is that you need to put counter = 0; somewhere in your code.
Java is also object oriented so you should avoid accessing like the above and make some 'getter and setter' methods:
public int getCounter() {
return counter;
}
and then call int counter = tungmidobj.getCounter();
remove TungMidlet constructor. If there was something useful to do there, you could also declare it protected - but this is not the case with your code snippet, see below.
Wherever you try to invoke that constructor directly, remove code that does this and find another way to do what you need. If needed, study code examples provided in LWUIT Tutorial - Introduction for how typical things are done in LWUIT.
put statement Display.init() in the beginning of the startApp method,
just like it is done in LWUIT Tutorial - Hello, LWUIT! example code
The reason why you are getting SecurityException is because you invoke TungMidlet constructor directly. Don't do that.
MIDP API documentation for MIDlet constructor states:
Throws:
SecurityException - unless the application management software is creating the MIDlet.
one way is
TungMidlet tungMidlet=new TungMidlet();
System.out.println(tungMidlet.counter);
but know encapsulation
second way is
you can make counter private variable and provide setter and getters.
private int counter;
public void setCounter(int counter){
this.counter=counter;
}
public int getCounter(){
return counter;
}
second way is preferred way as it achieves encapsulation

J2ME key event handling

I have created a textfield that takes all characters from the user.. but i want to disable the space so that user cant enter space ...help??
pin = new TextField("Pin#","",4,TextField.PASSWORD);
If it's a PIN number then maybe you should replace the constraints parameter with TextField.NUMERIC | TextField.PASSWORD.
Implement the ItemStateListener interface. Then call this.setItemStateListener(this) in the Form constructor.
Implement the itemStateChanged method so that if the Item is the one you are interested in then get its content and test it if it contains spaces.
In my case I create a MIDlet and a Form which contains a TextField. And it works. I do not know why did you say that the solution I gave you did not work to you ! Here is a very simple example I give ( I created it and tested it ! ) :
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMIDlet extends MIDlet {
public Display display;
public HelloMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
Form f = new F(display);
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
package hello;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;
public class F extends Form implements ItemStateListener {
private TextField pin = new TextField("PIN :","",4,TextField.PASSWORD);
private Alert alert;
private Display disp;
public F(Display d)
{
super("");
disp = d;
this.setItemStateListener(this);
this.append(pin);
}
public void itemStateChanged(Item item) {
if (item == pin)
{
for (int i=0; i<pin.getString().length(); i++)
{
if (String.valueOf(pin.getString().charAt(i)).equals(new String(" ")))
displayAlert();
}
}
}
private void displayAlert()
{
alert = new Alert("Info","No space please !",null, AlertType.ERROR);
disp.setCurrent(alert, this);
}
}

Categories

Resources