Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: MCV (buttons not working)

  1. #1
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default MCV (buttons not working)

    I am learning out design patterns and doing a little fun project on Model Control View (MCV). I got the concept down, it is pretty simple for the most part. However my buttons are not working. Here is the code:

    public class Controller 
    {
    	private Model model;
    	private View view;
     
    	Controller(Model model, View view)
    	{
    		this.model = model;
    		this.view = view;	
    	}
     
    	class addListeners implements ActionListener
    	{
    		String name, age, address;
     
     
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			try{
    				if(e.equals(view.btnEnter))
    				{
    				name=view.getName();
    				age=view.getAge();
    				address=view.getAddress();
     
    				model.printResult(name, age, address);
    				}
    				else if(e.equals(view.btnClose))
    				{
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}
    				else
    				{
    					System.out.print("There was an error!");
    				}
    			}
    			catch(Exception ex)
    			{
    				System.out.println(ex);
    				System.out.println("There was an error!");
    			}
     
    		}
    	}
    }

    Main Method
    public class MVCmain 
    {
    	public static void main(String[] args) {
     
    	Model model = new Model();
    	View view = new View();
    	Controller controller = new Controller(model,view);
     
     
    	view.setVisible(true);
     
    	}
    }

    It runs but nothing. My other questions is how can I make a box that will print the results. What option in swing offers that. I naturally already googled this but I keep getting JOptionDialog, pretty sure that is not what i want.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    We need to see how the MVC elements are wired together. Post the Model and View.
    how can I make a box that will print the results
    What results? How many results? What should the box look like? Review Oracle's Swing tutorials to see the containers, components, and layout managers available.

  3. #3
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)

    Model
    package org.model.practice;
     
    public class Model 
    {
    	String name;
    	String age;
    	String address;
     
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getAge() {
    		return age;
    	}
    	public void setAge(String age) {
    		this.age = age;
    	}
    	public String getAddress() {
    		return address;
    	}
    	public void setAddress(String address) {
    		this.address = address;
    	}
     
    	public void printResult(String name, String age, String address)
    	{
    		System.out.println(name+" \n"+
    				           age+" \n"+
    						   address);
     
    	}
    }

    view
    package org.model.practice;
     
    import java.awt.GridLayout;
    import javax.swing.*;
     
     
    public class View extends JFrame
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
     
    	JLabel lblName, lblAddress, lblAge;
    	JTextField txtName, txtAddress, txtAge;
    	JButton btnEnter,btnClose;
    	JFrame frame;
    	Box box;
    	JOptionPane pane;
     
    	View()
    	{
    		JPanel panel = new JPanel();
    		this.setSize(250,300);
    		panel.setLayout(new GridLayout(5,4));
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		//Labels
    		lblName = new JLabel("Name: ");
    		lblAddress = new JLabel("Address: ");
    		lblAge = new JLabel("Age: ");
     
    		//Text fields
    		txtName = new JTextField();
    		txtAddress = new JTextField();
    		txtAge = new JTextField();
     
    		//Buttons
    		btnEnter = new JButton("Enter");
    		btnClose = new JButton("Close");
     
    		//creating output box
    		box = new Box(1);
     
    		panel.add(lblName);
    		panel.add(txtName);
    		panel.add(lblAddress);
    		panel.add(txtAddress);
    		panel.add(lblAge);
    		panel.add(txtAge);
    		panel.add(btnEnter);
    		panel.add(btnClose);
    		panel.add(box);
     
    		this.add(panel);
    	}
     
    	public String getName()
    	{
    		return txtName.getText();
    	}
     
    	public String getAddress()
    	{
    		return txtAddress.getText();
    	}
     
    	public String getAge()
    	{
    		return txtAge.getText();
    	}
     
    }
    controller

    package org.model.practice;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JFrame;
     
    public class Controller 
    {
    	private Model model;
    	private View view;
     
    	Controller(Model model, View view)
    	{
    		this.model = model;
    		this.view = view;	
    	}
     
    	class addListeners implements ActionListener
    	{
    		String name, age, address;
     
     
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			try{
    				if(e.equals(view.btnEnter))
    				{
    				name=view.getName();
    				age=view.getAge();
    				address=view.getAddress();
     
    				model.printResult(name, age, address);
    				}
    				else if(e.equals(view.btnClose))
    				{
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}
    				else
    				{
    					System.out.print("There was an error!");
    				}
    			}
    			catch(Exception ex)
    			{
    				System.out.println(ex);
    				System.out.println("There was an error!");
    			}
     
    		}
    	}
    }

    Main
    package org.model.practice;
     
    public class MVCmain 
    {
    	public static void main(String[] args) {
     
    	Model model = new Model();
    	View view = new View();
    	Controller controller = new Controller(model,view);
     
     
    	view.setVisible(true);
     
    	}
    }

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    It actually is displaying, probably very small in the upper left corner of your screen. To improve the output, give the panel a preferred size, something like:

    panel.setPreferredSize( new Dimension( 250, 300 ) );

    then pack() the View after adding the panel to it (I removed the 'this'):

    add( panel );
    pack();

  5. #5
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)

    I just did it and still nothing. In the main method I am getting a warning under controller on line 10, say I did not use it.
    public class MVCmain 
    {
     
    	public static void main(String[] args) {
     
    	Model model = new Model();
    	View view = new View();
    	Controller controller = new Controller(model,view);
     
     
    	view.setVisible(true);
     
    	}
    }

    I also added a textArea to my inner class in the controller. This way it will be printing to the little application and not the console. Thank you for the pack(); advice, I didn't know that.

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    You need to be more specific about what you need help with. When you say "It runs but nothing", and "still nothing," what do you mean? Do you mean that the buttons are not causing some action to happen? The Enter and Close buttons do not have action listeners assigned to them.

    Did you mean to add the Controller's addListener class to them? (Class names should begin with capital letters.) If so, the view object should be aware of the controller object that created them, either by passing a reference to the View's constructor or by setting a reference to the Controller object after the View object is created. After that is sorted, then the Controller's listener can be added to the buttons.

  7. #7
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)

    Yes, sorry I meant when I hit either button nothing happens.
    or by setting a reference to the Controller object after the View object is created.
    Is this not what I am doing?
    private Model model;
    	private View view;
     
    	Controller(Model model, View view)
    	{
    		this.model = model;
    		this.view = view;	
    	}


    class AddListeners implements ActionListener
    	{	
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			try{
    				if(e.equals(view.btnEnter))
    				{
    				model.setName(view.getName());
    				model.setAddress(view.getAge());
    				model.setAge(view.getAddress());
     
    				view.txtArea.setText(model.printResult());
     
    				}
    				else if(e.equals(view.btnClose))
    				{
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}
    				else
    				{
    					System.out.print("There was an error!");
    				}

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    You're making the Controller instance aware of the View instance, but not the other way around.

    This is what you could do:

    Modify the main class so that the model is created first and passed to the Controller. The Controller's constructor then creates an instance of the View, passing a reference to itself to the View's constructor. The View constructor then adds listeners to the buttons:

    btnEnter.addActionListener( controller.addActionListener() );

    Note that I created a new Controller method, addActionListener() that returns an instance of your existing class, AddListeners. That's what I think was meant due to the name of the class, but I could be wrong. The new method looks like:
        // method addActionListener() returns an instance of the inner class
        // AddListeners for use by the controller's views.
        public ActionListener addActionListener()
        {
            return new AddListeners();
     
        } // end method addActionListener()
    Note that these changes require modifications to the constructors and the Controller class sets the view visible rather than the main class. I can post the updated code if you get stuck or can't follow my suggestions.

  9. #9
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)

    Ahhhhhh.....
    Controller(Model model, View view)
    	{
    		this.model = model;
    		this.view = view;	
     
    		this.view.listen(new AddListeners());
    	}

    In view
    void listen(ActionListener listenForButtons)
    	{
    		btnEnter.addActionListener(listenForButtons);
    		btnClose.addActionListener(listenForButtons);
    	}

    Now I am able to print "There was an error" to the textArea. I am getting somewhere at least.

    --- Update ---

    I seen your other post (#8) after I already posted. I working on understanding it over here.

    Something like this?
    Controller(Model model, View view)
    	{
    		this.model = model;
    		this.view = view;	
     
    		view.btnEnter.addActionListener(new AddListeners());
    		view.btnClose.addActionListener(new AddListeners());
     
    		//this.view.listen(new AddListeners());
    	}


    --- Update ---

    I do not get the create the model first... I am really trying to follow you.

    --- Update ---

    Ok did some debugging with println. The Enter button is working but not in the if statement, just the else statement.
    if(e.equals(view.btnEnter))
    				{
     
    				model.setName(view.getName());
    				model.setAddress(view.getAge());
    				model.setAge(view.getAddress());
     
    				name=view.getName();
     
    				view.txtArea.setText(model.printResult());
     
    				}
    				else if(e.equals(view.btnClose))
    				{
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}
    				else
    				{
    					name=view.getName();
    					System.out.println(name);
    					view.txtArea.setText("There was an error!");
     
    				}

     if(e.equals(view.btnEnter))
    Am I doing this wrong?
    Last edited by jocdrew21; September 7th, 2014 at 08:40 AM.

  10. #10
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: MCV (buttons not working)

    Yes you are.
    The object e is an object of type ActionEvent. This is how it is defined in your methods header.
    The object btnEnter is an object of type JButton. This is how you define it in your View-class.

    Comparing these two for equality will obviously return false.

  11. The Following User Says Thank You to Cornix For This Useful Post:

    jocdrew21 (September 7th, 2014)

  12. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    Look at the ActionEvent.getSource() method, notice what it returns and then imagine what you could do with that to handle button presses.

    Edit: And this is a case where it's okay to compare objects using '=='. Remember, you're actually trying to determine if two instances are the same object, not whether their values are the same as you've learned when comparing String objects..

  13. The Following User Says Thank You to GregBrannon For This Useful Post:

    jocdrew21 (September 7th, 2014)

  14. #12
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)



    I hope you do not get annoyed but I do not understand... JButton needs ActionListener and thats what I did. I know you are right but still do not know what i did wrong.

    --- Update ---

    Just seen your post, working it now. Ignore post 12 please

    --- Update ---

    if(e.getSource() == view.btnEnter)

    Thank you... It is working, the close button is giving me a java.lang.NullPointerException now but I am sure I can work that out. Your guys are awesome.

    else if(e.getSource() == view.btnClose)
    				{
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}

    I am using a panel and never used the JFrame. This is why I program concepts I learn, reading about them is one thing but doing it is another.

    For the record, I never knew about getSource() or Pack() until today. Thank you very much!

    --- Update ---

    Got it...
    else if(e.getSource() == view.btnClose)
    				{
    					view.frame.dispose();
    					view.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				}

    SOLVED!!!!!!!!!!! Thank you guys!!!!

  15. #13
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: MCV (buttons not working)

    You should set the default close operation after creating the frame instead of setting it after actually closing the frame.

  16. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MCV (buttons not working)

    I never knew about getSource() or Pack() until today.
    When you use new classes, you should review/skim the API page to see what's there, useful notes at the top, example usages, what methods are available and what they do. It's a simple thing, takes a minute or so, but pays huge dividends.

    Glad to help, glad you figured it out.

  17. #15
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MCV (buttons not working)

    @GregBrannon, good advice thank you...

    @Cornix
    You should set the default close operation after creating the frame instead of setting it after actually closing the frame.
    Yes I fixed it, I didn't notice that at first the application was closing but continued to run, thanks again.

Similar Threads

  1. MCV assignment , editing coursess problem
    By zerocool18 in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: February 22nd, 2014, 12:01 AM
  2. Button and Radio Buttons not working!!!
    By rokere1 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 19th, 2013, 03:59 PM
  3. Cannot get buttons working in GUI program
    By Yeshibo in forum AWT / Java Swing
    Replies: 3
    Last Post: April 23rd, 2012, 12:59 PM
  4. [SOLVED] Buttons not working..
    By khms in forum What's Wrong With My Code?
    Replies: 14
    Last Post: September 2nd, 2010, 06:01 PM
  5. radio buttons stop working
    By tabutcher in forum AWT / Java Swing
    Replies: 2
    Last Post: March 5th, 2010, 09:28 AM