548

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?

Peddler
  • 6,045
  • 4
  • 18
  • 22
  • 12
    Only if you are targetting a multi-monitor set-up! – DNA Sep 22 '12 at 19:46
  • 18
    I would also argue that this is [tag:language-agnostic] and has to do with the [tag:user-interface] more than Java specifically. – wchargin Jun 09 '13 at 17:03
  • 7
    I would agree with that @WChargin This question has become more valuable than I ever thought it could! – Peddler Jun 10 '13 at 15:22
  • 2
    I notice that beginners (such as myself) usually make use of multiple JFrames. Probably because its easier to call it from inside the main JFrame than making use of say a CardLayout. Although in some instances its not advisable to use it. – jantristanmilan Nov 19 '13 at 17:45
  • Debugging would be like eating cactus.. this is not advisable. – Taslim Oseni Apr 01 '18 at 10:29
  • 1
    Although this post is tagged as "Opinion Based" i find it very useful because both parts: those who are against and those who are in favour of it.. ring their opinions and examples based on what they have experienced. This is usedu to others.. I was looking to develop a java application with multiple Jframes.. I was wondering if it was bad practie.. maybe.. but in the facts I see that people do it and others do not.. so i am fine with it – Andy McRae Feb 27 '21 at 13:49
  • Why do huge amounts of questions get closed as a duplicate of this? Especially ones that have **nothing to do with** deciding how many JFrames to use, but are asking about technical how-to details of using each JFrame? There's no way I can see the answers here being useful for the typical near-0-score questions that are redirected here. – Karl Knechtel Feb 10 '23 at 18:21

9 Answers9

