I’m programming a desktop application in Java using NetBeans.
My question is this:
1st: I have a Jframe that is the principal frame of the application.
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.
private void addButtonMouseClicked(java.awt.event.MouseEvent evt) {
w = new window();
w.setVisible(true);
}
this is a screenshot simplified with a simple string instead of a full class
http://img820.imageshack.us/img820/3361/screenshotlw.png
3rd: In this new window have I read the text fields and create the object when I press some button.
Finally when I press the accept button I want the new frame to get the object in the 2nd frame.
Question: what is the most elegant/efficient/easy/better way of getting the object in the 2nd frame from the first one?.
My First Solution: was to create a static method setNewData() on the first windows, and the second windows calls this method when you press the button.
Now I came with a New Solution:
On the second frame I have a method to set a mouselistener on the button. And a getString() Function.
On the first frame I got this:
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());
}
};
And on the second frame I got this
public void setHandler(MouseListener ml){
button1.addMouseListener(ml);
}
public String getString(){
return texto.getText();
}
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.
Well, I don’t have enough rep to comment on mangst’s solution, but wanted to add that with your usage of the words elegant and efficient, this seemed like a prime opportunity for some design patterns.
What mangst has described is an implementation of the Observer pattern (http://en.wikipedia.org/wiki/Observer_design_pattern). I would, however, suggest having a collection of objects implementing the interface as suggested by mangst. This way, upon a given update you are able to iterate through many observers to perform some action in each, whether that is changing data, presentation, etc. Should multiple windows ever need to receive the data/action from your child window it’s simple to just add another to the list of Observers you already have.
There is also the Mediator pattern (http://en.wikipedia.org/wiki/Mediator_pattern) which could accomplish similar results.
There are a lot of cookie cutter approaches for very common computing problems, and by familiarizing yourself with the lexicon, you can easily implement tried and true approaches.