Results 1 to 14 of 14
  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default 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:

    Java Code:
    String response = gui.btnClick();
    I have initialized my variable so that when it is updated, other methods can see the updated variable.

    Java Code:
    private static String btnResponseText;
    here are my methods that attempt to retrieve what the user put in:

    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;
    	}
    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.

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

    Default 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.

  3. #3
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

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

    Default 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.

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

    Default 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.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default 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.

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

    Default Re: returning a string when button clicked

    Won't compile as some method is missing:
    Java Code:
    btnResponseText = getuIText();

  8. #8
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: returning a string when button clicked

    try now.

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

    Default Re: returning a string when button clicked

    OK, got it. Please hang on while I look this over...

  10. #10
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: returning a string when button clicked

    ok, thanks!

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

    Default 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.

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

    Default 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:

    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;
       }
    
    }
    I'd give the view an anonymous inner ActionListener class that calls the control's method above:

    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);
    So the control will only respond to this when an event occurs -- when the button is pressed.

    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;
       }
    
    }

  13. #13
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: returning a string when button clicked

    alright; thanks! will take a look at this, and see if this fixes it.

  14. #14
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: returning a string when button clicked

    ok, so if the user were to enter "l" for list all tasks, where would i pick up that character?

Similar Threads

  1. form appear after ok button clicked
    By sks in forum NetBeans
    Replies: 1
    Last Post: 06-01-2011, 08:50 AM
  2. show panel when button clicked
    By Aggror in forum New To Java
    Replies: 6
    Last Post: 10-14-2010, 04:05 PM
  3. Replies: 0
    Last Post: 04-28-2010, 01:39 PM
  4. Replies: 4
    Last Post: 02-16-2009, 03:20 PM
  5. Replies: 11
    Last Post: 02-13-2009, 12:52 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
  •