468

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:
    1. Showing wizard like dialogs.
    2. Displaying list, tree etc. selections for items that have an associated component.
    3. 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:

  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.
  2. 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).

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • @AndrewThompson Strange one, Im using a CardLayout, on the second panel there is another different CardLayout used (No images being displayed here) If I jump between the Panels, they begin to kind of mesh into one another. So I suppose Im wondering whether it's bad practice to have CL inside another CL... – Peddler Mar 04 '12 at 12:28
  • @AndrewThompson Why is using multiple `JFrame`s bad practice? What makes it user unfriendly and a coding nightmare? – Jeffrey Apr 20 '12 at 01:05
  • @Jeffrey You are welcome. Happy to expand on one of my favorite [Don't do it](http://meta.stackexchange.com/questions/8891/is-dont-do-it-a-valid-answer) topics. :) – Andrew Thompson Apr 20 '12 at 01:36
  • 1
    How about using `JInternalFrame` ? It's not difficult to implement and seems quite intuitive to me (many applications have a main window and several smaller frames inside it, take GIMP or Photoshop) – toniedzwiedz Jun 17 '12 at 09:50
  • @Andrew: Worth citing this [Q&A](http://stackoverflow.com/q/6309407/230513) in a third bullet under _nightmare_? – trashgod Oct 02 '12 at 18:05
  • 1
    It is not necessarily bad practice, check out thinkorswim. They use multiple frames for charts. Just depends. Although for the case at hand it is. – BAR Apr 16 '13 at 16:05
  • 6
    @user417896 *"Just depends."* No it doesn't. I've used Gimp. It's horrible and should be an MDI. – Andrew Thompson Apr 16 '13 at 16:15
  • 1
    @AndrewThompson I agree GIMP should be `MDI`. But, look at Excel. Should that be `MDI`? I like it `SDI` a lot better. Take a look at my answer to this question and let me know what you think of what I said. `SDI` has been my main thrust since I began developing in Swing and I've found a lot of success with it. – ryvantage Aug 01 '13 at 05:16
  • 5
    @ryvantage *"Should (Excel) be MDI?"* Good question. I feel it should be offered to the user both ways (certainly not ***only*** in MDI form). For example: 1) I currently use TextPad, and by configuration at my choice, it opens separate instances, that each offer multiple documents shown in a list. 2) Although I'll typically use FF in tabbed mode, occasionally I drag a tab off to a new window. -- The common factor in the examples is user choice. Deliver the app. 'however the user wants it'. – Andrew Thompson Aug 01 '13 at 09:49
  • 16
    @AndrewThompson You've just countered your own argument with your last comment. In your main answer you say this is bad practice and should never be done, but in your comment above you say you sometimes like SDI and we should offer our users the choice. Surely, this is exactly what user417896 was saying above. It depends. This is one of my biggest pet hates about my fellow developers. The fact that many of them become religiously fanatical about so-called 'best-practices'. We wouldn't have the innovative UIs we have today if we all stuck to 'best-practices' and didn't think outside the square. – DuncanKinnear Aug 15 '13 at 21:47
  • 3
    @DuncanKinnear The people who have a 1 percent chance of making a radical shift in usage of UI elements or design philosophy work, have enough experience that they already know the pitfalls. They are usually OS makers (for it to work best). This message is to 'the rest of you'. *"We wouldn't have the innovative UIs we have today.."* We also would not have the 1001 'unusable GUIs' that are out there. Personally I'd prefer to see innovation invested in the core program, than the 'decorations' that wrap it. – Andrew Thompson Aug 15 '13 at 21:57
  • 2
    In Windows 7, at least, the multiple icons for frames from the same application will be grouped together, which is fabulous! – Enwired Aug 28 '13 at 22:06
  • 1
    "Deliver the app. 'however the user wants it'" you said, and I agree. Don't use multiple frames unless there is a good reason, such as support for multiple monitors, or user needs. I have an app that displays things by default in multiple tabs in a tabbed pane, but users are allowed to open any tab in a separate window if they choose to do so, and the users seem to like that. – Enwired Aug 28 '13 at 23:22
  • 1
    @Enwired And on that matter of 'user choice', we can certainly agree. :) I'm thinking of developing a small 'file upload app.' that will offer the recent/current uploads in an MDI from which they can be dragged onto a separate instance of the app. I might even implement anonymous reporting to tell which deployment forms are most popular.. – Andrew Thompson Aug 29 '13 at 03:03
  • 1
    I've realized that the original question could be interpreted two ways: 1) Is it ok to use multiple instances of JFrame class? 2) Is it ok to use multiple windows of any class such as JFrame, JWindow and JDialog. I typically make my secondary windows be instances of JDialog, which is what you also recommended. But I'm not really sure why that is a better choice, if it is truly better, and if there might be some exceptions. (I've never had a use for JWindow.) – Enwired Aug 29 '13 at 17:03
  • 7
    Huge generalisation! It's not ALWAYS bad to let the user control their windows individually, and access them individually from the task bar. Good practice is to be aware of all the options, and pick one intelligently. There are certainly cases where multiple JFrames makes a good deal of sense. – Dawood ibn Kareem Dec 25 '13 at 21:18
  • @DavidWallace As has been expressed on another answer on this thread. I felt it was unnecessary to 'clutter' my answer with those points. (And my basic view is that when an OP is at the level where they can make an app. that does not make a complete mess of it, they will hardly be needing to ask questions at the level of those people to whom I offer the comment.) So basically (shrug) sure whatever - but that won't stop me from making the comment, and it sure won't change the text of my answer. – Andrew Thompson Dec 25 '13 at 21:25
  • @DavidWallace Let me ask you one questions: Why are Visual Studio, Eclipse, IntellijIDEA, MS Word, MySQL Workbench... all focused on acomplishment of all tasks in a single window? Did you ever see that some of them requires another window to acomplish some task? I.e. Imagine if you are in MySQL Workbench and you are using single window to acomplish database management tasks. And then, imagine if MySQL Workbench opens a new window if you select to generate EER diagram or if you create a new database. 10 databases, 10 windows! Both unnecessary and user unfriendly. – Branislav Lazic Dec 28 '13 at 17:46
  • 4
    The Excel example in another answer here shows it clearly. Interestingly, on my desktop at work, I have prefer to have Eclipse open in three separate windows. I find it more convenient that way. YMMV. – Dawood ibn Kareem Dec 28 '13 at 21:13
  • Please explain your main two arguments. Why is it _user unfriendly_? I would counter that most of the work I do happens in applications that do use multiple windows, e.g. my IDE, my web browser, my file browser, my text editor, my terminal emulator, etc. The developers behind those applications must have had reasons to not restrict themselves to a single top-level window. Please counter those reasons. – Feuermurmel Jan 11 '21 at 06:57
  • Why is it _a nightmare to code_? None of the applications I mentioned use modal dialogs (no dialog blocks the whole application) or the other behavior you mentioned. Why are those behaviors ever necessary in your opinion? – Feuermurmel Jan 11 '21 at 06:57
216

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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):

