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 );

Similar Messages

  • 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);
    }

  • Get the values of hashmap in another class

    Hi All,
    i already posted this topic yesterday..But i did not get any helpful response..Kindly help me because I am new to java and I need some help regarding hashmap..
    I have a one value object java class which name is HashTestingVO.java
    *******************************************INPUT OF HashTestingVO.java***************************************
    public class HashTestingVO extends PersistentVO implements ILegalWorkFlowACLVO {
    public final static HashMap legalReviewPieceRelatedACLMap = new HashMap();
    legalReviewPieceRelatedACLMap.put("Futhure Path Check","ereview_acl_piece_related_cat1");
    legalReviewPieceRelatedACLMap.put("Send to Legal Review","ereview_acl_piece_related_cat1");
    legalReviewPieceRelatedACLMap.put("Review Precondition","ereview_acl_piece_related_cat1");
    Now i want to get the Hash Map values of this in another class called Testing.java class
    Ex: i need the value like this in Testing.java
    HashTestingVO obj=new HashTestingVO();
    obj.get(Futhure Path Check) -----------> I want to get the value of key1
    Public means you can access it another class..
    But Static means within the class we will use it...

    already posted this topic yesterday..But i did not get any helpful response..Kindly help me because I am new to java and I need some help regarding hashmap..I thing Exposing your dataStructure to any other class is not the right practise.
    You can make the Hashmap object private and nonstatic and provide a getter method in this class to get the value corresponding to any particular key.
    public Object getValue(String key)
      return egalReviewPieceRelatedACLMap.get(key);
    }

  • How can I pass a value from Client to EntityImpl class?

    Hi everyone,
    I am using ADF BC to develop my Application.
    I want to do something in the EntityImpl class.
    My job needs a value from Client.
    I can't find any way to slove the problem.
    Is there anyone have an ideal, please tell me.
    Thanks,
    Tuan Vu Minh
    FPT Software Solution Company (Oracle partner)
    FPT Coporation
    Add: 3th Fl., 51 Le Dai Hanh Builiding,
    Hai Ba Trung Dist,
    Hanoi,
    The Socialist Republic of VietNam
    Tel: (84,4) 9745476
    Fax: (84,4) 9754475
    Email: [email protected]
    Website: http://www.fss.com.vn , http://www.fpt.com.vn

    Firstly, let me state that I'm not a Swing programmer, so your mileage may vary. However I don't think a Swing solution is what you need. ADF BC will do this for you.
    Assumptions on my answer:
    1) You're generating the log_id from a database sequence and it is automatically populated in the UserLog table.
    2) You have 2 VOs, namely UserLogView and ActionLogView based on the EOs.
    Create a View Link between each VO making UserLogView the master.
    In your UI, once the user has inserted into UserLogView, include a bound create button for the ActionLogView such that it creates an associated ActionLogView record for the user when they wish to enter the log details. ADF BC will populate the ActionLogView Log_id with the parent's UserLogView log_id automatically. You'll then need to navigate to the ActionLogView screen to allow the user to enter the rest of the details.
    As such, you don't need to expose the log_id to the client, ADF BC will take care of the population of the log_id correctly for you when creating the detail record.
    Another approach may be to define one VO encompassing both EOs, where the ActionLog is a reference. Look at the JDevelope help page "View Object Wizard - Entity Objects Page", specifically at the "Reference" section for more info. You'll need to test out the updateable flag for both EOs defined within the VO to ensure you can update the values of both.
    Test this out in the Business Components Browser before writing the UI to see if the ADF BC solution works, and saving you time in writing the UI.
    Hope this helps.
    CM.

  • 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

  • Passing values from method array to class array

    HELP!! Plz excuse any ignorance. Am a noob and have created an array within my class. I then try to alter those array values from inside one of the classes methods. When I try to access the new values from the class array, they don't exist. I think it's a duration/scope issue and am struggling to get around it. This is the only way I can implement the task required and would appreciate any advice you can thorw. cheers in advance.. =~D

    I suspect that you're altering an array passed as a parameter, rather than array that's a field of the instance, but as you didn't post any of your code, that can only be a guess.

  • How to update and use the values of variables of another class

    I can we update or use the values of the variables of another class. For example, if we have class A
    public class A //(situated in package view)
    public s0,s1;
    public void runFunction()
    ...some coding and proceedings
    s0="Hi";s1"Hello";
    ......some coding
    RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp?alert=F");
    dispatcher.forward(request, response);
    ARunner.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    a.runFunction();
    %>
    MainUser.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
    %>
    A.class has some procedures and String variables which can be updated and later can be used in JSP pages. The project starts with ARunner.jsp which uses the A.class and updates the values of string variables s0 and s1of A to hi and hello respectively.And then redirects the page to MainUser.jsp.
    Now what I want is ,when I call those string variables(s0 & s1 of A.class) in any another jsp likeMainUser.jsp it should give me the value of hi and hello respectively not null as it is giving right now. Could you refine the coding for this one?

    public class A //(situated in package view)
    public String s0,s1;
    public void runFunction()
    ...some coding and proceedings
    s0="Hi";s1"Hello";
    ......some coding
    RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp");
    dispatcher.forward(request, response);
    ARunner.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    a.runFunction();
    %>
    MainUser.jsp
    <jsp:useBean id="a" class="view.A" scope="session"/>
    <%
    System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
    %>
    giving code again to remove the typing errors. Please guide.

  • How to send a String value  from Servlet to  Action class in Struts .

    when iam trying to send string value from Servlet to Struts Action class through Http Session, iam getting null value, iam really in big confusion, help me.

    please elaborate clearly or put you code of both action and servlet here
    Are both of them in same web application

  • Get a value from the method to class in workflow

    Hi Expert,
         I am doing a workflow and passing a value when submiting  and i need to get the passing value in the Class for further info,
    ****Instantiate an empty event container
      CALL METHOD cl_swf_evt_event=>get_event_container
        EXPORTING
          im_objcateg  = cl_swf_evt_event=>mc_objcateg_cl
          im_objtype   = iv_objtype
          im_event     = iv_event
        RECEIVING
          re_reference = lr_event_parameters.
    *****Set up the name/value pair to be added to the container
      lv_param_name = 'LEVEL'.
      lv_level = wd_this->adlvl.
    ****Add the name/value pair to the event conainer
      TRY.
          CALL METHOD lr_event_parameters->set
            EXPORTING
              name  = lv_param_name
              value = lv_level.
    CALL METHOD cl_swf_evt_event=>raise
            EXPORTING
              im_objcateg        = ls_sibflpord-catid
              im_objtype         = ls_sibflpord-typeid
              im_event           = iv_event
              im_objkey          = ls_sibflpord-instid
              im_event_container = lr_event_parameters.
    I Created a Customised Class zcl_asset and  i need to get the iv_event or  lv_level  value which i passing in the above method to process further to determine the approver in my customised  zcl_asset class.
    Thanks,
    Regards,
    Deeesanth

    >I am doing a workflow and passing a value when submiting and i need to get the passing value in the Class for further info,
    Look, this is not really possible. You cannot pass a value with your code to a class (whatever you mean by this?). With your method you are triggering an event with a parameter. It is possible to "catch" this event and its parameter from workflow. Then your parameter value will be in your workflow and you can use it later (with your class).
    So for example, if you start a workflow with your code, you can create a container element into the workflow, and then with simple binding (in workflow editor) you can get your parameter value into the container element.
    Regards,
    Karri

  • 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.

  • Passing value from Forms to another Portal Object

    Hi,
    I created a Portal form and a customised button to display another form ,but i need to send the value of one of the field in the URL. write now i call the other form in the (OnClick)Java Event Handler of the Button , but it's not recognizing the variable i declare for the filed value
    Thanks.

    Hi,
    I am doing something similar to what you have described. I have a custom login form with a hidden field(not login/password) which I need to pass to the next form. I tried calling the form like you have explained, but it's not working. The control goes to
    http://portalhost:7777/pls/portal/!PORTAL.wwa_app_module.accept
    and it gives a page not found error.
    Where do I need to place the pl-sql code? I have tried pasting it in the after processing section in the Additional PL/SQL Code tab, as well as in the Submit section of the PL/SQL Button Event Handler, for the Login button. Both don't work...
    Please help!
    Thanks,
    Somya

  • Executing another class from another package with a click of a button

    package language;
    textfield_4 = new JTextField();
    getContentPane().add(textfield_4);
    button_10 = new JButton("Open");
        getContentPane().add(button_10);
        button_10.addActionListener(new java.awt.event.ActionListener()
          public void actionPerformed(ActionEvent e)
            String cmd = "notepad.exe";
            String path = textfield_4.getText();
            try
              Runtime.getRuntime().exec(cmd + " \"" + path + "\"");
            catch (IOException ex)
              ex.printStackTrace();
        button_12 = new JButton("Run");
        getContentPane().add(button_12);From the codes above, what i intended to do is when clicking the "Run" button, it will pass the values from textfield_4 to another class in another package thus, executing the class with the value of textfield_4. What are the steps to do that? If possible, please insert sample codes. Thank you.

    import  anyPackage.AnotherClass;
    button_12.addActionListener(new ActionListener() {
      AnotherClass ac = new AnotherClass();
      ac.execute(textfield_4.getText());
    });Is that what you wanted?

  • Access data of one class from another class

    Hi,
    I am creating one class say ClassA with some data members,the same class has main() method on execution of which the data members will b assigned a value.
    now i have another class say ClassB with main() method and i want to use the data in ClassA in ClassB do i have any way by which i can have access to that data.
    The instance of ClassA created in ClassB is not showing any values in data members.
    Can u help me find a solution for this.
    Thank you.
    Parag.

    I have tried by making one data member public so that it can have direct access from other class.But it shows null value.
    The problem is that ClassA class data members are assigned values when it completes the execution of function main() so does it retains the values.
    c sample code below.
    public classA{
    int a,b;
    p s v m(String [] args)
    setab();
    public void setab()
    //set values of a and b by doing some manipulations.
    public classB{
    p s v m(string []args)
    classA aclass = new classA();
    /* now what should i do to access the values of a & b in
    aclass object*/
    i strictly need to follow this way do i have a way out.

  • Values from JSP to Struts Action Class

    Dear All,
    Am working on a small struts project, i want to get values from JSP in the Action class, i tried with sending variables using request through URL, it works fine, any other way is there to send the values from JSP to action class. Am not having any input fields in the JSP.I have links.
    Thanks,
    vyrav.

    I have a dispatch action for that am calling the action like this viewfiles.do?parameter=edit, and i have to send a variable ID from the same page, so am doing like this through java script, viewfiles.do?parameter=edit&id=10. Am able to get the id in the dispatch action edit, but when i start tomcat with security manager its not calling the action itself and its giving accesscontrol exception, but when i directly type viewfiles.do in URL its calling the action.
    I dont know wats the problem, tomcat security manager not allowing this. Please help me.
    Thanks,
    vyrav.

Maybe you are looking for

  • NTP Error Logs on Nexus 5K [ ntpd[4746]: ntp:time reset +0.279670 s]

    Hi Team, We are using almost 10 Nexus 5k in our DC currently we are getting same error logs in all Nexus 5k. " ntpd[4746]: ntp:time reset +0.279670 s "  Is it major error or just for reset time?........ Please check and let me know if you need any ot

  • AE_DETAILS_GET_ERROR on XI 7.0 SP06

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> Hi experts , I have installed Xi 7.0 sp06 . As a test we tried to run a basic file to file scenario... but we get this error. <!--  Call Adapter   --> - <SAP:Error xmlns:SAP="http://sap.com/xi/

  • PL/SQL Version in Forms 9 or 10?

    I am looking for reasons to upgrade Forms. What version of PL/SQL does Forms 9 and 10 run? Thanks!

  • Missing parts

    I purchased a new Samsung refirgerator last October. I also paid for professional installation. The installation crew found one of the screws holding the door handle on was missing. They said that they would be back the next day. Here it is Aguust an

  • HP J 6400 working with Windows 8

    How can I get my HP J6400 to work with Windows  8 ? This question was solved. View Solution.