java - Is there a better way to connect two JPanels? -
netbeans project , source code of minimal example
is there better way connect jframe
jpanel
class other making fields of jpanel
public?
i writing program there going option button, when button pressed custom joptionpane.showoptiondialog
brought jpanel
inside hold specific options user wants.
when user presses joptionpane.ok_option
button program closes optiondialog
jpanel
inside , returns jframe
. need whatever inputted in jpanel used in jframe
class. did making text fields of jpanel
public feel cheap way of doing since netbeans
not let me unless opened source in notepad.
also totally ok if joptionpane.ok_option
saving fields of jpanel
in file , separately retrieve them in jframe
class.
so there better way this?
jframe
action listener:
private void gosettingsactionperformed(java.awt.event.actionevent evt) { settings settings = new settings(); int result = joptionpane.showoptiondialog(null, settings, "settings", joptionpane.ok_cancel_option, joptionpane.information_message, null, new string[]{"save", "cancel"}, "default"); if (result == joptionpane.ok_option) { username = settings.jtextfield1.gettext(); usernameinputedlabel.settext(username); } }
your question specific example of general question: how 2 objects communicate?
- your consideration of using public field know wrong.
- you mention saving data file, isn't over-kill, , won't add needless time , resource overhead when simpler solution available?
- better use same technique you'd use if not swing gui: public methods including getter , setter methods if need be.
e.g.,
private void gosettingsactionperformed(java.awt.event.actionevent evt) { settings settings = new settings(); int result = joptionpane.showoptiondialog(null, settings, "settings", joptionpane.ok_cancel_option, joptionpane.information_message, null, new string[]{"save", "cancel"}, "default"); if (result == joptionpane.ok_option) { // **** give settings class method: username = settings.getusername(); usernameinputedlabel.settext(username); } }
edit
state in comment:
i have used getters , setters books i've read , forums frequent know general consensus having getters , setters worse public fields.
sorry, that's hogwash. please consider code vs. code. in code above, suggest givng settings method, like:
// in declarations: // don't name jtextfield1 private jtextfield usernamefield = new jtextfield(); // public getter method public string getusername() { return jtextfield1.gettext(); // should named usernamefield }
whereas suggestion make jtextfield public, exposing comers. riskier? allow calling code change state of settings object without knowing it?
Comments
Post a Comment