Solved

MVC controller data flow in multple windows

Posted on 2011-02-26
6
1,022 Views
Last Modified: 2013-12-14
Hi Experts

I have a question relating to MVC and multiple windows and displaying results on different windows (Panels), I am quite a new Java developer and am completely stuck...

This is the scenario:

I have Main JFrame window container, and I have created multiple JPanel windows that make up the multi window application. I also have a Controller class that changes the currently displayed Panel in the Frame. I also have java classes that carry out various logic such as get data and process this data to be displayed on the different frames.

The panels are all instantiated and registered with the controller, the controller has methods to display (using a layoutManager.replace(...) method.

I am able to display different Panels from button clicks, by sending a call to the Controller class, what I want to be able to do is use the Controller to call the logic classes behind the scenes, for example to get and display a list of users onto a JTable in the userSelectPanel panel. Can you please advise how I can call the logic classes and display the data onto the Panel screens after they have been displayed.

So in summary I want to be able to do is...

1. Load the first panel (mainPanel), contained in the Main()
2. Press a button on mainPanel which loads userSelect
3. Call the Controller, this loads userSelectPanel and also makes a call to a class (sampleUserData) that extracts the user data and displays this in a table in userSelectPanel

Below are cut-down code samples of mainPanel, userSelectPanel and controller classes, with a sample data class.

Any help on this would be hugely appreciated, I am looking for a code smaple of a strategy from which I can use this within the rest of the application.


//Main Class (JFrame container containing mainPanel JPanel

      public class Main extends javax.swing.JFrame {
            static {
               try {          
                     javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
               } catch(Exception exception) {
                     System.out.println("Error loading L&F: " + exception);
               }        
            }
            Controller controller;
            JPanel userSelectPanel;
            
            /** Creates new form Main */
            public Main() {                      
                  initComponents();
                  //JPanel secondPanel = new SecondPanel();
                  controller = new Controller(this);
                  userSelectPanel = new UserSelectPanel(controller);
                  
                  controller.setMainPanel(mainPanel);
                  controller.setSecondPanel(userSelectPanel);
            }
      //GUI generation code omitted for clarity

            private void btnMainExitActionPerformed(java.awt.event.ActionEvent evt) {
            }

            private void btnMainEnterActionPerformed(java.awt.event.ActionEvent evt) {
                  controller.showUserSelectPanel();
            }

            /**
            * @param args the command line arguments
            */
            public static void main(String args[]) {
                  java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                              new Main().setVisible(true);
                        }
                  });
            }

            // Variables declaration - do not modify
            public javax.swing.JButton btnMainEnter;
            public javax.swing.JButton btnMainExit;
            private javax.swing.JLabel jLabel1;
            private javax.swing.JLabel jLabel2;
            private javax.swing.JPanel mainPanel;
            // End of variables declaration
      }


//userSelectPanel (JPanel)

      public class UserSelectPanel extends javax.swing.JPanel {

            Controller controller;
            
            /** Creates new form UserSectPanel */
            public UserSelectPanel(Controller c) {
                  initComponents();
                  controller = c;
            }
            
            private void btnUserSelectActionPerformed(java.awt.event.ActionEvent evt) {
                  controller.showMainPanel();
            }
      }

//Controller class

      public class Controller {//implements ActionListener {
            JPanel mainPanel, userSelectPanel;
            Main main;

            GroupLayout layout;

            public Controller(Main m) {
                  main = m;
                  layout = (org.jdesktop.layout.GroupLayout)main.getContentPane().getLayout();
            }

            public void setMainPanel(JPanel m) {
                  mainPanel = m;
            }

            public void setSecondPanel(JPanel us) {
                  userSelectPanel = us;
            }

            public void showMainPanel() {
                  layout.replace(userSelectPanel, mainPanel);
                  main.pack();
            }

         public void showUserSelectPanel() {
                  layout.replace(mainPanel, userSelectPanel);
                  main.pack();
            }
      }


//Sample data
      public class SampleUserData {

            public String[][] userDetails() {
                  String[][] userDetails = new String[4][2];
                  int userID = 0;

                  for (int row = 0; row <4; row++) {
                        for (int col = 0; col < 2; col++) {
                              userID = row + 1;
                              userDetails[row][0] = Integer.toString(userID);
                              userDetails[row][1] = "TestName" + userID;
                        }
                  }
            return userDetails;
            }
      }
      

Thanks in advance to anyone that can help
0
Comment
Question by:BinaryFlusher
  • 3
  • 2
6 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 34989661
Sorry, I'm probably missing something, but I see there are not many responses, so maybe other people
also have some questions.

What I wanted to ask, is what it is specifically that you are asking about.
It looks like you are doing all reasonably, so why can't you just go ahead and do what you want?

So, as I understand, you are able to display your interface, and what prevents you to call
those logic classes behind the scene from Controller and populate JTable in UserSelectPanel which you need to populate?

Is it that you don't know how to do some specific operation, e.g. how to populate JTable?
Or you tried to do it, and it throws exception in some place?

If you want to know how to do some specific operation, then, maybe you could ask specifically what is the
operation you want some help with. If you wrote some code, part of which doesn't work, why would not you
post your code and you'll hopefully get some help with debugging it?

I think if you formulate your question in a more specific way, it might  be easier to understand and you may get more help.











0
 

Author Comment

by:BinaryFlusher
ID: 34989935
Hi for_yan

Sorry for not being explicit. What I want to know is how I can access, for example a specific component, such as the JTable, in the new displayed panel after it has been displayed, from within the controller. At the moment I can swap the panels but I cannot see the JTable in the new userSelectPanel from within the controller. What I want to be able to do is display the new panel and trigger the data load from the array class into the table.

Do I need to use a listener of some description? Currently from within the controller I cannot see any of the specific components such as the text field or table in the panel being displayed, so I am not sure how to add the data from the model, in this case the array data.

Do I add this functionality to load the data from the SampleDataClass within the new panel itself, if so how can I initiate ths after the panel has been loaded, what event can i use to trigger this so that it happens as soon as the panel, and the table within it, is populated?

Hope this is clearer.

Thanks
0
 

Author Comment

by:BinaryFlusher
ID: 34989946
Further comment:

What I would like to do is have the controller be responsible for displaying the specific panels, after button clicks on screen, and for the controller to also mediate between the panels and the classes that do the data processing and manipulation...

thanks again
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 47

Accepted Solution

by:
for_yan earned 250 total points
ID: 34990407

If you want necessarily strictly follow MVC recommendations
you can study this code for Calculator:

http://www.leepoint.net/notes-java/GUI/structure/40mvc.html
It is relatively simple, but in my mind still too complicated.

 I usually do in the way which is more simple for me to understand and keep in mind
even if it does not have clean separation between MVC.

So in your case with JTable I could have done it something like below:

 Here I don't refer directly to visual elemnts in controller,
if you want you can do that also, just set up them as instance variables in controller
provide for setter methods for them
and pass these variables from Main after those elements are
created.  You can then setData in the JTable directly in controller,
the data should of course still show up in your GUI, once this JTable
was passed before from Main.


------------------------------------------------------------------
I think in controller you can say:

public class Controller {

SampleUserData sud;


MyTableModel tableData;
...

public void mainMethod(String key){

sud = new SampleUserData();
sud.retrieveUserData(key);
tableData = sud.getData();


}

public MyTableModel getData(){
return tableData;
}
...

}

----------------------------------------------------------------------------------
in your SampleUserData :

public SampleUserData {
MyTableModel data;

public void retrievedUserData(String key){

Vector v;
//here you retrieve user data say from database, or as you showed it
create it in array or vector  and then store this data it into object MyTableModel
which would normally extend AbtsractTableModel )

data .setVector(v);

}
 
public MyTableModel getData() {
return data;
}

}

-------------------------------------------------------------------------------------------
In your Main
you make your
JTable myTable;
as instance variable
perhaps in constructor or somehwre in the setup
part when you create SelectUserPanel and JTable inside that panel
you construct your JTable


myTable = new JTable(...)


then your Main can implement listeners attached to buttons or textfields
and you can also have action methods
and say in one of them you can
determine which button is clicked, or say read something
from textfields which user populated - in fact retrieve some
 - user input, say , some key in String Key,
and then inside that action method you say:

controller.mainMethod(key);
MyTableData data = controller.getData();
myTable.setModel(data);

as a result your JTable should be populated

------------------------------------------------------------------------------------------




 

0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 34991838
You could also create a class that extends JPanel, encapsulating the elements of that panel, including your table.  At that point you can either expose the table through a getTable() method or provide a method of setting the table model for the table, such as setData(MyDataType) or setTableModel(TableModel) if you want the Controller to build the TableModel.  If your controller has an instance of this class, instead of a normal JPanel, it will be able to perform the tasks you need it to do.
0
 

Author Closing Comment

by:BinaryFlusher
ID: 34999060
NA
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now