enter image description here

MDI (Multiple-Document Interface, i.e., every window can have multiple documents):

enter image description here

ryvantage
  • 13,064
  • 15
  • 63
  • 112
  • 17
    Well thought out. If you have multiple modules that have nothing to do with each other, why not create separate applications? Also, there's no restriction saying you have to use *modal* dialogs, you could use modeless dialogs to serve as a second "frame". – Jeffrey Jul 31 '13 at 03:43
  • 1
    Very good answer and detailed answer though I have to agree with @kleopatra on this one.. I once had an application with over a hundred screens where users wanted to compare output data off multiple screens/same screen with different inputs. We built a custom windowing system to allow us to do that. Users were just more comfortable with having 2 JFrames to keep next to one another ;) – javatarz Oct 09 '13 at 05:41
  • 1
    While I understand your argument, I would still prefer to have everything in one `JFrame` and a big parent `JTabbedPane`; but with the possibility to open a second window (or even more) where the layout can be different, offering hence a hybrid behaviour where SDI lovers are happy and MDI ones as well. In all cases, I always considered `JInternalFrame` as a horrible pattern which gives you all the inconvenients of both worlds. The flexibility they offer just sucks and they eat away a lot of precious screen space for no real purposes. – Guillaume Polet Sep 30 '14 at 21:03
  • I agree SDI is sometimes appropriate (and users often prefer it). There is one more drawback, and I did not find any workaround for that so far, unfortunatelly: each `JFrame` gets its own taskbar icon. Sometimes this is exactly what you want, but sometimes it is not. In WinAPI this is easy to configure, but in Swing it seems it cannot be done. – Suma Mar 27 '18 at 09:08
  • @suma in that case I think I would opt for a `JDialog` over a `JFrame`. – ryvantage Mar 27 '18 at 19:58
  • 1
    My app is a Dataflow Geometry programming app, with 2 JFrame windows: a programming GUI (module drag 'n click editor where you design program) a 2D computer graphics (where you see your program run) It works very smoothly on the MacOS. The only thing I need help with is, how do you make the sibling window come forward (to z== 1 rank) when you click on either of the app windows (giving it z == 0 rank)? My attempts all lead to infinite recursion. – pbierre Sep 28 '20 at 15:56
55

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
DuncanKinnear
  • 4,563
  • 2
  • 34
  • 65
  • 7
    This is exactly my experience as well. If there's one thing I'm certain of, it's that you are doing something wrong when people try and circumvent your user-friendlyness to do whatever it is they really want to do. Functionality is king. – ryvantage Sep 27 '13 at 02:30
  • One way to get around this, is to allow to have multiple JFrame's opened, all offering the same functionality, but by default everything is done within a single window. This actually allows the user to choose between SDI or MDI. – Guillaume Polet Oct 01 '14 at 19:17
  • Sorry? Can you explain your solution a bit better, please? How can it be a single window AND multiple windows? We have one main window where the main application runs, but sometimes we need to open dialogs, and sometimes those dialogs (based on user requirements) need to be modeless. Making rules that the interface should be this way or that is just going to dig a big hole for yourself. – DuncanKinnear Oct 02 '14 at 01:24
  • 1
    @GuillaumePolet I agree with Duncan, can you explain what you mean a bit more? I share his confusion – Ungeheuer Dec 17 '15 at 02:43
  • I think what he means is that the user could start multiple copies of the application (the 'JFrame') but inside each of those it is SDI. However, our client application is a very thick client, so this would be a resource hungry approach. – DuncanKinnear Dec 17 '15 at 02:48
  • @JohnnyCoder For example, in Eclipse IDE, by default, all the editors open within tabs of the same frame, but you have the possibility to start a new window that is linked to the same workspace to display other editors. – Guillaume Polet Dec 17 '15 at 09:01
20

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);
Hauleth
  • 22,873
  • 4
  • 61
  • 112
