Stop a method from executing until another class does its bit

Hi all,
For my app I have a login screen where to get login success the user must first register. I therefore have two class LoginDialog and Register which is a dialog.
In LoginDialog if the user clicks on Register it brings up a new instance of the Register dialog but continues to process the calling method (which happens to return to another class processing the login). What I require is that when I create a new Register object, the creating method does nothing until the Registration form is completed. I'm not at all au fait with threads so was wondering if there is an easy way to do it.
I have thought of passing the LoginDialog as an argument in the Register constructor and having an empty while loop running in the invoking method (i.e. while (false) do nothing) and creating public access to that boolean variable so that at completion of the registration it sets the boolean variable to true in LoginDialog so it should break out of the while loop and continue. Is that a satisfactory way of pausing and restarting a method?
Cheers,
Chris

Hi,
I have a MainFrame class which calls processLogin which creates a new LoginDialog which houses the Register button. When I click on the register button it opens a new Registration screen but LoginDialog returns to MainFrame in the background and says that no user has logged in. What I require is that when the Register object is created after clicking the Register button that LoginDialog waits until the Registration is complete.
Maybie the code will help (sorry if it is a bit lengthy).
Snippet of LoginDialog
public void actionPerformed(ActionEvent event)
        if(event.getSource() == ok) {
             _username = user.getText();
               _password = new String(password.getPassword());
               _server = server.getText();
               //ensure port number is an integer
               try{
                    _port = Integer.parseInt(port.getText());
               catch(NumberFormatException e){
                    JOptionPane.showMessageDialog(this,
                    "Please use an integer value only for the port number","Error",
                    JOptionPane.WARNING_MESSAGE);
               //checks username and password length
               if((_username.length()==0) || (_password.length() == 0)){
                    JOptionPane.showMessageDialog(this,
                         "Please enter a valid username and password","Error",
                              JOptionPane.WARNING_MESSAGE);
                    return;
               //checks server length
               if(_server.length()== 0){
                    JOptionPane.showMessageDialog(this,
                         "Invalid server host","Error",
                              JOptionPane.WARNING_MESSAGE);
                    return;
               try{
                    db = new DatabaseConnection();
                    boolean exists = db.doesUserExist(_username, _password);
                    db.close();
                    if(exists){
                         //System.out.println("User exists on database");
                         this.dispose(); //get rid of login screen now user is confirmed
                    if(!exists){
                              _username = null;
                              _password = null;
                              this.dispose();
               catch(java.sql.SQLException e){
                    JOptionPane.showMessageDialog(this,
                         "Unable to connect to database. Please try again.","Error",
                              JOptionPane.WARNING_MESSAGE);
          else if(event.getSource() == cancel) {
               //NOTHING
          else if(event.getSource() == register){
               Register register = new Register();
               //while (processRegistration){
          this.setVisible(false);
     }and Register
//import classes
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Register extends JFrame implements ActionListener {
     //declare components
     JLabel lblHeading;
     JLabel lblUserName;
     JLabel lblUserPwd;
     JLabel lblCnfUserPwd;
     JLabel lblFirstName;
     JLabel lblLastName;
     JLabel lblAge;
     JLabel lblEmpId;
     JLabel lblEmail;
     JLabel lblSex;
     String userName;
     char[] userPwd;
     char[] cnfPwd;
     String strUserPwd;
     String strCnfUserPwd;
     String firstName;
     String lastName;
     String age;
     String empid;
     String email;
     String sexStr;
     Socket toServer;
     ObjectInputStream streamFromServer;
     PrintStream streamToServer;
     JComboBox comboSex;
     JTextField txtUserName;
     JPasswordField txtUserPwd;
     JPasswordField txtCnfUserPwd;
     JTextField txtFirstName;
     JTextField txtLastName;
     JTextField txtAge;
     JTextField txtEmpId;
     JTextField txtEmail;
     Font f;
     Color r;
     JButton btnSubmit;
     JButton btnCancel;
     DatabaseConnection db;
     boolean exists, entrySuccess;
     public Register() {
          this.setTitle("Register");
        JPanel panel=new JPanel();
          //apply the layout
           panel.setLayout(new GridBagLayout());
           GridBagConstraints gbCons=new GridBagConstraints();
          //place the components
          gbCons.gridx=0;
          gbCons.gridy=0;
          lblHeading=new JLabel("Registration Info");
           Font f = new Font("Monospaced" , Font.BOLD , 12);
          lblHeading.setFont(f);
          Color c=new Color(0,200,0);
          lblHeading.setForeground(new Color(131,25,38));
          lblHeading.setVerticalAlignment(SwingConstants.TOP);
          gbCons.anchor=GridBagConstraints.EAST;
          panel.add(lblHeading, gbCons);
          gbCons.gridx = 0;
          gbCons.gridy = 1;
          lblUserName = new JLabel("Enter Username");
          gbCons.anchor=GridBagConstraints.WEST;
          panel.add(lblUserName, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=1;
          txtUserName=new JTextField(15);
          panel.add(txtUserName, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=2;
          lblUserPwd=new JLabel("Enter Password ");
          panel.add(lblUserPwd, gbCons);
          gbCons.gridx = 1;
          gbCons.gridy = 2;
          txtUserPwd = new JPasswordField(15);
          panel.add(txtUserPwd, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=3;
          lblCnfUserPwd=new JLabel("Confirm Password ");
          panel.add(lblCnfUserPwd, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=3;
          txtCnfUserPwd=new JPasswordField(15);
          panel.add(txtCnfUserPwd, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=4;
          lblEmpId=new JLabel("Employee ID");
          panel.add(lblEmpId, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=4;
          txtEmpId=new JTextField(15);
          panel.add(txtEmpId, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=5;
          lblFirstName=new JLabel("First Name");
          panel.add(lblFirstName, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=5;
          txtFirstName=new JTextField(15);
          panel.add(txtFirstName, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=6;
          lblLastName=new JLabel("Last Name");
          panel.add(lblLastName, gbCons);
          gbCons.gridx = 1;
          gbCons.gridy = 6;
          txtLastName=new JTextField(15);
          panel.add(txtLastName, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=7;
          lblAge=new JLabel("Age");
          panel.add(lblAge, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=7;
          txtAge=new JTextField(3);
          panel.add(txtAge, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=8;
          lblEmail=new JLabel("Email");
          panel.add(lblEmail, gbCons);
          gbCons.gridx=1;
          gbCons.gridy=8;
          txtEmail=new JTextField(20);
          panel.add(txtEmail, gbCons);
          gbCons.gridx=0;
          gbCons.gridy=9;
          lblSex=new JLabel("Sex");
          panel.add(lblSex, gbCons);
          gbCons.gridx = 1;
          gbCons.gridy=9;
          String [] sexArr = {"Male", "Female"};
          comboSex = new JComboBox(sexArr);
          comboSex.setSelectedIndex(0);
          panel.add(comboSex, gbCons);
          JPanel btnPanel=new JPanel();
          btnSubmit=new JButton("Submit");
          btnPanel.add(btnSubmit);
          btnSubmit.addActionListener(this); //add listener to the Submit button
          btnCancel=new JButton("Cancel");
          btnPanel.add(btnCancel);
          btnCancel.addActionListener(this); //add listener to the Cancel button
          gbCons.gridx=0;
          gbCons.gridy=10;
          gbCons.anchor=GridBagConstraints.EAST;
          panel.add(btnPanel, gbCons);
          getContentPane().add(panel);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          setVisible(true);
          setSize(450,400);
     }//end or Register()
     public void actionPerformed(ActionEvent ae) {
          Object o = ae.getSource(); //get the source of the event
          if(o == btnCancel)
               this.dispose();
          if(o == btnSubmit){
               userName = txtUserName.getText();
               userPwd = txtUserPwd.getPassword();
               strUserPwd = new String(userPwd);
               cnfPwd = txtCnfUserPwd.getPassword();
               strCnfUserPwd = new String(cnfPwd);
               firstName = txtFirstName.getText();
               lastName = txtLastName.getText();
               age = txtAge.getText();
               empid = txtEmpId.getText();
               email = txtEmail.getText();
               sexStr = (String)comboSex.getItemAt(0);
               db = new DatabaseConnection();
               //Now check to see if username and password combination have been
               //taken
               try{
                    exists = db.doesUserExist(userName.trim(), strUserPwd.trim());
               catch (java.sql.SQLException e){
                    System.out.println(e);
               //Checks that each field has been filled in.
               if(userName.length() == 0 ||  strUserPwd.length() == 0 ||
               strCnfUserPwd.length() == 0 || firstName.length() == 0 ||
               lastName.length() == 0 || age.length() == 0 || empid.length() == 0
               || email.length() == 0){
                    JOptionPane.showMessageDialog(this,
                    "One or more entry has not been filled in. Please go back and try again",
                    "Message", JOptionPane.ERROR_MESSAGE);     
               //Ensures that passwords match
               if(!strUserPwd.equals(strCnfUserPwd)){
                    JOptionPane.showMessageDialog(this,
                    "Passwords do not match. Please go back and try again",
                    "Message", JOptionPane.ERROR_MESSAGE);
               if(exists){
                    JOptionPane.showMessageDialog(this,
                    "Username and password combination already exists. Please go back and try again",
                    "Message", JOptionPane.ERROR_MESSAGE);
               if(!exists) {
                    String userDetails = (userName.trim() + " " + strUserPwd.trim()
                    + " "  + firstName.trim() + " "
                    + lastName.trim() + " " + age.trim() + " " + empid.trim() + " "
                    + email.trim() + " " + sexStr.trim());
                    //System.out.println(userDetails);
                    //Try to connect to the database and insert the user details.
                    //If successful then user will be alerted and the registration page
                    //should be disposed automatically. If for some reason the insert
                    //was not successful then user is prompted to try again.
                    try{
                         entrySuccess = db.registerUser(userDetails);
                         if(entrySuccess){
                              JOptionPane.showMessageDialog(this,
                              "Congratulations, you have successfully registered for the Instant Messenger service!",
                              "Message", JOptionPane.INFORMATION_MESSAGE);
                              this.dispose();     
                         if(!entrySuccess){
                              JOptionPane.showMessageDialog(this,
                              "There was a problem entering your details. Please try again.",
                              "Message", JOptionPane.ERROR_MESSAGE);
                    catch(java.sql.SQLException e){
          }//end of else
          db.close();
     }//end of actionPerformed()
}//end of classCheers,
Chris

Similar Messages

  • Stop the report from firing until the user clicks the Go button?

    Hi All,
    Is there a way to stop the report from firing until the user clicks the Go button? At the moment it is populating when I open the dashboard page. I found something online that said i could use the Page Options>Save Current Settings> For Others.. but even though i am signed in as an administrator i only see a For Me.. option. Also, even after setting this option i would like to be able to hit the 'Go' button to run the report and have it uncollapse the section. Is this possible?
    Thanks

    Thanks for the replies,
    In my report i am trying to constrain the report to todays data only. However the only prompt i have is for another column. If i place a filter on the date column with Year=0000 it will not change with the prompt selection and so will never return any results. Is there any other way?
    It seems wasteful to fire a request to the database onload of the page. Is there an option to only fire a request what the prompts are entered? I will be using a stored proc which needs parameters to run the request so it would be good to be able to set the report to not run until it has parameters entered
    Thanks

  • I'm a user of Mac OS X 10.4 Tiger and, as well, a user of Google fead reader, which will stop to work from July 1st 2013. Does anybody know of any alternative RSS reader which works on OS X 10.4? Thanks in advance.

    I'm a user of Mac OS X 10.4 Tiger and, as well, a user of Google fead reader, which will stop to work from July 1st 2013. Does anybody know of any alternative RSS reader which works on OS X 10.4? Thanks in advance.

    Hello, you still might be in luck...
    TenFourFox is the most up to date browser for our PPCs, they even have G4 & G5 optimized versions...
    http://www.floodgap.com/software/tenfourfox/
    In TFF>Preferences>General>Manfe Add-ons..., type rss in the Search all add-ons bar...

  • Accessing a native method from within a packaged class

    I have seen some very useful information from RPaul. However, I can not quite get it to work.
    I have a class "JNIGetUserId" that is in a package "com.services.localoptions". I am trying to call a native method from a dll. it works fine at the default package level. But not in the package. I have tried adding the "_" between each level of the directory in the h and c++ files. I also found that doing a javah at the top of the package structure it includes some information in the h file. A "_0005" shows up between each level.
    This is on Windows XP. I am also using VisualAge for Java. I also am using JDK 1.3.1.
    The source files:
    package com.services.localoptions;
    * This class provides the JNI Interface to call the
    * AD User Maintainence routines.
    * These routines are stored in the JNIGetUserIdLibrary.dll.
    * The routines are:
    * <ul>
    * <li>getUser - returns a string containing the User Id
    * <eul>
    * @author: Ray Rowehl
    * @date (10/15/2003 10:30:59 AM)
    public class JNIGetUserId
         // Load the library
         static
         try
              System.out.println("loading dll");
         System.loadLibrary("JNIGetUserIdLibrary");
         System.out.println("loaded dll");
         catch (UnsatisfiedLinkError ue)
              System.out.println("Link Error");
    * native C++ method to call getUserId routine
    public native String getUser() throws Exception;
    * This method allows us to test standalone..
    * Creation date: (10/16/2003 2:08:58 PM)
    * @param args java.lang.String[]
    public static void main(String[] args)
         try
              System.out.println("Trying method 3");
              JNIGetUserId lGUD = new JNIGetUserId();
              System.out.println(lGUD.getUser());
         catch (Exception e)
              System.out.println("Got an exception " + e);
              e.printStackTrace();
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class JNIGetUserId */
    #ifndef IncludedJNIGetUserId
    #define IncludedJNIGetUserId
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: JNIGetUserId
    * Method: getUser
    * Signature: ()Ljava/lang/String;
    JNIEXPORT jstring JNICALL Java_com_localoptions_JNIGetUserId_getUser
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    // Implements method to return a string to Java
    // C++ core header
    #include <iostream.h>
    // header from Java Interface
    #include "JNIGetUserId.h"
    #include "JNIGetUserId2.h"
    // returns a string back to Java for package structure
    JNIEXPORT jstring JNICALL Java_com_services_localoptions_JNIGetUserId_getUser
    ( JNIEnv * env, jobject thisObject )
         // set up constant user id for testing return
         char* userid = "RROWEHLP";
         // return userid to caller
         return env->NewStringUTF( userid );     
    // returns a string back to Java for flat structure
    JNIEXPORT jstring JNICALL Java_JNIGetUserId_getUser
    ( JNIEnv * env1, jobject thisObject1 )
         // set up constant user id for testing return
         char* userid1 = "RROWEHL1";
         // return userid to caller
         return env1->NewStringUTF( userid1 );     
    }

    Ok. A co-worker figured it out for me. The key thing is to do "javah com.services.localoptions.JNIGetUserId". Note the use of "." instead of "\". Running on windows, I was used to doing "\". That was part of the problem. Another key is doing the javah at the top of the package structure. This was mentioned in a post over at IBM.
    We got our JNI stuff working now. thanks, ray.

  • Value from JDialog to another class

    Hi:
    I have a trouble with getting my values from a JDialog box to another class.
    Here's what I have:
    This is an ftp application. I have a main frame where if the user selects File->New Connection
    it pops up a Connect dialog box. The connect dialog box has various fields such as profile name, host address, user name, and so on. In addition, there are three buttons, Add, Connect and Cancel.
    After the user types info and clicks Connect, all these information should be sent to the main frame from where it would send the information to another class which would connect to the ftp server.
    I have a class called Profile which is used to wrap these information to be sent to the main frame.
    Now, how can i get this info to the main frame? Here's the code in main frame:
    class MainFrame extends JFrame {
    JMenuItem newconnection = new JMenuItem("New Connection", 'N');
    newconnection.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Profile p = new Profile();
    ConnectDialog con = new ConnectDialog();
    p = con.getProfile();
    makeNewConnection(p); //this is the method i use to make a new connection
    The problem is that by the time i get to the line p = con.getProfile(),
    con object no longer exists.
    Should i use threads or should i just send the main frame as the parameter to create the Connect dialog. If i use threads, how should i code it, and if i use main frame as the parent frame for connect dialog, how do i get the info to main frame. Please help. Here's the code for ConnectDialog. Also, please advice if ConnectDialog code can be improved since i am new to swing. Thanks for helping a needy student.
    public class ConnectDialog extends JDialog{
    private MainFrame parent;
    private String defaultDownloadPath;
    private static Profile currProfile;
    private JList profileList;
    private JPanel listPanel;
    private JPanel infoPanel;
    private JPanel labelPanel;
    private JPanel buttonPanel;
    private JPanel arrangedComponents;
    private Vector data;
    private JLabel ProfileName;
    private JLabel HostAddress;
    private JLabel Account;
    private JLabel PortNo;
    private JLabel login;
    private JLabel password;
    private JLabel DownLoadPath;
    private JButton addButton;
    private JButton cancelButton;
    private JButton connectButton;
    private JButton browseButton;
    private JButton clearButton;
    private JLabel Anonymous;
    private JCheckBox anonymous;
    private JTextField profileName;
    private JTextField hostAddress;
    private JTextField account;
    private JTextField portNo;
    private JTextField loginName;
    private JTextField passwd;
    private JTextField downloadPath;
    private final int textSize = 20;
    private final int fontSize = 12;
    private Container cp;
    public ConnectDialog(MainFrame main) {
    super(main, true);
    parent = main;
    data = new Vector();
    currProfile = new Profile();
    profileList = new JList(data);
    listPanel = new JPanel();
    labelPanel = new JPanel();
    infoPanel = new JPanel();
    buttonPanel = new JPanel();
    arrangedComponents = new JPanel();
    ProfileName = new JLabel("Profile Name:");
    ProfileName.setForeground(Color.black);
    HostAddress = new JLabel("Host Address:");
    HostAddress.setForeground(Color.black);
    Account = new JLabel("Account:");
    Account.setForeground(Color.black);
    PortNo = new JLabel("Port:");
    PortNo.setForeground(Color.black);
    login = new JLabel("Login:");
    login.setForeground(Color.black);
    password = new JLabel("Password:");
    password.setForeground(Color.black);
    DownLoadPath = new JLabel("Download Path:");
    DownLoadPath.setForeground(Color.black);
    addButton = new JButton("Add");
    addButton.setMnemonic('A');
    addButton.setForeground(Color.black);
    cancelButton = new JButton("Cancel");
    cancelButton.setForeground(Color.black);
    clearButton = new JButton("Clear");
    clearButton.setForeground(Color.black);
    connectButton = new JButton("Connect");
    connectButton.setForeground(Color.black);
    connectButton.setMnemonic('C');
    browseButton = new JButton("Browse");
    browseButton.setForeground(Color.black);
    browseButton.setMnemonic('B');
    Anonymous = new JLabel("Anonymous: ");
    Anonymous.setForeground(Color.black);
    anonymous = new JCheckBox();
    profileName = new JTextField(textSize);
    profileName.setText("");
    profileName.setBorder(BorderFactory.createLoweredBevelBorder());
    profileName.setBorder(BorderFactory.createLineBorder(Color.black));
    profileName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    hostAddress = new JTextField(textSize);
    hostAddress.setText("");
    hostAddress.setBorder(BorderFactory.createEtchedBorder());
    hostAddress.setBorder(BorderFactory.createLineBorder(Color.black));
    hostAddress.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    account = new JTextField(textSize);
    account.setText("");
    account.setBorder(BorderFactory.createLoweredBevelBorder());
    account.setBorder(BorderFactory.createLineBorder(Color.black));
    account.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    portNo = new JTextField(5);
    portNo.setText("");
    portNo.setText("21");
    portNo.setBorder(BorderFactory.createEtchedBorder());
    portNo.setBorder(BorderFactory.createLineBorder(Color.black));
    portNo.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    loginName = new JTextField(textSize);
    loginName.setText("");
    loginName.setBorder(BorderFactory.createEtchedBorder());
    loginName.setBorder(BorderFactory.createLineBorder(Color.black));
    loginName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    passwd = new JTextField(textSize);
    passwd.setText("");
    passwd.setBorder(BorderFactory.createEtchedBorder());
    passwd.setBorder(BorderFactory.createLineBorder(Color.black));
    passwd.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    downloadPath = new JTextField(textSize);
    downloadPath.setText("");
    downloadPath.setBorder(BorderFactory.createEtchedBorder());
    downloadPath.setBorder(BorderFactory.createLineBorder(Color.black));
    downloadPath.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    cp = this.getContentPane();
    this.setBounds(200,200,600,300);
    this.setResizable(false);
    cp.setLayout(new BorderLayout());
    setListPanel();
    setLabelPanel();
    setButtonPanel();
    setActionListeners();
    this.setBackground(Color.lightGray);
    this.setVisible(true);
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    public String getDefaultDownloadPath() {
    return defaultDownloadPath;
    // public Profile getProfile() {
    // try {
    // this.wait();
    // } catch (Exception e) {}
    // return currProfile;
    public void setListPanel() {
    profileList.setFont(new Font("Dialog", Font.PLAIN, 12));
    profileList.setBackground(Color.white);
    profileList.setForeground(Color.black);
    profileList.setPrototypeCellValue("MMMMMMMMM");
    listPanel.setPreferredSize(profileList.getPreferredScrollableViewportSize());
    listPanel.setBorder(BorderFactory.createEtchedBorder());
    listPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    listPanel.setBackground(Color.white);
    listPanel.add(profileList);
    cp.add(listPanel, "West");
    public void setLabelPanel() {
    arrangedComponents = new JPanel();
    arrangedComponents.setLayout(new BorderLayout());
    labelPanel = new JPanel();
    labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
    labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    JPanel row1 = new JPanel();
    row1.add(ProfileName);
    labelPanel.add(row1);
    JPanel row2 = new JPanel();
    row2.add(HostAddress);
    labelPanel.add(row2);
    JPanel row3 = new JPanel();
    row3.add(Account);
    labelPanel.add(row3);
    JPanel row4 = new JPanel();
    row4.add(PortNo);
    labelPanel.add(row4);
    JPanel row5 = new JPanel();
    row5.add(login);
    labelPanel.add(row5);
    JPanel row6 = new JPanel();
    row6.add(password);
    labelPanel.add(row6);
    JPanel row7 = new JPanel();
    row7.add(DownLoadPath);
    labelPanel.add(row7);
    infoPanel.setLayout(new BoxLayout(infoPanel,BoxLayout.Y_AXIS));
    infoPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    row1 = new JPanel();
    row1.add(profileName);
    row1.add(profileName);
    infoPanel.add(row1);
    row2 = new JPanel();
    row2.add(hostAddress);
    row2.add(hostAddress);
    infoPanel.add(row2);
    row3 = new JPanel();
    row3.add(account);
    infoPanel.add(row3);
    row4 = new JPanel();
    row4.setLayout(new FlowLayout());
    row4.add(portNo);
    row4.add(Box.createHorizontalStrut(57));
    row4.add(Anonymous);
    row4.add(anonymous);
    infoPanel.add(row4);
    row5 = new JPanel();
    row5.add(loginName);
    infoPanel.add(row5);
    row6 = new JPanel();
    row6.add(passwd);
    infoPanel.add(row6);
    row7 = new JPanel();
    row7.setLayout(new FlowLayout());
    row7.add(downloadPath);
    row7.add(browseButton);
    infoPanel.add(row7);
    arrangedComponents.add(labelPanel, "West");
    arrangedComponents.add(infoPanel, "Center");
    cp.add(arrangedComponents, "Center");
    public void setButtonPanel() {
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(addButton);
    buttonPanel.add(connectButton);
    buttonPanel.add(cancelButton);
    buttonPanel.add(clearButton);
    cp.add(buttonPanel, "South");
    public void setActionListeners() {
    anonymous.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         if(anonymous.isSelected()) {
         loginName.setText("anonymous");
         passwd.setText("your email here");
         else {
         loginName.setText("");
         passwd.setText("");
    addButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         if(profileName.getText() != "" && !data.contains(profileName.getText())){
         data.add(profileName.getText());
         profileList.setListData(data);
    connectButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         connectButtonPressed();
    cancelButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         JButton b = (JButton) e.getSource();
         ConnectDialog c = (ConnectDialog) b.getTopLevelAncestor();
         c.dispose();
    clearButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         profileName.setText("");
         hostAddress.setText("");
         account.setText("");
         portNo.setText("");
         loginName.setText("");
         passwd.setText("");
         downloadPath.setText("");
    browseButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         JFrame browseFrame = new JFrame("browse for folder");
         browseFrame.setBounds(230,230,200,200);
         JDirectoryChooser fileChooser = new JDirectoryChooser();
         fileChooser.setFileSelectionMode(JDirectoryChooser.DIRECTORIES_ONLY);
         int option = fileChooser.showDialog(browseFrame);
         if(option==JFileChooser.APPROVE_OPTION) {
         File f = fileChooser.getSelectedFile();
         defaultDownloadPath = f.getAbsolutePath();
         downloadPath.setText(defaultDownloadPath);
    public void connectButtonPressed() {
    if(!profileName.getText().equals("") && !hostAddress.getText().equals("") &&
    !loginName.getText().equals("") && !passwd.getText().equals("")) {
    currProfile.setProfileName(profileName.getText());
    currProfile.setHostAddress(hostAddress.getText());
    currProfile.setAcct(account.getText());
    currProfile.setUserName(loginName.getText());
    currProfile.setPassword(passwd.getText());
    currProfile.setDownloadPath(downloadPath.getText());
    parent.setProfile(currProfile);
    this.dispose();
    else {
    JFrame f = new JFrame("Error!");
    JOptionPane.showMessageDialog(f, "Some fields empty!", "", JOptionPane.ERROR_MESSAGE);
    }

    If the dialog is modal then you can just call show and wait for it to close by the user, then grab the info:
    ConnectDialog dialog = new ConnectDialog();
    dialog .show();
    Profile profile = con.getProfile();
    makeNewConnection( profile );

  • No access to method from within the same class

    Hey there.
    First I have to excuse my English for I'm german and just learning...
    Ok, my problem is as follows. I have a class called JDBC_Wrapper it includes the method sendQuery(String query). When I call this method from within another class (where 'wrapper' is my instance of JDBC_Wrapper) it works fine. For example:
    wrapper.sendQuery("SELECT * FROM myDataBase");
    But then I have written a method called getNumRows() into my JDBC_Wrapper class.
    This method should send a query through sendQuery(Strin query) but when calling getNumRows() it says: "java.sql.SQLException: [FileMaker][ODBC FileMaker Pro driver][FileMaker Pro]Unbekannter Fehler." (Unbekannter Fehler -> Unknown Exception). What could that be?
    I'm using jdk2 sdk 1.4.2 with BlueJ. My database is Filemaker Pro 6. The ODBC/JDBC connector works fine.
    BerndZack

    This is within my JDBC_Wrapper class:
    public ResultSet sendQuery(String query)
            if(connected)
                try
                    Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                    ResultSet rs = s.executeQuery(query);
                    return rs;
                catch(Exception e)
                    System.out.println(e);
            else
                //System.out.println("There is no connection to the datasource!");
            return null;
    public int getNumRows()
            try
                ResultSet r;
                r = this.sendQuery("SELECT COUNT(*) FROM " + table_name); // At this line the error occurs
                r.next();
                return (int)r.getInt(1);
            catch(Exception e)
                System.out.println(e.getMessage());
                return -1;
    }When I call sendQuery() from within another class it works, but calling getNumRows()
    throws an exception.

  • Stop escaped characters from resolving within String class.

    Hello,
    Is it possible to stop escaped characters from resolving within the String class?
    For example, I define a character array,
    char[] c = {'0','\\','n'}
    and I want to create a String based on this exact sequence (0\n). However, when I call the String constructor String(char[]), it resolves the \n sequence into the newline character, creating a String of length 2 not 3.
    I'm not very familiar with the innards of the Java compiler (does "xyz" translate to char[]{'x','y','z'}?), so maybe this is something very basic.
    Does anyone know if there is a flag that can be set somehow before I create a String instance (it appears that no String constructor supports this kind flag)?
    Or perhaps is there a method in the standard Java release that escapes all escape characters in a character array...? I'm curious if there is a simpler way (like a flag), because the method approach seems superfluous.
    Thanks,
    Brien

    What do you mean?char[] c = {'0', '\\', 'n'};
    String s = new String(c);
    System.out.println(s);does give the string 0\n...
    And by the way, it's not the String class that transforms \n to the linefeed character, it is the compiler..

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • Displaying the output from a java class executed from W/I another class

    I have compiled a java class, but I have run into a problem executing the class. I have read the posts and still have not solved the solution. I have tried to get the output of the Process by using "proc.getOutputStream().toString()", however it displays it in binary (ex. java.io.BufferOutputStream@48eb2067). If anyone can provide any assistance I would greatly appreciate it. Or if you could tell me if I'm on the right track or not. Thanks ALL. Here is a code segment:
    int truncStart = s.indexOf(".java");
                   s = s.substring(0,truncStart);
                   String[] command2 = {"java","c:/"+s};
                   try
                   //JOptionPane.showMessageDialog(null,"Exec. File "+s, "Exec. File : ",JOptionPane.ERROR_MESSAGE);
                   proc = Runtime.getRuntime().exec(command2);
                   JOptionPane.showMessageDialog(null,"Output: "+proc.getOutputStream().toString(),"Output"
    ,JOptionPane.ERROR_MESSAGE);
                   }

    You have to read the stream, like:
    InputStream stream = proc.getOutputStream();
    // now use methods on stream, such as read() to read the characters/lines - or wrap it in another line-friendly stream - see the java.io.* classes - keep reading until you get an end-of-stream indicator, depending on the API you end up using.

  • Rendered attribute of commandButton preventing action method from executing

    When I add a rendered tag to my commandButton it'll only execute the method intermittantly. After a lot of testing, I've narrowed down the problem so I now know when it does and does not work properly.
    If rendered="true" it always works fine
    If rendered="#{issue.update}" and isUpdate() is simply "return true;" it'll always work correctly
    If rendered="#{issue.update}" and isUpdate() is simply "return this.getId() != 0;" it will not execute the action specifiied, however the page does refresh.
    It's also interesting to note that on the rendered page, the button is always shown only when it should be. So when the action fails to execute, the button is shown on the screen.
    In the case that doesn't work, I debugged through and noticed that isUpdate() is called six times for a single page refresh. By printing a stacktrace for each call, I discovered that it's called once in the ApplyRequestValues stage of the lifecycle and the other five times are from RenderResponse (I have the stacktraces, let me know if they'd be worth posting). This method is only referenced once and only on the jsf page, never in the java code... but I'll go back and try to understand why it's calling it so many times later.
    The first time isUpdate() is called, it will retrun false because the value for id has not yet been assigned, which makes sense. This causes a "false" to be returned from isUpdate() and this is what is causing the action to not be executed. If I debug through and change the return value to be true here (only the first time) the action is updated. So my question is, what's going on here? I don't understand why is isUpdate() called so many times, why is it called so early in the lifecycle, and why the call in the apply request values stage determines whether or not it executes the action?
    Now, as a workaround, I put a binding on the id, and tried to use that value. That exposed another problem with my page which requires some explanation... Here are the relevent sections of the page and backing bean...
    issue.jsp
    <h:outputText value="#{issue.init}" />
    there's a datatable here which displays all issues and has a commandLink to edit the issues (immediate="true"). It posts back to this page and passes an ID on the URL.
    <h:inputHidden id="id" value="#{issue.id}" binding="#{issue.idBinding}" />
    <h:inputText id="name" value="#{issue.name}" required="true" />
    <h:commandButton id="updateIssue" value="Update" action="#{issue.updateIssue}" rendered="#{issue.update}" />
    Issue.java
    getInit() will get the id from the FacesContext (specifically, the URL) and load the data from the database.
    On the rendered page in my web browser:
    After clicking on an edit link, the page is loaded and the name is filled in, the update button is on the screen, and everything looks good.
    When I view source, I see that the hidden input for id is set to zero. I'm still trying to figure out why this is the case since all the other parameters are set properly. I stepped through getInit() and it is, indeed setting the id property properly.
    So when I added the binding to get the value from there instead of via the local values, I found that it always got zero (presumedly because that's what is rendered in the HTML code). This means that isUpdate() still returns false on the first call, and my attempt at a workaround fails! So, just as a test, I used some "javascript on the URL" trickory to set the id field to "10". That worked just fine. So the root of the problem is that issue.id is not loading. I put code in the getId() method to always look at the binding and then faces context and put the id into this.id if it found a non-null and non-zero value. It now returns the correct value all of the time but the HTML produced still says the value is zero.
    I've spent about 4 hours on this issue and I'm to the point where I need advice from someone who is more educated on how JSF works. I know the inputHidden get the vaule for the HTML tag it produces from getId() because when I hard code that to always return 10, it works. But when I leave it to return the proper value, the debug statements say it's returning the proper value, but the HTML always says it's zero. This isn't an acceptable solution anyway because I use getId() in the datatable to display the IDs of each of the issues; I just wanted to see if it'd work and it didn't.
    Here's my latest getInit() method (which returns the value from the URL when called from the datatable, but not when called from the inputHidden.
        public int getId() {
            if(getIdBinding() != null && !getIdBinding().isLocalValueSet()) {
                if(getIdBinding().getSubmittedValue() != null) {
                    int temp = Integer.parseInt((String)getIdBinding().getSubmittedValue());
                    if(temp != 0) {
                        this.id = temp;
                        log.info("Got binding value of "+this.id);
            FacesContext ctx = FacesContext.getCurrentInstance();
            if(ctx != null) {
                Map<String, String> map = ctx.getExternalContext().getRequestParameterMap();
                    if(map != null) {
                    String given_id = map.get("id");
                    if(given_id != null) {
                        // if given an ID and no action, we load the data
                        try {
                            log.info("Got value from FacesContext of "+given_id);
                            int temp = Integer.parseInt(given_id);
                            if(temp != 0)
                                this.id = temp;
                        } catch(NumberFormatException e) {
                            // if what's passed in isn't an integer, we leave everything at default values
            return this.id;
        }Thanks in advance,
    Adam

    I'm clicking a link which will load data into a form. In the form there is a field called "id" which has a value of something other than zero. I press the update button (which is only rendered when the id is non-zero), it submits the form. When the restore view happens, the id is the default value of 0 because it has not yet applied the values from the form to the backing bean. Therefore the rendered attribute of update button (isUpdate()) will return false, and the update() method does not get queued.
    When I switch my backing bean to session level, the restore view already has the id loaded, even before the values from the form are applied, so everything works as expected. The problem was that I needed to have the correct return values before any values have been loaded into the member variables.
    As a solution to this, I made some private boolean variables called isNew and isUpdate. Both of them are true by default. This makes sure that the isNew() and isUpdate() methods (attached to the render attribute of my command buttons) return true in the restore view phase. When I read in the id from the URL or hidden input, it'll update the boolean values accordingly, which makes sure the buttons are rendered properly. This allowed me to set the backing bean back to the request scope, which make me happy. <img class="emoticon" src="images/emoticons/grin.gif" border="0" alt="" />
    Thank you Mr. De Campo. You gave me exactly what I was looking for... a better understanding of how thigns work, and (indirectly) a clean solution to my problem.

  • Need to stop servlet execution until another thread completes its execution

    Hi all,
    i created servlet & in the doPost method i run a thread,after the thread end its execution, the servelt takes a result from this thread & do something in it.
    my problem is that , i need to make the servlet stop the execution until this thread ends, & then the servlet continue in executing the remaining code.
    welcome to any help.

    This appears to be a threads related problem. Try Thread.join - http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#join()

  • Problem in calling method with object in another class

    Hi All,
    Please tell me the solution, I have problem in calling a method I am posting the code also
    First Program:-
    import java.io.*;
    public class One
    public One()
    System.out.println("One:Object created");
    public void display()
    System.out.println("One:executing the display method");
    static
    System.out.println("One:executing the static block");
    Second Program:-
    import java.io.*;
    public class Two
    public Two()
    System.out.println("Two:Object created");
    public static void main(String arg[])throws Exception
    System.out.println("Two:executing the main method");
    System.out.println("Two:loading the class and creating the object::One");
    Object o=Class.forName("One").newInstance();
    System.out.println(o);
    o.display(); //displaying error here in compile time.
    static
    System.out.println("Two:executing the static block");
    waiting for your answer,
    thanks in advance,bye.

    Hi All,
    Please tell me the solution, I have problem in
    calling a method I am posting the code also
    First Program:-
    import java.io.*;
    public class One
    public One()
    System.out.println("One:Object created");
    public void display()
    System.out.println("One:executing the display
    method");
    static
    System.out.println("One:executing the static
    block");
    Second Program:-
    import java.io.*;
    public class Two
    public Two()
    System.out.println("Two:Object created");
    public static void main(String arg[])throws
    Exception
    System.out.println("Two:executing the main
    method");
    System.out.println("Two:loading the class and
    creating the object::One");
    Object o=Class.forName("One").newInstance();
    System.out.println(o);
    o.display(); //displaying error here in compile
    time.
    static
    System.out.println("Two:executing the static
    block");
    waiting for your answer,
    hanks in advance,bye.the line
    o.display()
    could be written as
    ((One)o).display();

  • How to stop as files from running until a certain frame

    Hi all,
    I have a simple flash game with two frames at the moment.
    Most of the stuff that happens is in as files linked to
    different movie clips.
    I orignially only had one frame my background frame and when
    testing I just press ctl+enter and bamm away it goes the
    actionscript runs as soon as the movie/game starts and ergo the
    game plays.
    My problem is this, I now want to have a start/home frame at
    the beginning (of course) which has the start game button on which
    when clicked THEN starts the game.
    Currently the game starts in the first frame along with the
    start button :(
    How do I stop the game running straight away and my first
    frame only contains the start button, which when clicked then goes
    to the 2nd frame and starts the game?
    Reagrds,
    Red.

    A friend resolved the issue for me;
    By renaming the main contrustor and calling this in the start
    button Example action script applied to the button:
    START OF ACTION SCRIPT
    import flash.events.MouseEvent;
    stop();
    startBTN.addEventListener(MouseEvent.CLICK, startClick);
    function startClick(event:MouseEvent):void
    trace ("Button clicked");
    gotoAndStop(2);
    gameGo();
    /*gameGo() is the renamed main document class, renaming it
    prevents it from been run instanly
    and it is called from the button*/
    END OF ACTION SCRIPT

  • J2ME error to get value from variable in another class

    hi,,
    i write code for a mobile application like a tour guide..
    i had create 5 class for this application, KutaBeachDictionary MIDlet class, ListMainMenu List class, ListMenuHotel List class, HotelDes01 Form class and the last Hotel class that store all information.
    the problem is, i have [choose] variable in ListMenuHotel that contain getSelectedIndex() value, i want to take [choose] value from ListMenuHotel class to [index] variable in HotelDes01, so it determine the name of hotel that will display in form.but the index always 0 although i had choosen different menu from ListMenuHotel..
    here is all code
    in MIDlet class
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.midlet.MIDlet;
    public class KutaBeachDictionary extends MIDlet {
        public KutaBeachDictionary() {
            lstMenuUtama = new ListMenuUtama(this);
            lstMenuHotel = new ListMenuHotel(this);
            htlDes1 = new HotelDes01(this);
            frmLoading = new FormLoading(this);
        public Display getDisplay() {
            return Display.getDisplay(this);
        public void exitMIDlet() {
            switchDisplayable(null, null);
            destroyApp(true);
            notifyDestroyed();
        public void startApp() {
            if (midletPaused) {
                resumeMIDlet();
            } else {
                initialize();
                startMIDlet();
            midletPaused = false;
            getDisplay().setCurrent(frmLoading);
            new Thread(frmLoading).start();
            frmLoading.done = false;
            frmLoading.gLoading.setValue(0);
        public void pauseApp() {
            midletPaused = true;
        public void destroyApp(boolean unconditional) {
        private boolean midletPaused = false;
        public ListMenuHotel lstMenuHotel;
        public ListMenuRestaurant lstMenuRestaurant;
        ListMenuUtama lstMenuUtama;
        FormAbout frmAbout;
        public HotelDes01 htlDes1;
        FormLoading frmLoading;
    }the code in ListMenuHotel
    import java.io.IOException;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.List;
    import javax.microedition.lcdui.Ticker;
    public class ListMenuHotel extends List implements CommandListener {
        Hotel objHotel = new Hotel();
        ListMenuHotel(KutaBeachDictionary run) {
            super("List Hotel", List.IMPLICIT);
            this.run = run;
            try {
                btnImage = Image.createImage("/btnImage.png");
            } catch (IOException e) {
            tickerMenu = new Ticker("Daftar Hotel di Pantai Kuta Bali");
            setTicker(tickerMenu);
            for (int i = 0; i < objHotel.namaHotels.length; i++) {
                append(objHotel.namaHotels, btnImage);
    addCommand(new Command("Select", Command.OK, 0));
    addCommand(new Command("Back", Command.BACK, 0));
    setCommandListener(this);
    public void commandAction(Command cmd, Displayable dsp) {
    if (cmd == SELECT_COMMAND) {
    choose = getSelectedIndex();
    Display.getDisplay(run).setCurrent(run.htlDes1);
    switch (cmd.getCommandType()) {
    case Command.BACK:
    Display.getDisplay(run).setCurrent(run.lstMenuUtama);
    break;
    public int getChoose() {return choose;}
    private KutaBeachDictionary run;
    private Image btnImage;
    private Ticker tickerMenu;
    private int choose;
    the code in HotelDes01 Form classimport java.io.IOException;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.ImageItem;
    public class HotelDes01 extends Form implements CommandListener {
    private KutaBeachDictionary run;
    private int index;
    private Hotel isiHotel = new Hotel();
    public HotelDes01(KutaBeachDictionary run) {
    super("Inna Kuta Hotel");
    index = run.lstMenuHotel.getChoose(); //here is the problem..the value remain 0 althought i choose another??!!
    this.run = run;
    Image imgHotel = null;
    String namaHotel = "\n" + isiHotel.namaHotels[index] + "\n";
    try {
    imgHotel = Image.createImage("/HotelImage/interface/htlDes1.png");
    } catch (IOException e) {
    append(new ImageItem(null, imgHotel, ImageItem.LAYOUT_CENTER, null));
    append(namaHotel);
    addCommand(new Command("Back", Command.BACK, 0));
    setCommandListener(this);
    public void commandAction(Command cmd, Displayable dsp) {
    switch (cmd.getCommandType()) {
    case Command.BACK:
    Display.getDisplay(run).setCurrent(run.lstMenuHotel);
    break;
    can someone fix the code,, i had tried so many ways,,but completely failure.. T_T
    Edited by: diaca on Mar 22, 2010 7:55 AM
    Edited by: diaca on Mar 22, 2010 8:01 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    hei bro,i had solved the problem :)
    the problem is , i had constructed the form of hotelDes01 each time the program starting with this code
    public class KutaBeachDictionary extends MIDlet {
        public KutaBeachDictionary() {
            //.. declaring several new object
            htlDes1 = new HotelDes01(this);
        //..another procedure like startApp, pauseApp, etc
    public HotelDes01 htlDes1;
    }i think if i declare this class in the beginning it never updated the index value
    so i delete the code above, and i declare the htlDes1 in the listMenuHotel like this:
    public class ListMenuHotel extends List implements CommandListener {
        //..several code just like before
    public void commandAction(Command cmd, Displayable dsp) {
            if (cmd == cmdSelect) {
               objHotel.setChoose(getSelectedIndex()); //i change the code like this
               showInformation();
            if (cmd == cmdBack) {
                Display.getDisplay(run).setCurrent(run.lstMenuUtama);
        public void showInformation() {
            HotelDescription htlDes1 = new HotelDescription(run); //reconstruct the object in the class ListMenuHotel
            Display.getDisplay(run).setCurrent(htlDes1); //display the object
        }so the form of hotelDes01 now always reconstruct whenever user change the election in ListMenuHotel class and now index value get updated.. :D
    thanks for trying to fix the code qnat..
    this is my coursework, so i get to finish it ASAP..

  • Passing values from JTextField to another class

    Hi,
    I have 2 classes...one is main and the other is a RequestForm class which is instantiated by main class using
    RequestForm application =new RequestForm();
    the constructor for the RequestForm displays the form in which the users enters his/her personal data...
    now my problem is how should i return those values back to main class...ne suggestions would be greatly appreatiated....
    sample code from RequestForm
    public void actionPerformed(ActionEvent event) {
    pressed: " + event.getActionCommand());
    if (event.getSource() == submitbutton){
         String name = namefield.getText();
         int id = Integer.parseInt(idfield.getText());
         String email = emailfield.getText();
         String title = titlefield.getText();
         String location = locfield.getText();
         String contact = contactfield.getText();
    .......      

    This should help...
    As you can see I'm passing a reference of Main into the RequestForm class and then I use that reference to call a method in the Main class.
    V
    public class Main {
       int id = 0;
       String email = "";
       String title = "";
       String location = "";
       String contact = "";
       public Main() {
          new RequestForm(this);
       public set(String _email, int _id, String _title, String _location, String _contact) {
          email = _email;
          id    = _id;
          title = _title;
          location = _location;
          contact = _contact;
    public RequestForm {
       Main main;
       public RequestForm(Main _main) {
          main = _main;
       public void actionPerformed(ActionEvent event) {
          if (event.getSource() == submitbutton){
             String name = namefield.getText();
             int id = Integer.parseInt(idfield.getText());
             String email = emailfield.getText();
             String title = titlefield.getText();
             String location = locfield.getText();
             String contact = contactfield.getText();
             main.set(name, id, email, title, location, contact);
    }

Maybe you are looking for