Page 1 of 2 12 LastLast
Results 1 to 20 of 26
  1. #1
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default Return result from JOptionPane to JFrame

    Hi.
    I have Frame and button in that Frame. When I click on the button it opens
    Dialog. In that Dialog is button. When I click on that button it returns something to the frame (for example draw Rectangle or Oval).

    I have tried few times, but it wasn't good :-(

    My thinking:
    class NewFrame extends JFrame
    class NewPanel extends JPanel
    in NewPanel I have button.add(ActionListener)

    NewDialog extends JDialog
    DialogPanel extends JPanel
    in DialogPanel there is dialogButton.add(ActionListener)

    Problem is how with using mouse clicks on dialogButton to affect the change of NewFrame (for example draw Rectangle in that NewFrame).
    Please give me advice.
    Last edited by cselic; 05-07-2010 at 07:08 PM.

  2. #2
    sathishsengg is offline Member
    Join Date
    Jan 2010
    Posts
    10
    Rep Power
    0

    Default

    two more ways to achieve your goal, see the below code-snippet. you can also write your own event handler.

    Java Code:
    class DialogPanel extends JPanel
    {
    	NewFrame nf;
    	DialogPanel(NewFrame nf)
    	{
    		this.nf=nf;
    	}
    	public void actionPerformed(ActionEvent ae)
    	{
    		...
    		nf.setShape(oval);
    		.....
    	
    	}
    	
    }
    class  NewDialog extends JDialog
    {
    	DialogPanel dp;
    	
    	NewDialog(NewFrame nf)
    	{
    		dp=new DialogPanel(nf);	
    	}		
    }
    
    
    class NewFrame extends JFrame
    {
    	int shape;
    	NewPanel np;
    	public NewFrame()
    	{
    		np=new Newpanel(this);
    	}	
    	public void setShape(int shape)
    	{
    			....
    	}
    }
    class NewPanel extends JPanel
    {
    	NewFrame nf;
    	Newpanel(NewFrame nf)
    	{
    		this.nf=nf;
    	}
    	public void actionPerformed(ActionEvent ae)
    	{
    		new NewDialog(nf).show();	
    	}
    }
    ------------

    another way, nf is the object of NewFrame see the above code-snippet

    class NewFrame extends JFrame
    class NewPanel extends JPanel
    in NewPanel I have button.addActionListener(nf)

    NewDialog extends JDialog
    DialogPanel extends JPanel
    in DialogPanel there is dialogButton.addActionListener(nf)

  3. #3
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Thank you. This was very useful.
    I still have not succeeded to write it :(

    I probably do not think well, and I'm using worse ways of programming.
    I'll keep trying.

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

    Default

    Quote Originally Posted by cselic View Post
    Thank you. This was very useful.
    I still have not succeeded to write it :(
    You may get better help if you can show us how you are trying at present. Post a very small compilable program that does nothing but tries to demonstrate this effect that you're after and let us analyze it.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

  6. #6
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Let's simplify it. I want to return some value from Dialog to Frame.
    For example:
    I have Frame and Dialog. When I click on Frame's button it opens Dialog. When I click on Dialog's button its change Frame's label text.

    Code of this example:
    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JTextArea;
    import javax.swing.WindowConstants;
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    
    public class DialogExample {
    	public static void main(String[] args) {
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			
    			@Override
    			public void run() {
    				NewFrame frame = new NewFrame();
    				frame.showFrame();
    			}
    		});
    	}
    
    }
    
    class NewDialog extends JDialog {
    	JTextField textField = new JTextField(20);
    	JTextArea textArea = new JTextArea(20,6);
    	JButton button = new JButton("Ok");
    	
    	public NewDialog() {
    		Container content = getContentPane();
    		content.add(textField,BorderLayout.NORTH);
    		content.add(textArea);
    		content.add(button, BorderLayout.SOUTH);
    		
    		button.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				NewFrame frame = new NewFrame();
    				frame.setLabelText("Label is changed");
    			}
    		});
    		
    		setLocationRelativeTo(null);
    		setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    		setSize(new Dimension(300,200));
    		
    		setVisible(false);
    	}
    	
    	public void showDialog() {
    		setVisible(true);
    	}
    	public String getTextFromTextField() {
    		return textField.getText();
    	}
    }
    
    class NewFrame extends JFrame {
    	NewDialog dialog = new NewDialog();
    	JLabel label;
    	
    	public NewFrame() {
    		Container content = getContentPane();
    		
    		JButton buttonOpenDialog = new JButton("Open a dialog");
    		label = new JLabel("Label not changed");
    		//content.add(dialog);
    		setLayout(new FlowLayout());
    		content.add(buttonOpenDialog);
    		content.add(label);
    		
    		buttonOpenDialog.addActionListener(new ActionListener() {
    			
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				dialog.showDialog();
    			}
    		});
    	}
    	public void showFrame() {
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(new Dimension(400,400));
    		setVisible(true);
    	}
    	
    	public void setLabelText(String text) {
    		label.setText(text);
    	}
    }
    Last edited by cselic; 05-09-2010 at 12:30 AM.

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

    Default

    Quote Originally Posted by Darryl.Burke View Post

    Your problem is simple, a lack of object references, but please understand that many here, myself included, will not answer cross-posted questions as we are loathe to put in the effort to answer a question that has already been answered elsewhere.

    Much luck in the future.
    Last edited by Fubarable; 05-09-2010 at 12:36 AM.

  8. #8
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Cross posted
    Return result from JOptionPane to JFrame - Java Programming Forums
    Yes. :D
    I have posted this thread on that forum, too.
    But, as you can see, the java-forums.org dominates.
    This forum is the best. :cool:

  9. #9
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    that has already been answered elsewhere.
    It hasn't answered, yet. it hasn't marked as SOLVED, yet.
    Read it carefully.
    Last edited by cselic; 05-09-2010 at 12:59 AM.

  10. #10
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    a lack of object references
    I fix it with:
    Java Code:
    button.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				 NewDialog d = new NewDialog();
    			        for (Window w : JDialog.getWindows()) {
    			                if ( w instanceof NewFrame) {
    			                	(((NewFrame) w).setLabelText(setTextInLabel()));
    			                }
    			}
    		}});
    I, still had some errors in program. I'll try to fix them later.
    Program:
    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JTextArea;
    import javax.swing.WindowConstants;
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Window;
    
    public class DialogExample {
    	public static void main(String[] args) {
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			
    			@Override
    			public void run() {
    				NewFrame frame = new NewFrame();
    				frame.showFrame();
    			}
    		});
    	}
    
    }
    
    class NewDialog extends JDialog {
    	String labelText = "Label is not changed";
    	JTextField textField = new JTextField(20);
    	JTextArea textArea = new JTextArea(20,6);
    	JButton button = new JButton("Ok");
    	
    	public NewDialog() {
    		Container content = getContentPane();
    		content.add(textField,BorderLayout.NORTH);
    		content.add(textArea);
    		content.add(button, BorderLayout.SOUTH);
    		 
    		button.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    			//	labelText = "Label is changed";
    				 NewDialog d = new NewDialog();
    			        for (Window w : JDialog.getWindows()) {
    			                if ( w instanceof NewFrame) {
    			                	(((NewFrame) w).setLabelText(setTextInLabel()));
    			                }
    			}
    		}});
    		
    		setLocationRelativeTo(null);
    		setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    		setSize(new Dimension(300,200));
    		
    		setVisible(false);
    	}
    	
    	public void showDialog() {
    		setVisible(true);
    	}
    	
    	public String setTextInLabel() {
    		return labelText;
    	}
    }
    
    class NewFrame extends JFrame {
    	//NewFrame frame = new NewFrame();
    	NewDialog dialog = new NewDialog();
    	String setTextOfLabel ="";
    	JLabel label;
    	
    	public NewFrame() {
    		//this.frame = f;
    		Container content = getContentPane();
    		
    		JButton buttonOpenDialog = new JButton("Open a dialog");
    		label = new JLabel(dialog.setTextInLabel());
    		setLayout(new FlowLayout());
    		content.add(buttonOpenDialog);
    		content.add(label);
    		
    		buttonOpenDialog.addActionListener(new ActionListener() {
    			
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				dialog.showDialog();
    			}
    		});
    	}
    	public void showFrame() {
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(new Dimension(400,400));
    		setVisible(true);
    	}
    	
    	public void setLabelText(String text) {
    		label.setText(text);
    	}
    }

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

    Default

    You can push the data from the JDialog to the JFrame, but I prefer that the JFrame pull the data from the JDialog. It allows looser coupling:

    Java Code:
    public class DialogExample2 {
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
          @Override
          public void run() {
            NewFrame2 frame = new NewFrame2();
            frame.showFrame();
          }
        });
      }
    
    }
    
    class NewDialog2 extends JDialog {
      //private String labelText = "Label is not changed";
      private JTextField textField = new JTextField(20);
      private JTextArea textArea = new JTextArea(20, 6);
      private JButton button = new JButton("Ok");
      private boolean exitClean = false;
    
      public NewDialog2() {
        Container content = getContentPane();
        content.add(textField, BorderLayout.NORTH);
        content.add(textArea);
        content.add(button, BorderLayout.SOUTH);
    
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            exitClean = true;
            NewDialog2.this.dispose();
          }
        });
    
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        setSize(new Dimension(300, 200));
    
        setVisible(false);
      }
      
      public void setExitClean(Boolean exitClean) {
        this.exitClean = exitClean;
      }
      
      public boolean isExitClean() {
        return exitClean;
      }
    
      public void showDialog() {
        exitClean = false;
        setVisible(true);
      }
      
      public String getTextField() {
        return textField.getText();
      }
      
      public String getTextArea() {
        return textArea.getText();
      }
    
    }
    
    class NewFrame2 extends JFrame {
      private NewDialog2 dialog = new NewDialog2();
      private JLabel label;
    
      public NewFrame2() {
        Container content = getContentPane();
    
        JButton buttonOpenDialog = new JButton("Open a dialog");
        label = new JLabel("Initial Label Text");
        setLayout(new FlowLayout());
        content.add(buttonOpenDialog);
        content.add(label);
    
        buttonOpenDialog.addActionListener(new ActionListener() {
    
          @Override
          public void actionPerformed(ActionEvent e) {
            //[color="red"]Error in code here.  Please see post below for correction.[/color]
            dialog.addWindowListener(new WindowAdapter() {
              public void windowClosed(WindowEvent e) {
                // check that window closed due to button press
                if (dialog.isExitClean()) {
                  label.setText(dialog.getTextField());
                }
              }
            });
            dialog.showDialog();
          }
        });
      }
    
      public void showFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(new Dimension(400, 400));
        setVisible(true);
      }
    
      public void setLabelText(String text) {
        label.setText(text);
      }
    }

    If you decide to use a modal dialog, then there's no need for the WindowListener (WindowAdapter).

    Error in the above code. Please see below for correction.
    Last edited by Fubarable; 05-10-2010 at 02:39 AM. Reason: error in code notification

  12. #12
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    This solution is great. Thank you for your patience and time you devoted
    solving this problem.

    I do not have big knowledge about WindowListener (WindowAdapter).
    I will immediately begin to learn it.

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

    Default

    Quote Originally Posted by cselic View Post
    This solution is great. Thank you for your patience and time you devoted
    solving this problem.

    I do not have big knowledge about WindowListener (WindowAdapter).
    I will immediately begin to learn it.
    But as noted above, if you place your JPanel in a modal JDialog or a JOptionPane (which in essence is a modal JDialog), then there's no need to use a WindowListener since the flow of the program in the calling window halts when the modal dialog is set visible, and then resumes at the same place once the dialog has been made invisible or disposed of. It is at that point in the program you can pull the information out of the JPanel that was displayed in the dialog.

    Much luck.

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

    Default

    Hang on a second and I'll show you what I mean...

  15. #15
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Thank you.
    I will have to devote some time for learning JOptionPane and modal Dialog, too. ;)

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

    Default

    For example, using a modal dialog (this time a JOptionPane)

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DialogExample3Test {
      public DialogExample3Test() {
        
      }
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Dialog Example 3");
        frame.getContentPane().add(new DialogExample3Gui(5).getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }
    
    class DialogExample3Gui {
      private JPanel mainPanel = new JPanel();
      private JTextField[] fields;
      private DialogExampleWindow2 window2;
      
      public DialogExample3Gui(int fieldCount) {
        window2 = new DialogExampleWindow2(fieldCount);
        fields = new JTextField[fieldCount];
        JButton showDialogBtn = new JButton("Show Dialog");
        showDialogBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(mainPanel, window2.getPanel(), 
                "Enter Text", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
              for (int i = 0; i < fields.length; i++) {
                fields[i].setText(window2.getFieldText(i));
              }
            }
          }
        });
        
        int eb = 10;
        mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
        mainPanel.setLayout(new GridLayout(0, 1, 0, eb));
        for (int i = 0; i < fields.length; i++) {
          fields[i] = new JTextField(10);
          fields[i].setEditable(false);
          fields[i].setFocusable(false);
          mainPanel.add(fields[i]);
        }
        mainPanel.add(showDialogBtn);
      }
    
      public JPanel getMainPanel() {
        return mainPanel;
      }
    
    }
    
    class DialogExampleWindow2 {
      private JTextField[] fields;
      private JPanel panel = new JPanel();
      
      public DialogExampleWindow2(int fieldCount) {
        int gap = 5;
        panel.setLayout(new GridLayout(0, 1, 0, gap));
        fields = new JTextField[fieldCount];
        for (int i = 0; i < fields.length; i++) {
          fields[i] = new JTextField(10);
          panel.add(fields[i]);
        }
      }
      
      public JPanel getPanel() {
        return panel;
      }
      
      public String getFieldText(int index) {
        if (index < 0 || index >= fields.length) {
          throw new ArrayIndexOutOfBoundsException("bad index: " + index);
        }
        return fields[index].getText();
      }
      
    }

  17. #17
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    I have looked only the first program, in details, so far.

    Java Code:
    buttonOpenDialog.addActionListener(new ActionListener() {
    
          @Override
          public void actionPerformed(ActionEvent e) {
            dialog.addWindowListener(new WindowAdapter() {
              public void windowClosed(WindowEvent e) {
                // check that window closed due to button press
                if (dialog.isExitClean()) {
                  label.setText(dialog.getTextField());
                }
              }
            });
            dialog.showDialog();
          }
        });
      }
    I'm flattered, and impressed. These are excellent techniques and programming skills. With a few lines of code has been done many things.

    click on the button -> see if dialog window is closed (and window is closed when dialog button is pressed) -> well if it's closed set label text.

    Three listeners: second inside the first, and third is inserted into the second. It's brilliant.

    I will now look in details, second program.
    Last edited by cselic; 05-09-2010 at 11:21 PM.

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

    Default

    On review of my posts I must apologize as I gave bad advice in my DialogExample2 code. In the example, I added a WindowListener to the JDialog from within the JButton's ActionListener actionPerformed method which means that a new WindowListener will be added to the JDialog every time the button is pressed which is not good. You just want one WindowListener added to the JDialog, that's it, and it would be best to add it from the class's constructor and not from an ActionListener's actionPerformed method. The changes I suggest are here:

    Java Code:
      public NewFrame2() {
        Container content = getContentPane();
    
        JButton buttonOpenDialog = new JButton("Open a dialog");
        label = new JLabel("Initial Label Text");
        setLayout(new FlowLayout());
        content.add(buttonOpenDialog);
        content.add(label);
    
        // !! Added here
        dialog.addWindowListener(new WindowAdapter() {
          public void windowClosed(WindowEvent e) {
            // check that window closed due to button press
            if (dialog.isExitClean()) {
              label.setText(dialog.getTextField());
            }
          }
        });
    
        buttonOpenDialog.addActionListener(new ActionListener() {
    
          public void actionPerformed(ActionEvent e) {
            // !! add window listener removed from here.
            dialog.showDialog();
          }
        });
      }
    Again, sorry for the misleading code.

  19. #19
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    This is the text of a PM sent to me by "cselic"

    Listen to me, you stupid.
    You're trying to destroy my efforts of writing a good code.
    when D.B. need to help, and do some constructive things, he's not here, he's not useful. But, hey, when it's there something to be destructive you're the first.
    I know those people who appear to be destructive.
    I hate that kind of people.
    Because of thath, I'll give you a few orders:
    1. never do reply with posts on my threads.
    2. give an apology for your behavior is destructive.
    cselic, as I asked you on another forum: if you consider cross posting wrong, then why did you do it in the first place?

    I see you also cross posted your earlier question "Sort in Cyrillic order" and didn't bother to inform either forum of the discussions on the other one.

    Writing vitriolic and insulting PMs isnt' going to help you. I've already reported your message as I'm sure it's in violation of the rules for the site. Oh, and you can't stop me from responding in your threads, nor from pointing out any more cross posts I happen to come across.

    db

  20. #20
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Why do you immediately try to put moderators by your side?!

    I do not understand your need for spamming this interesting topic
    If you want to get into a conflict better find another person. I have no time for squabbling.
    If you want to fully discuss some things about me open a new thread.

    Here is the primary goal of better writing code, and philosophical discussions are secondary.

Page 1 of 2 12 LastLast

Similar Threads

  1. JOptionPane to JFrame
    By mitty in forum New To Java
    Replies: 5
    Last Post: 04-12-2010, 04:57 PM
  2. Replies: 6
    Last Post: 04-12-2010, 11:33 AM
  3. Methods, JOptionPane, Return Values
    By Cubba27 in forum New To Java
    Replies: 2
    Last Post: 12-04-2009, 02:46 AM
  4. Passing data from one JFrame to another JFrame
    By tarami in forum New To Java
    Replies: 3
    Last Post: 08-06-2009, 05:44 PM
  5. Replies: 4
    Last Post: 04-22-2009, 11:02 PM

Posting Permissions

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