19

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.

Necronet
  • 6,704
  • 9
  • 49
  • 89
  • 8
    Don't you have same effect for user when using multiple `JInternalFrame`'s too? Personally, I dissagree with use of `JInternalFrame`'s! `CardLayout` is a real bless! – Branislav Lazic Jun 15 '13 at 15:14
  • 6
    I agree with @brano88. `JInternalFrame` offers no advantages in any of the three cases you mentioned (1. where's the evidence that `JInternalFrame` is lighter than `JFrame`? 2. Your `JInternalFrame`s could be just as cluttered/messy/stuck together as a bunch of `JFrame`s. 3. How is `JInternalFrame` easier? It's the same exact code, except one is contained within a `JDesktopPane` and one is contained within the natural screen area. They sound equally complex to me.) – ryvantage Jul 31 '13 at 03:36
  • 1
    1. JFrame is a hevyweight component compare to JInternalFrame which is a lightweight. 2. Have you ever seen an app which contains tons of windows at the same time to be functional? IDE, Browsers, even in finance application it is a goal to keep it in the same scope. 3. I have found JIF to be very easy to use in the past and have no complaint of course pick the component that best suits an scenario – Necronet Jul 31 '13 at 06:03
  • 5
    1. I'd like to see proof of this. Both are objects, both are `JComponent`s, both have almost identical structures, except one is rendered on a `JDesktop` and one is not. Again, sorry, but I believe you are speculating regarding the "weight" of `JFrame`. 2. My applications use SDI and my clients are very happy. However, you said "a ton of windows," which, of course that would suck. But, my point is this: *"a ton of" `JInternalFrame`s would suck just as bad!* If you're saying JIFs allow you to be a sloppy UI designer, then that's terrible. A cluttered mess is a cluttered mess, whether JF or JIF. – ryvantage Jul 31 '13 at 12:12
  • 2
    "of course pick the component that best suits an scenario" – Necronet Jul 31 '13 at 17:37
  • 1
    @Necronet "Have you ever seen an app which contains tons of windows at the same time to be functional?" - Actually GIMP is like that and there are some very happy GIMP users out there. – DuncanKinnear Dec 17 '15 at 03:00
9

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.

Sai Kishore
  • 326
  • 1
  • 7
  • 16
Matt Dawsey
  • 123
  • 1
  • 3
  • 11
    hmm ... nothing new compared to the accepted answer, afaics? – kleopatra Jan 10 '13 at 11:09
  • 6
    "Every JFrame shows a new task bar icon" - this only applies on Windows! On Mac OS X every application has just one dock icon, regardless of how many windows it has open, and it is common for applications to have multiple top level windows. – Rolf May 27 '14 at 08:49
8

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.

Sai Kishore
  • 326
  • 1
  • 7
  • 16
Lijo
  • 6,498
  • 5
  • 49
  • 60
5

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?

Keith Spriggs
  • 235
  • 1
  • 4
  • 10
  • 1
    That's basically doing what the Cardlayout and JTabbedPane can do, but doing it in reverse and making your code overly complex while you have clean and easy solution to achieve the same thing. – Guillaume Polet Oct 01 '14 at 19:04
5

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.

arunjoseph
  • 85
  • 1
  • 1