Communication between JFrames - java

I have two frames, Frame A and Frame B. Now, how the frame A will know when a button on Frame B is pressed?

It won't. I would consider a design pattern such as mvc: http://tomdalling.com/blog/software-design/model-view-controller-explained/
You need to have some sort of background construction to allow for the jFrames to communicate. MVC allows changes in the information for one jFrame to affect another. It's a little conceptually complex but appears to be a generally accepted form for creating user interfaces. There are a lot of resources out there to help you learn the correct form

Related

Differences between containers

I have read many different topics and information sources but I can't really understand the differences of containers in java I know JPanel, JFrame and Container are similar and should be used at different levels within the construction of a program and I know there is JWindow and acts relatively the same. I am fairly new to programming so I am just unfamiliar with the setup. Here is what I have found out/assumed about each one, please correct me if i'm wrong.
JPanel is for the integration between JFrame or a Container typically separating different sections for labels, buttons, sliders etc...
JFrame acts as a receiver of JPanels and can construct them based on instructions from the coder, JFrame can also take the same labels, buttons, sliders etc....
Container is the same as JFrame though I am assuming container is a parent of JFrame.
I'm unsure of JWindow I just found out about this one.
Both JPanel and JFrame are Containers, yet more specialized for specific purposes. And yes, you have to assemble them correctly so they act as your user interface.
But as Container does not do much on it's own you probably never put that into your UI directly. Use it as base class to construct more specialized other classes.
To move along get some simple example running, you could follow the Java Tutorials.

Is displaying a new JFrame a good pratice? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm developing an application which displays images, and plays sounds from a database. I'm trying to decide whether or not to use a separate JFrame to add images to the database from the GUI.
I'm just wondering whether it is good practice to use multiple JFrame windows?
I'm just wondering whether it is good practice to use multiple JFrames?
Bad (bad, bad) practice.
User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..
A nightmare to code and maintain:
A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.
A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.
There are any number of ways of displaying many elements in one GUI, e.g.:
CardLayout (short demo.). Good for:
Showing wizard like dialogs.
Displaying list, tree etc. selections for items that have an associated component.
Flipping between no component and visible component.
JInternalFrame/JDesktopPane typically used for an MDI.
JTabbedPane for groups of components.
JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.
JLayeredPane far many well ..layered components.
JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.
As items in a JList (simple example below).
As nodes in a JTree.
Nested layouts.
But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.
Many images
In this case where the multiple elements are images, it would be better to use either of the following instead:
A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.
A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).
The multiple JFrame approach has been something I've implemented since I began programming Swing apps. For the most part, I did it in the beginning because I didn't know any better. However, as I matured in my experience and knowledge as a developer and as began to read and absorb the opinions of so many more experienced Java devs online, I made an attempt to shift away from the multiple JFrame approach (both in current projects and future projects) only to be met with... get this... resistance from my clients! As I began implementing modal dialogs to control "child" windows and JInternalFrames for separate components, my clients began to complain! I was quite surprised, as I was doing what I thought was best-practice! But, as they say, "A happy wife is a happy life." Same goes for your clients. Of course, I am a contractor so my end-users have direct access to me, the developer, which is obviously not a common scenario.
So, I'm going to explain the benefits of the multiple JFrame approach, as well as myth-bust some of the cons that others have presented.
Ultimate flexibility in layout - By allowing separate JFrames, you give your end-user the ability to spread out and control what's on his/her screen. The concept feels "open" and non-constricting. You lose this when you go towards one big JFrame and a bunch of JInternalFrames.
Works well for very modularized applications - In my case, most of my applications have 3 - 5 big "modules" that really have nothing to do with each other whatsoever. For instance, one module might be a sales dashboard and one might be an accounting dashboard. They don't talk to each other or anything. However, the executive might want to open both and them being separate frames on the taskbar makes his life easier.
Makes it easy for end-users to reference outside material - Once, I had this situation: My app had a "data viewer," from which you could click "Add New" and it would open a data entry screen. Initially, both were JFrames. However, I wanted the data entry screen to be a JDialog whose parent was the data viewer. I made the change, and immediately I received a call from an end-user who relied heavily on the fact that he could minimize or close the viewer and keep the editor open while he referenced another part of the program (or a website, I don't remember). He's not on a multi-monitor, so he needed the entry dialog to be first and something else to be second, with the data viewer completely hidden. This was impossible with a JDialog and certainly would've been impossible with a JInternalFrame as well. I begrudgingly changed it back to being separate JFrames for his sanity, but it taught me an important lesson.
Myth: Hard to code - This is not true in my experience. I don't see why it would be any easier to create a JInternalFrame than a JFrame. In fact, in my experience, JInternalFrames offer much less flexibility. I have developed a systematic way of handling the opening & closing of JFrames in my apps that really works well. I control the frame almost completely from within the frame's code itself; the creation of the new frame, SwingWorkers that control the retrieval of data on background threads and the GUI code on EDT, restoring/bringing to front the frame if the user tries to open it twice, etc. All you need to open my JFrames is call a public static method open() and the open method, combined with a windowClosing() event handles the rest (is the frame already open? is it not open, but loading? etc.) I made this approach a template so it's not difficult to implement for each frame.
Myth/Unproven: Resource Heavy - I'd like to see some facts behind this speculative statement. Although, perhaps, you could say a JFrame needs more space than a JInternalFrame, even if you open up 100 JFrames, how many more resources would you really be consuming? If your concern is memory leaks because of resources: calling dispose() frees all resources used by the frame for garbage collection (and, again I say, a JInternalFrame should invoke exactly the same concern).
I've written a lot and I feel like I could write more. Anyways, I hope I don't get down-voted simply because it's an unpopular opinion. The question is clearly a valuable one and I hope I've provided a valuable answer, even if it isn't the common opinion.
A great example of multiple frames/single document per frame (SDI) vs single frame/multiple documents per frame (MDI) is Microsoft Excel. Some of MDI benefits:
it is possible to have a few windows in non rectangular shape - so they don't hide desktop or other window from another process (e.g. web browser)
it is possible to open a window from another process over one Excel window while writing in second Excel window - with MDI, trying to write in one of internal windows will give focus to the entire Excel window, hence hiding window from another process
it is possible to have different documents on different screens, which is especially useful when screens do not have the same resolution
SDI (Single-Document Interface, i.e., every window can only have a single document):
MDI (Multiple-Document Interface, i.e., every window can have multiple documents):
I'd like to counter the "not user friendly" argument with an example that I have just been involved with.
In our application we have a main window where the users run various 'programs' as separate tabs. As much as possible we have tried to keep our application to this single window.
One of the 'programs' they run presents a list of reports that have been generated by the system, and the user can click on an icon on each line to pop open a report viewer dialog. This viewer is showing the equivalent of the portrait/landscape A4 page(s) of the report, so the users like this window to be quite big, almost filling their screens.
A few months ago we started getting requests from our customers to make these report viewer windows modeless, so that they could have multiple reports open at the same time.
For some time I resisted this request as I did not think this was a good solution. However, my mind was changed when I found out how the users were getting around this 'deficiency' of our system.
They were opening a viewer, using the 'Save As' facility to save the report as a PDF to a specific directory, using Acrobat Reader to open the PDF file, and then they would do the same with the next report. They would have multiple Acrobat Readers running with the various report outputs that they wanted to look at.
So I relented and made the viewer modeless. This means that each viewer has a task-bar icon.
When the latest version was released to them last week, the overwhelming response from them is that they LOVE it. It's been one of our most popular recent enhancements to the system.
So you go ahead and tell your users that what they want is bad, but ultimately it won't do you any favours.
SOME NOTES:
It seems to be best practice to use JDialog's for these modeless windows
Use the constructors that use the new ModalityType rather than the boolean modal argument. This is what gives these dialogs the task-bar icon.
For modeless dialogs, pass a null parent to the constructor, but locate them relative to their 'parent' window.
Version 6 of Java on Windows has a bug which means that your main window can become 'always on top' without you telling it. Upgrade to version 7 to fix this
Make an jInternalFrame into main frame and make it invisible. Then you can use it for further events.
jInternalFrame.setSize(300,150);
jInternalFrame.setVisible(true);
It's been a while since the last time i touch swing but in general is a bad practice to do this. Some of the main disadvantages that comes to mind:
It's more expensive: you will have to allocate way more resources to draw a JFrame that other kind of window container, such as Dialog or JInternalFrame.
Not user friendly: It is not easy to navigate into a bunch of JFrame stuck together, it will look like your application is a set of applications inconsistent and poorly design.
It's easy to use JInternalFrame This is kind of retorical, now it's way easier and other people smarter ( or with more spare time) than us have already think through the Desktop and JInternalFrame pattern, so I would recommend to use it.
Bad practice definitely. One reason is that it is not very 'user-friendly' for the fact that every JFrame shows a new taskbar icon. Controlling multiple JFrames will have you ripping your hair out.
Personally, I would use ONE JFrame for your kind of application. Methods of displaying multiple things is up to you, there are many. Canvases, JInternalFrame, CardLayout, even JPanels possibly.
Multiple JFrame objects = Pain, trouble, and problems.
I think using multiple Jframes is not a good idea.
Instead we can use JPanels more than one or more JPanel in the same JFrame.
Also we can switch between this JPanels. So it gives us freedom to display more than on thing in the JFrame.
For each JPanel we can design different things and all this JPanel can be displayed on the single JFrameone at a time.
To switch between this JPanels use JMenuBar with JMenuItems for each JPanelor 'JButtonfor eachJPanel`.
More than one JFrame is not a good practice, but there is nothing wrong if we want more than one JFrame.
But its better to change one JFrame for our different needs rather than having multiple JFrames.
If the frames are going to be the same size, why not create the frame and pass the frame then as a reference to it instead.
When you have passed the frame you can then decide how to populate it. It would be like having a method for calculating the average of a set of figures. Would you create the method over and over again?
It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.

JAVA Swing MVC - Main Controller?

I'm having some troubles designing the architecture of an application I'm trying to develop. I'm working on JAVA, and I started working on this application because I want to deepen my overall knowledge of JAVA, architectures and patterns. I want to follow the guidelines to make a reusable, low coupled application, like it should be. The application has only one JFrame, but inside it there are several JPanels, each one representing a module of the application.
The question is: in JAVA Swing, how to implement an appropriate MVC pattern?
I struggle on how to understand the way it should be done.
Should I have a main Controller class, that holds references to all the other Controllers?
(I have an image to demonstrate this, here: https://docs.google.com/file/d/0B7tBdn5slIFeY2FoSmxESTREQ1k/edit?usp=sharing)
And in this case, should all the events that require changing the module that is being presented redirect to the main Controller?
Or should I just couple the JFrame with the Controllers of the application, and communicate directly with them?
Basically, I would like to know if i need to have a class that 'manages' all the others.
I have already read several explanations, and different opinions, but I believe this is a little more specific.
Hope I have made myself clear (and hope as well that my explanation is better than my drawing :)).
EDIT:
a sample of the application usage:
One (an only one) JFrame throughout all the lifecycle of the application;
the menu will be on the left side, as in BorderLayout.WEST;
the current module of the application will be in the center, as in BorderLayout.CENTER;
when the user presses one button of the menu, the corresponding module is loaded into the BorderLayout.CENTER;
Should the menu (View) have it's own Controller, and this Controller communicate with the JFrame? And the JFrame load the new module into it's Layout? Or should the JFrame have its own Controller (or Model, as Gilbert Le Blanc said)?
I know this may seem to specific, or easy to understand, but everytime I think of an desktop application, I struggle to understand this.
When you have an application with a GUI, the GUI model becomes the application view. The application interacts with the GUI through the GUI model.
Or should I just couple the JFrame with the Controllers of the application, and communicate directly with them?
This is what I've done. I've packaged the controller classes together, but I've never created one main controller class.
I keep the GUI controller classes in a separate package from any other application controller classes, like the data access objects.
I usually put each JPanel in its own class, but I wouldn't call that a requirement. The JFrame has its own class, although the instance of the JFrame and the instance of the GUI model are passed to almost all of the GUI components. This makes menu actions possible.
This Traffic Signal GUI article goes over the basics of how to code a very simple GUI.
Edited to respond to the changes in the question.
The GUI controller is separate from the GUI model. The GUI model contains all of the data elements that make up your GUI. Strings for JTextFields, DefaultTableModels for JTables.
Based on your application design, I'd recommend that you create a Java class for every JPanel that you want to put in the center of your application. Your JFrame will control which JPanel is displayed, based on the menu. I'd also suggest that you look at the JTabbedPane which uses a different user interface to accomplish the task of choosing which panel to work with.
Assuming you're going with the menu on the left, each menu option (toggling JButton?) will have it's own controller method or class. These controllers have to have an instance of the JFrame so the controller can call the method in the JFrame class that puts the appropriate panel in the center of the display. The controller decides which method to call, but the methods themselves are a part of the JFrame class.
I've been talking about JFrame and JPanel classes. It's important that you use composition rather than inheritance to build these classes. The JFrame class contains a JFrame. It does not extend JFrame. The only time you extend a Swing component is when you want to override a component method.
As discussed here, Swing components use a separable model architecture with the model and view loosely coupled using the observer pattern. Not every GUI control has to be part of your application's controller. Using an ActionListener, such as Action, is particularly convenient for encapsulating application functionality.
Addendum: I'd use CardLayout, illustrated here to switch panels. Note how the Action handlers can be used with buttons, menus, combos, toolbars, etc. Each card's content can have it's own implementation of the MVC pattern, separate from the others. Use a PropertyChangeEvent, seen here, for communication between components.
In general, Swing components, e.g. buttons and tables, already listen to their respective models, leaving you to focus on your application's data model and its listening views. Conveniently, a Swing model, e.g. ComboBoxModel or TableModel`, can have more than one listener.

basic MVC pattern and GUI

I wanted to ask for a tip. How would you struct your application if you had a JFrame with many JPanels which have like ten JTextFields Labels, and an Edit Button.
Would you put all the code in the JFrame or would you extend from JPanel and include all of them in the JFrame?
What about the buttons? I want to use the MVC pattern, how would you handle the actionlisteners? Are each of them an own controller or would you use only one controller for all of them?
I think it's first of all a question of style and personal preference. It also depends on what your application should do and how.
If your JPanels all are very similar in a certain way it would probably make sense to extend from JPanel. For example if every panel had 10 Buttons where Button 1 does always action xyz() for its corresponding model-object (especially when this object is the same for all buttons of 1 JPanel) and Button 2 does abc() ...
If the JPanels are not strongly correlated in such a way I would place my code rather in the JFrame or in a third Object which sets the whole GUI up from outside.
It's similar with the actionlisteners. If you have very few actions I would probably go for just one controller-object for ease of use (not many files). If you have a lot of different actions I would group similar actions into one controller-object per group of actions.
That said it probably is best to start with a simple approach (YAGNI) where you do everything from the JFrame / third object and have one actionlistener and then refactor when you feel that splitting things up gives you a cleaner or more flexible design.

Designing mvc controller layer

I am trying to understand and practice the MVC-pattern to improve my development. So I started refactoring an application I once wrote and have progressed so far. It is completely clear how my model looks like and also the view is ready so far. But now I am searching for a good practice to design my controller layer.
I have created a view that's split up in different main components. Let me give you a short example:
There are 3 Panels that group specific components:
"FilePanel", holding a JTextField and two JButtons
"DataPanel", holding all components neccessary to display some data and some JButtons
"CalendarPanel", showing some calendar-sheets
These three Panels are each in a separate class and afterwards instantiated and arranged in a GUI-class.
No the actual question. As I separate the Panels, how should I build the controllers? Should each panel get its own controller class (FileController, DataController, CalendarController)? Or should there just be one controller class for the whole view?
If I create one controller class for each panel, how do can I achieve that the controllers communicate with each other? Example: If a button is clicked in "FilePanel", how do I notify "DataPanel" about this?
Could you give me some examples of best practice?
Are the Panels fundamentally separate?
NO: The set of panels is fundamentally one state. For example the panels represent a console showing different aspects of the same items under control. The user selects an item and all the other panels update to show views of the item. In this case one Controller is enough.
YES: That is can each of them move through various states independendently? This is the kind of realtionship you might have in a "Portal" style application. The user can work in each Panel pretty independently - extreme example, two separate side-by-side browser panes in one overall viewer. It's the kind of effect you get in Composite Applications where the user has windows open on different back-end systems. Sometimes user actions in one window cause things to happen in another window, but generally they run separately. In this case we have can have separate controllers each responsible for the state of a Panel. They can communicate with each other by event handling mechanisms. User clicks in File Panel, View contacts its controlled, which issues a "File Selected" event, whose payload is the id of the file. Note that the "click" event is translated into a non-ui specific event.
By having separate controllers we decouple the details of the current set of panels. Addind a new panel requires only that the new controller registers for events.

Categories

Resources