Results 1 to 14 of 14
- 01-29-2012, 03:57 PM #1
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
returning a string when button clicked
I would like to have a string returned (which was the user's input into a text field). the only problem is, that I am calling the method from another class:
I have initialized my variable so that when it is updated, other methods can see the updated variable.Java Code:String response = gui.btnClick();
here are my methods that attempt to retrieve what the user put in:Java Code:private static String btnResponseText;
when i update btnResponseText with "hi there!", why does my method, btnClick return null yet? I guess I am not sure how to return a value with acitonPerformed, since it has to be void.Java Code:public void actionPerformed(ActionEvent e) { btnResponseText = "hi there!"; Toolkit.getDefaultToolkit().beep(); // Get the text btnResponseText = getuIText(); } public String getuIText() { String userResponse = uI.getText(); btnResponseText = "hi there!"; return userResponse; } public String btnClick() { //where initialization occurs: jbtnSubmit.addActionListener(this); /*public void actionPerformed(ActionEvent e) { return ""; }*/ return btnResponseText; }
-
Re: returning a string when button clicked
It's hard if not impossible to guess what's going on with your other code. Because of this we have requested many times both here and at stackoverflow.com, that you please create and post an SSCCE
Also there is no good reason to use static variables here. If you are doing this to solve some problem, to make a variable global don't as it's the wrong way to solve this.
Also, why are you adding ActionListeners multiple times? This code is quite confusing.
- 02-01-2012, 04:12 AM #3
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Re: returning a string when button clicked
alright. here are my sscce's. was having trouble getting them to compile though.
[Java] public class Code1 { public static void main(String[] args) { Code2 gui = n - Pastebin.com
[Java] import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLab - Pastebin.com
-
Re: returning a string when button clicked
Best if you post SSCCE's here in the forum. The basic premise is that if you're asking for some free advice, you should put in the effort to make it as easy as possible for a volunteer to help you.
- 02-01-2012, 04:29 AM #5
Re: returning a string when button clicked
You've been a member long enough to know that you should post the SSCCE on the forum. Most members (self included) won't click links. For some who are willing to click, the free file sharing host may be blocked by a corporate firewall.
If it's too long to post here, it's not a SSCCE.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 02-01-2012, 04:31 AM #6
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Re: returning a string when button clicked
Java Code:public class Code1 { public static void main(String[] args) { Code2 gui = new Code2(); // Start up the user interface Code2.startGUI(); gui.writeToTextArea('s', "What would you like to do? [L]ist tasks or [C]reate a new one or [E]dit a task or [D]elete a task?"); // wait for a button click to get user response String response = gui.btnClick(); System.out.print(response); } }Java Code:import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JWindow; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Code2 implements ActionListener { JLabel jLabInstruction, jLaberror, copyright; JLabel curStatus = new JLabel(""); JFrame frame = new JFrame(); JTextField uI; Object fileExists; boolean file; JTextArea textArea; JButton jbtnSubmit; Object results; String[] diagResults; boolean check; JScrollPane areaScrollPane; String btnResponseText; // Set up the GUI end for the user public void startGUI() { // These are all essential GUI pieces copyright = new JLabel(""); uI = new JTextField(""); uI = new JTextField(25); new JTextArea(""); final JFrame jfrm = new JFrame( "program"); jfrm.setLayout(new FlowLayout()); jfrm.setSize(300, 300); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textArea = new JTextArea(5, 20); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setCaretPosition(textArea.getDocument().getLength()); jLabInstruction = new JLabel("SYSTEM: Please type in a command: "); jbtnSubmit = new JButton("Submit"); jLaberror = new JLabel(""); textArea.setMargin(new Insets(10, 10, 10, 10)); areaScrollPane = new JScrollPane(textArea); areaScrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 150)); jfrm.add(jLaberror); jfrm.add(curStatus); jfrm.add(areaScrollPane); jfrm.add(jLabInstruction); jfrm.add(uI); jfrm.add(jbtnSubmit); jfrm.add(copyright); jfrm.setVisible(true); } public String getuIText() { String userResponse = uI.getText(); return userResponse; } public void actionPerformed(ActionEvent e) { btnResponseText = "hi there!"; Toolkit.getDefaultToolkit().beep(); // Get the text btnResponseText = getuIText(); } // Writes to the text area public void writeToTextArea(char annotation, String userInputText) { if (annotation == 's') { textArea.append("\nSYSTEM: " + userInputText); } else if (annotation == 'n') { textArea.append(userInputText.toUpperCase()); } else { { textArea.append("\nUSER: " + userInputText.toUpperCase()); } } } public String btnClick() { //where initialization occurs: jbtnSubmit.addActionListener(this); return btnResponseText; } }Last edited by droidus; 02-01-2012 at 04:38 AM.
-
Re: returning a string when button clicked
Won't compile as some method is missing:
Java Code:btnResponseText = getuIText();
- 02-01-2012, 04:38 AM #8
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Re: returning a string when button clicked
try now.
-
Re: returning a string when button clicked
OK, got it. Please hang on while I look this over...
- 02-01-2012, 04:56 AM #10
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Re: returning a string when button clicked
ok, thanks!
-
Re: returning a string when button clicked
OK, some problems as I see them:
- You are trying to allow your gui to communicate with outside classes, and that's a good thing, but to do this, care must be taken to respect Swing threading and to respect the event-driven programming paradigm.
- You are making your GUI class implement a listener interface -- a bad move, as it makes the one class do too much, and makes it harder to work in different parts of your program in isolation, here mainly the view and the control. So first recommendation -- get rid of the "implements ActionListener" from the Code2 class or any GUI class.
- Next, and likely the most confusing aspect of your program is your btnClick() method, and how you try to use it in the outside program. What you are doing with this method is adding the internal ActionListener to the button when the other class's main method is called. So understand exactly when this method is called -- once and only at program start up, that's it. So what happens is you add an ActionListener to the button and immediately request the response String before the user has ever had a chance to push a button or write in any JTextField or do anything. Later when the user presses the button, the ActionListener's actionPerformed method is called, the response String is set, but your outside class is blissfully unaware of what's going on. So in essense you're ignoring the concept of event driven programming. To solve this your outside class must listen for button click. Hang on, and let me see if I can show one way to do this.
-
Re: returning a string when button clicked
Consider creating a "Control" class whose task is to respond to button presses or <enter> presses in the JTextField. The control class's methods will be called from anonymous inner listeners held by the view (or GUI) class:
I'd give the view an anonymous inner ActionListener class that calls the control's method above:Java Code:class Code2BControl { private Code2BView view; public void btnSubmitActionPerformed(ActionEvent e) { String uiText = view.getuIText(); view.writeToTextArea('a', uiText); } public void initialize() { if (view != null) { view.writeToTextArea( 's', "What would you like to do? [L]ist tasks or [C]reate a new one or [E]dit a task or [D]elete a task?"); } } public void setView(Code2BView view) { this.view = view; } }
So the control will only respond to this when an event occurs -- when the button is pressed.Java Code:// !! let's give the button and text field an anonymous inner action listener ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (control != null) { // have it call the control's method control.btnSubmitActionPerformed(e); uI.selectAll(); // select all of uI's text so we can easily overwrite it } } }; jbtnSubmit.addActionListener(actionListener); uI.addActionListener(actionListener);
The whole thing would look like so:
Java Code:import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class Code2B { public static void main(String[] args) { Code2BView view = new Code2BView(); Code2BControl control = new Code2BControl(); view.setControl(control); control.setView(view); view.startGUI(); control.initialize(); } } // !! no longer implements ActionListener class Code2BView { private Code2BControl control; // !! JLabel jLabInstruction, jLaberror, copyright; JLabel curStatus = new JLabel(""); JFrame frame = new JFrame(); JTextField uI; Object fileExists; boolean file; JTextArea textArea; JButton jbtnSubmit; Object results; String[] diagResults; boolean check; JScrollPane areaScrollPane; String btnResponseText; public void startGUI() { copyright = new JLabel(""); uI = new JTextField(25); uI.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { uI.selectAll(); // !! so all text highlights when focused gained } }); new JTextArea(""); final JFrame jfrm = new JFrame("program"); jfrm.setLayout(new FlowLayout()); jfrm.setSize(300, 300); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textArea = new JTextArea(5, 20); textArea.setEditable(false); textArea.setFocusable(false); // !! so focus goes to text field textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setCaretPosition(textArea.getDocument().getLength()); jLabInstruction = new JLabel("SYSTEM: Please type in a command: "); jbtnSubmit = new JButton("Submit"); // !! let's give the button and text field an anonymous inner action listener ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (control != null) { // have it call the control's method control.btnSubmitActionPerformed(e); uI.selectAll(); // select all of uI's text so we can easily overwrite it } } }; jbtnSubmit.addActionListener(actionListener); uI.addActionListener(actionListener); // !! jLaberror = new JLabel(""); textArea.setMargin(new Insets(10, 10, 10, 10)); areaScrollPane = new JScrollPane(textArea); areaScrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 150)); jfrm.add(jLaberror); jfrm.add(curStatus); jfrm.add(areaScrollPane); jfrm.add(jLabInstruction); jfrm.add(uI); jfrm.add(jbtnSubmit); jfrm.add(copyright); jfrm.setVisible(true); } public String getuIText() { String userResponse = uI.getText(); return userResponse; } // Writes to the text area public void writeToTextArea(char annotation, String userInputText) { if (annotation == 's') { textArea.append("SYSTEM: " + userInputText + "\n"); } else if (annotation == 'n') { textArea.append(userInputText.toUpperCase() + "\n"); } else { textArea.append("USER: " + userInputText.toUpperCase() + "\n"); } } // !! setter method to allow us to add Control public void setControl(Code2BControl control) { this.control = control; } } class Code2BControl { private Code2BView view; public void btnSubmitActionPerformed(ActionEvent e) { String uiText = view.getuIText(); view.writeToTextArea('a', uiText); } public void initialize() { if (view != null) { view.writeToTextArea( 's', "What would you like to do? [L]ist tasks or [C]reate a new one or [E]dit a task or [D]elete a task?"); } } public void setView(Code2BView view) { this.view = view; } }
- 02-01-2012, 05:26 AM #13
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Re: returning a string when button clicked
alright; thanks! will take a look at this, and see if this fixes it.
- 02-02-2012, 03:50 AM #14
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
Similar Threads
-
form appear after ok button clicked
By sks in forum NetBeansReplies: 1Last Post: 06-01-2011, 08:50 AM -
show panel when button clicked
By Aggror in forum New To JavaReplies: 6Last Post: 10-14-2010, 04:05 PM -
Minimize (not exit) the application to tray when the close button is clicked
By Nandish Reddy in forum EclipseReplies: 0Last Post: 04-28-2010, 01:39 PM -
[SOLVED] Open a different class from the same package when button clicked.
By mainy in forum AWT / SwingReplies: 4Last Post: 02-16-2009, 03:20 PM -
[SOLVED] How to destroy a process when a button is clicked?
By pranav13 in forum AWT / SwingReplies: 11Last Post: 02-13-2009, 12:52 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks