Results 1 to 7 of 7
  1. #1
    Joe2003 is offline Member
    Join Date
    Jan 2008
    Posts
    21
    Rep Power
    0

    Default Returning data from a JFrame/JDialog?!

    Hi

    Ok. I have a JFrame or JDialog, whatever. On it are 3 textboxes. When the object is closed I want to return a string array containing the data in each of the 3 textboxes.

    How can I do this? When I start a new JFrame/JDialog box the process will halt untill the object is closed, by which time all data structures contained within the object no longer exist. So a Object.getValues() type operation would fail!

    Any pointers?

    Thanks

    Joe

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class BeforeClosing {
        JTextField[] fields;
    
        private JPanel getContent() {
            String[] strs = { "user", "enters", "text" };
            fields = new JTextField[strs.length];
            JPanel panel = new JPanel();
            for(int i = 0; i < fields.length; i++) {
                fields[i] = new JTextField(strs[i], 6);
                panel.add(fields[i]);
            }
            return panel;
        }
    
        public static void main(String[] args) {
            BeforeClosing test = new BeforeClosing();
            JFrame f = new JFrame();
            // Use a WindowListener instead of
            // f.setDefaultCloseOperation(...);
            f.addWindowListener(test.closeMonitor);
            f.add(test.getContent());
            f.setSize(300,140);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    
        private WindowListener closeMonitor = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                for(int i = 0; i < fields.length; i++) {
                    System.out.printf("fields[%d] text = %s%n",
                                       i, fields[i].getText());
                }
                System.exit(0);
            }
        };
    }
    To make sure you get the kind of data you want you can use an InputVerifier, which can be frustrating/difficult for the user, or a DocumentFilter.

  3. #3
    Joe2003 is offline Member
    Join Date
    Jan 2008
    Posts
    21
    Rep Power
    0

    Default

    But are you not just using global variables? What if I am spreading this across more than one class file?

    thanks

  4. #4
    Joe2003 is offline Member
    Join Date
    Jan 2008
    Posts
    21
    Rep Power
    0

    Default

    my reasoning is in general one would not expect to have to "pull" data out of a JDialog, but instead would expect that the JDialog "pushes" changes to its model.
    This would be in line with the general ideas of MVC.

    If you have methods in the JDialog that return the data how do you know that it was time to call these get_...() methods ? How do you know that the user had finished the editing? There must be away to return a data type from the JDialog when it is closed?!
    Last edited by Joe2003; 01-08-2009 at 12:31 AM.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Joe2003 View Post
    But are you not just using global variables? What if I am spreading this across more than one class file?
    Then don't use public (not global) variables. Instead use public accessor methods that extract the information from the J-widgets.

    For instance if you have a JDialog class, MyJDialog, and it has a private JTextField called userNameField, then have a public method in this class like so:
    Java Code:
    public String getUserName()
    {
      return userNameField.getText();
    }
    Then any object that holds a MyJDialog object, myJDialog, that has displayed and then returned, you can extract the information simply by calling
    Java Code:
    String userName = myJDialog.getUserName();
    Make sense?

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Joe2003 View Post
    my reasoning is in general one would not expect to have to "pull" data out of a JDialog, but instead would expect that the JDialog "pushes" changes to its model.
    This would be in line with the general ideas of MVC.
    Either way could work with MVC. If you wanted the dialog to push changes to the model, that's simple: allow the JDialog class to accept a listener of whatever flavor you desire, and use an observer design pattern to notify observers of changes. This is probably the best way to handle non-modal dialogs.

    If you have methods in the JDialog that return the data how do you know that it was time to call these get_...() methods ? How do you know that the user had finished the editing? There must be away to return a data type from the JDialog when it is closed?!
    If you call the dialog in a modal fashion, you will know absolutely when it returns -- code flow will resume immediately after the myDialog.setVisible(true) statement.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    For instance (and sorry for this being long-winded:
    FramePanel.java
    Java Code:
    import java.awt.*;
    import java.awt.Dialog.ModalityType;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    /**
     * Creates JPanel for a JFrame Button press launches a JDialog that
     * has ability to change JPanel's label String via observer pattern.
     * Avoids extending JFrame and JDialog or any JComponents that don't need to be
     * extended -- extends by composition, not inheritance.  
     * @author Pete
     */
    public class FramePanel
    {
      private static final Dimension MAIN_SIZE = new Dimension(600, 450);
      private static final String TITLE_STRING = "Changing Title";
      private JPanel mainPanel = new JPanel(); // main JPanel
      private JDialog dialog; // our dialog
      
      // creates the JPanel that the JDialog holds
      private MyDialogPanel dialogPanel = new MyDialogPanel(TITLE_STRING);
      
      // the JLabel that is changed by the dialog
      private JLabel titleLabel = new JLabel(TITLE_STRING, SwingConstants.CENTER);
    
      public FramePanel(final JFrame frame)
      {
        // add a change listener to the dialog that will grab the 
        // String in the dialog's JTextField when notified via the observer
        // pattern
        dialogPanel.addChangeListener(new ChangeListener()
        {
          public void stateChanged(ChangeEvent arg0)
          {
            changeTitle(dialogPanel.getNewTitle());
          }
        });
        titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 32));
        
        JPanel centerPanel = new JPanel(new GridBagLayout());
        JButton showDialogBtn = new JButton("Show Dialog");
        centerPanel.add(showDialogBtn, new GridBagConstraints());
        showDialogBtn.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent arg0)
          {
            if (dialog == null)
            {
              createDialog(frame);
            }
            if (!dialog.isVisible())
            {
              dialog.setVisible(true);
            }
          }
        });
        
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setPreferredSize(MAIN_SIZE);
        mainPanel.add(titleLabel, BorderLayout.NORTH);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
      }
      
      private void createDialog(JFrame frame)
      {
        ModalityType modalityType = ModalityType.MODELESS; // non-modal dialog
        dialog = new JDialog(frame, "Dialog", modalityType);
        dialog.getContentPane().add(dialogPanel.getMainPanel()); // add JPanel to dialog
        dialog.pack();
        dialog.setLocationRelativeTo(null);
      }
    
      public void changeTitle(String title)
      {
        titleLabel.setText(title);
      }
    
      public JComponent getPanel()
      {
        return mainPanel;
      }
    
      // Create JFrame and show it in a thread-safe manner
      private static void createAndShowGUI()
      {
        JFrame frame = new JFrame("ChangingTitleFrame Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new FramePanel(frame).getPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowGUI();
          }
        });
      }
    }
    MyDialogPanel.java
    Java Code:
    import java.awt.Dimension;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class MyDialogPanel
    {
      private static final Dimension MAIN_SIZE = new Dimension(300, 150);
      private JPanel mainPanel = new JPanel();
      private List<ChangeListener> listenerList = new ArrayList<ChangeListener>();
      private JTextField newTitleField = new JTextField(15);
    
      public MyDialogPanel(String text)
      {
        newTitleField.setText(text);
        newTitleField.getDocument().addDocumentListener(new DocumentListener()
        {
          public void changedUpdate(DocumentEvent e)
          {
            notifyListeners();
          }
    
          public void insertUpdate(DocumentEvent e)
          {
            notifyListeners();
          }
    
          public void removeUpdate(DocumentEvent e)
          {
            notifyListeners();
          }
    
        });
    
        mainPanel.setPreferredSize(MAIN_SIZE);
        mainPanel.add(new JLabel("New Title Text: "));
        mainPanel.add(newTitleField);
      }
    
      public JComponent getMainPanel()
      {
        return mainPanel;
      }
    
      public void addChangeListener(ChangeListener listener)
      {
        listenerList.add(listener);
      }
    
      private void notifyListeners()
      {
        ChangeEvent ce = new ChangeEvent(this);
        for (ChangeListener listener : listenerList)
        {
          listener.stateChanged(ce);
        }
      }
    
      public String getNewTitle()
      {
        return newTitleField.getText();
      }
    
    }
    Last edited by Fubarable; 01-08-2009 at 03:41 AM. Reason: The dialog panel uses a document listener to continuously change the JLabel text

Similar Threads

  1. Passing data from one JFrame to another
    By abhiN in forum New To Java
    Replies: 2
    Last Post: 03-28-2008, 06:39 AM
  2. Replies: 0
    Last Post: 03-11-2008, 05:55 PM
  3. help with jdialog
    By leonard in forum AWT / Swing
    Replies: 1
    Last Post: 08-05-2007, 06:37 AM
  4. Close a JDialog Programmatically
    By Marcus in forum Advanced Java
    Replies: 1
    Last Post: 07-06-2007, 05:06 PM
  5. problems with jDialog in a JFrame
    By bbq in forum AWT / Swing
    Replies: 1
    Last Post: 07-05-2007, 05:14 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •