Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Swing: How to access variables in a 2nd frame from the first frame?
    text
    copied!<p>I'm programming a desktop application in <strong>Java</strong> using <strong>NetBeans</strong>.</p> <p>My question is this:</p> <p>1st: I have a Jframe that is the principal frame of the application. </p> <p>2nd: In some moment I want to create a new object of some kind, so I press addButton y create a new JFrame (I create a new class window that extends Jframe) with some text fields in it.</p> <pre><code>private void addButtonMouseClicked(java.awt.event.MouseEvent evt) { w = new window(); w.setVisible(true); } </code></pre> <p>this is a screenshot simplified with a simple string instead of a full class <a href="http://img820.imageshack.us/img820/3361/screenshotlw.png" rel="nofollow noreferrer">http://img820.imageshack.us/img820/3361/screenshotlw.png</a></p> <p>3rd: In this new window have I read the text fields and create the object when I press some button.</p> <p>Finally when I press the accept button I want the new frame to get the object in the 2nd frame.</p> <p><strong>Question</strong>: what is the most elegant/efficient/easy/better way of getting the object in the 2nd frame from the first one?.</p> <p><strong>My First Solution:</strong> was to create a static method <code>setNewData()</code> on the first windows, and the second windows calls this method when you press the button.</p> <p>Now I came with a <strong>New Solution</strong>: On the second frame I have a method to set a mouselistener on the button. And a <code>getString()</code> Function.</p> <p>On the first frame I got this:</p> <pre><code>private void addButtonMouseClicked(java.awt.event.MouseEvent evt) { w = new window(); w.setHandler(ml); w.setVisible(true); } MouseListener ml = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { TextFieldOn1stFrame.setText(w.getString()); } }; </code></pre> <p>And on the second frame I got this</p> <pre><code>public void setHandler(MouseListener ml){ button1.addMouseListener(ml); } public String getString(){ return texto.getText(); } </code></pre> <p>Note: Sorry for the Long Text, I'm new on java and don't know if this solutions are the best. btw sorry about my english too.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload