I have written many FORTRAN codes, but am new to Java, which I find much more powerful and more difficult.
I have a program that was written several years ago in MS Access.
The program consists of a main window with buttons that take you to other windows where you input data and make queries.
Things have changed and the program needs to be rewritten. I want to rewrite it in Java.
I have written many small programs in Java, but they just do engineering calculations and only involve one window or screen.
To write Java programs, I have been using netbeans 5.5 and can easily design guis and add functionality.
However, I cannot figure out how to code multiple windows that interact with each other. For example, I would like to do the following:
1. Add a button1 to JFrame1, which will be the main screen-size window (I think they call it the Parent)
2. Add a button2 to JFrame2, which will be a secondary screen-size window (I think they call it a Child).
3. Add functionality so that when button1 is clicked, JFrame2 is displayed instead of JFrame1.
4. When button2 is clicked, JFrame1 is displayed again. Can you suggest how I can do this? I don't see it covered in the three Java books I have been using.
Can supply a simple Java code that does this or direct me to a reference that explains how to do write the code.
Thank you.

Recommended Answers

All 19 Replies

As long as the two frames have references to one another, you can easily interact between the two. Another idea may be to use a non-visual controller that can act as a mediator between the two frames and synchronize interactions and state changes as needed.

Here is a small example with a view controller. The two view classes defined have essentially the same code here (which you would never want to code into a real app), but since they just represent your other two frames I made them separate for clarity of the example.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JFrame;

public class FrameExample {
        
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                Controller viewController = new Controller();
                MainView main = new MainView(viewController);
                DetailView detail = new DetailView(viewController);
                viewController.showView("Main");
            }
        });
    }
    
    static class Controller {
        HashMap<String,JFrame> views;
        
        public Controller(){
            views = new HashMap<String,JFrame>();
        }
        
        public void registerView(String name, JFrame view){
            views.put(name,view);
        }
        
        public void showView(String name){
            if (views.containsKey(name)){
                for (String key : views.keySet()){
                    views.get(key).setVisible(key.equals(name));
                }
            }
        }
    }
    
    static class MainView extends JFrame {
        final Controller viewController;
        
        public MainView(Controller controller){
            super();
            this.viewController = controller;
            
            setTitle("Main");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            getContentPane().setLayout(new BorderLayout());
            JButton button = new JButton("Show Detail");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    viewController.showView("Detail");
                }
            });
            getContentPane().add(button, BorderLayout.SOUTH);
            pack();
            setSize(200,200);
            viewController.registerView(getTitle(), this);
        }
    }
    
    static class DetailView extends JFrame {
        final Controller viewController;
        
        public DetailView(Controller controller){
            super();
            this.viewController = controller;
            
            setTitle("Detail");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            getContentPane().setLayout(new BorderLayout());
            JButton button = new JButton("Show Main");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    viewController.showView("Main");
                }
            });
            getContentPane().add(button, BorderLayout.SOUTH);
            pack();
            setSize(200,200);
            
            viewController.registerView(getTitle(), this);
        }
    }    
}

This in itself is still probably not a solution to your needs, but without any more information on the relationship between your two views, it's at least a starting point perhaps.

commented: Nice example, what more can I say :) +6

Thank you very much for the FrameExample.java code. It works very well and has provided an excellent start for what I need to do. I like the use of the Controller. Can you tell me why the hash map was needed or refer me to a reference that explains it? I do know what a hash map is, but I don't understand why it is needed here. Apparently the program needs Lines 5 and 22-27 to compile.

The HashMap just provides a mechanism to look up a frame reference by name (the string key assigned when it was registered). The showView() method just loops through all of the views in the map and sets all but the requested one to not be visible.

This was just a quick-and-dirty example of using a controller to mediate some of your component interactions. There may be a much more suitable arrangement for your interface and usage needs, but you would need to post some more specific information the app and it's organization.

The HashMap just provides a mechanism to look up a frame reference by name (the string key assigned when it was registered). The showView() method just loops through all of the views in the map and sets all but the requested one to not be visible.

This was just a quick-and-dirty example of using a controller to mediate some of your component interactions. There may be a much more suitable arrangement for your interface and usage needs, but you would need to post some more specific information the app and it's organization.

The java program I am planning will display a number of windows, maybe 12, by clicking on a button in one window to move to another window. I believe I should have a separate Java file for each window because of the different actions required in each window. I tried to split the java file with a view controller, which was posted earlier, into two files, one for the main view and the other for the detail view, but was unsuccessful. When I ported them in a folder as a project to netBeans 6, I was unable to get a successful build because of errors associated with the Controller. Apparently, I did not properly provide the correct Controller statements in each of the two files. Can you divide the single java file into two files so that the Controller errors will be eliminated and result in a successful build and run? From what I have read, the use of a Controller is growing in popularity.
jdseader

Yes definitely. I only included all of those as static inner classes for compactness of the example. Each of those would normally be an independent class on it's own. You will noticed that I used them as such in the main() method.

Yes definitely. I only included all of those as static inner classes for compactness of the example. Each of those would normally be an independent class on it's own. You will noticed that I used them as such in the main() method.

Yes, I did notice the static inner classes. However, when I separated the file into two files, I was unable to eliminate the Controller errors.
I would appreciate any help, advice, or code you could send.

What are the Controller errors you are getting? I have no trouble putting them in separate files here. Are you placing the classes in the same package? If they are not in the same package you will need to add import statements for those classes. Beyond that I can't see where you would get errors with those classes.

What are the Controller errors you are getting? I have no trouble putting them in separate files here. Are you placing the classes in the same package? If they are not in the same package you will need to add import statements for those classes. Beyond that I can't see where you would get errors with those classes.

I did not put the two files in a package. Therefore, I did add import statements to the second file. The two source files were together in a project. The problem seems to be related to Controller Statements that may be needed in the second file, which goes from line 66 to 89 in the code that was sent. The second file begins with the 7 import statements. Lines 1 to 64 and Line 90 became the first, main, file. In line 66, I changed the word "static" to "public". The error messages all said that the class Controller could not be found in the second file.
Thank you for your interest and help.

If the classes are in the same package (directory) then you should not need the import statements. In Netbeans, you can also right click in the code editor and "Fix Imports".

I did not put the two files in a package. Therefore, I did add import statements to the second file. The two source files were together in a project. The problem seems to be related to Controller Statements that may be needed in the second file, which goes from line 66 to 89 in the code that was sent. The second file begins with the 7 import statements. Lines 1 to 64 and Line 90 became the first, main, file. In line 66, I changed the word "static" to "public". The error messages all said that the class Controller could not be found in the second file.
Thank you for your interest and help.

I am still getting errors with the Controller class when I try to build the project in NetBeans 6.0.
The Project consists of two Source files made from the single source file posted above.
The first file consists of lines 1 to 65 plus line 90. However, the following line has been added before line 1:
package multiplewindows.frames;
The second file consists of lines 66 to 89. However, before line 66, I added the line:
package multiplewindows.frames;
and after that line, I added the import lines 1 to 8.
When I try to build the project, I get the following error messages for the second file:

cannot find symbol
symbol : class Controller
location: class multiplewindows.frames.DetailView
final Controller viewController;

and the error message:

cannot find symbol
symbol : class Controller
location: class multiplewindows.frames.DetailView
public DetailView(Controller controller){

It appears that I am not using the Controller properly with the two files. Can this be corrected?

Ok, that is because you left the Controller nested in FrameExample. Really each of those static classes should be moved up to their own top-level public classes. You don't want the Controller nor the main view to remain nested in FrameExample.

You can leave main() as it is in FrameExample, but make each static class it's own file in that same package and it'll be fine.

Ok, that is because you left the Controller nested in FrameExample. Really each of those static classes should be moved up to their own top-level public classes. You don't want the Controller nor the main view to remain nested in FrameExample.

You can leave main() as it is in FrameExample, but make each static class it's own file in that same package and it'll be fine.

Thank you very much for your prompt and very useful reply. I un-nested the Controller and MainView Classes in FrameExample. I also removed the word, "static" in lines 22 and 42 of the posted code. In the new DetailView java file, in the orginal line 66, I changed the word, "static" to "public". Now the code builds and runs successfully.
Clearly, I have a great deal to learn about Java programming.

Clearly, I have a great deal to learn about Java programming.

A working programmer doesn't ever stop learning :)

Two books that might help you get from Fortran to Java easier are Head First Java and Head First Design Patterns.
Object-oriented programming is quite a different beast than procedural Fortran.

and oh, get into the habbit of always using packages for everything.
It may not be required by the language spec (an omission which by many is considered a major historical flaw in the language) but it's good practice and many application frameworks and libraries expect all classes to be in a package.
Many editors in fact will enforce it.

commented: A good tip :) +1

and oh, get into the habbit of always using packages for everything.
It may not be required by the language spec (an omission which by many is considered a major historical flaw in the language) but it's good practice and many application frameworks and libraries expect all classes to be in a package.
Many editors in fact will enforce it.

Thank you for this suggestion. I am beginning to see the wisdom in that.

I too am an old Fortran and VBA (excel) programmer having problems similar to the above while I have attempted to migrate a VBA program to JAVA, and found this most helpful. Are there any new books out that are considered improvements to those mentioned above that someone could recommend. This program requires user input in at about four different stages in its execution, one of which appears in a for loop.

twmgeo: this thread is four years old, and there's no use reviving it; if you want a list of books to look at, just take a look at the sticky thread on top of the java forum.

as far as I understand you, you will only be using very basic java, and the code for that hasn't really been changed over the last few years.

Thanks. My main issue is go get several gui's to work sequentially as input/output during the course of a program's execution. So far my reading of Java in 24 hours and Java, the complete reference have not helped (not blaming them necessarily as I am still in the steep part of the java learning cureve). Do you know of a ref in particular that would be more helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.