how to not show objects from last screen when "switching screens?" - java

I'm newish to programming so there might be something obvious I don't know of that's a solution to this.
I'm currently writing a program that tests the user on words that they've entered before. When the user is entering words, the screen shows a jtextfield and jtextarea among other things for adding a word and it's definition and a variable is set to the constant NOT_TESTING to remember that that's the screen being displayed. My question is, when I want to switch screens to show the testing screen which has a jlabel displaying the word and a different jtextfield to write the definition of a word, what's the best way to not show the jtextfield and jtextarea from the screen where the user submits a word? (I'm not sure screen is the proper term, but I'm using it anyway.) If I don't make the components instnace variables, then I can't remove them when making a different screen, but it seems ridiculous to make them instance variables and then remove them whenever I switch screens, create new objects when going back to the old screen, and have so many instance variables.
Sorry for the long explanation, basically my question is: what's the best way to not show objects from previous screens when drawing a new screen?

Take a look at CardLayout, which allows multiple JPanels to be shown without the other one showing (basically, it makes the entire window that panel and you can switch between them).

Related

What is the functional difference between creating a Java frame inside the main class and creating a Java Frame inside a constructor? [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.

using DefaultListMethod to make custom buttons via showOptionDialog

I am just learning AWT / Swift / JavaFx recently and I feel like I have learned a lot but have barely scratched the surface. There might be a much easier way to do this BUT, I am trying to make a GUI button in eclipse that calculates the distance between two objects that the user creates. Lets call them Robots for now. So, I have one button that allows the user to create the Robots and it stores them in a DefaultListModel (listModel) and displays them in a Jlist (list) below the buttons. When the user then clicks on a robot, another button becomes actice and allows them to calculate the distance between them (one of the parameters of the robots is their location on a grid). I have all that worked out but my problem is that I am trying to make it to where they have to select two different Robots. At first I thought I could let them select two Robots and then make the computeDistance button becomes active, but I am not really sure how to do that because the only way I can select more than one object in the JList is to cntrl click and I don't want the user to have to know that trick.
My next idea was to allow the user to have one Robot selected and then give them a popup window displaying the other Robots and have them select one. Via showOptionsDialog, I have discovered how to make a custom JOptionPane, so I thought, why not make them buttons (probably will look awful, but I don't know how to make anything other than JOptionPane.showXxx at this point (like I said, only skin deep so far). Have tried consulting the javadocs, but right now that is a LOTTT to take in and have read a decent amount, I thought.
Ok, sorry if this is long, but is there a way, using my DefaultListMethod to make custom buttons? I tried a bunch of ways by creating Object[] options = {list.elements()}; etc but that doesn't work. Any help would be much appreciated!

Retrieve Values from multiple JFrame to a single JFrame

I have 5 JFrames in my application and I want the values from all 5 JFrames to be sent to a single JFrame. And it is a process where I have to go one frame to another and the value entered previously should not be lost and must be visible at the end of the process.
Easy example is,
I key in my name in the first frame,
then I key in my Address in the second frame,
then my mobile number in the third frame
and so on till the last frame where I want my keyed in details in the previous forms to be in the final frame to display my data in JTextfields. Is this possible? Because if it is a single form, I know how to do it. But when it is multiple forms in this situation I am lost. Please help.
This has nothing to do with Swing or JFrames and all to do with the general issue of getting information from one object into another. Yes it's possible -- give the classes that you wish to extract information from "getter" methods, and then call them when you want the information. If you want to gather this information in an event-dependent fashion, then you will need to have one class listening for state changes brought on by events in the other classes. A PropertyChangeListener can work well for this.
Or if you use modal JDialog windows instead of JFrames, you will always be notified when the dialog has returned and is no longer visible, since the calling code's program flow resumes from right after where it told the dialog to become visible.
Next we can discuss whether having 5 separate JFrames is a good idea or not. I'm guessing you know my opinion on this, else I wouldn't have mentioned the subject.

Saving states across JFrames

I am trying the save the state of a previous frame and then carry it over to the other frame. More like saving the data of the textfields and areas so that when i press next button some text fields,and variables will be initialized in the next forms Labels and when you press back your previous data will still remain in your form inteface.Pls help
More like data binding but across different forms
You can use any varible for that, and pass it as parameter to every JFrame you create.
But it sounds more like you want to use a CardLayout for your JFrame and use different cards that can be shown for the user. See How to use CardLayout.
If you are trying to create a wizard like UI, you should look up Sun(oracle)tutorial here.
Use something like Java's XMLEncoder.

Java - Creating an RPG dialog

So this may seem strange, but I am trying to create a very basic game that works somewhat like what an older RPG game may have as the interface (think choosing attacks from a list (ex: Pokemon)).
Right now I have a class that extends JFrame, and it contains private variables of three panels: one for displaying the sprites at the top 75% of the screen, and the other two are the ones I wish to display text on (one for announcements like, "CRITICAL HIT" and the other for the selectable choices). The second of the text boxes would only be visible sometimes, but that is irrelevant.
Can anybody start me off or lend me a hand? I am finding many way but none that seem to work for my needs.
Edit: My game is laid out and the sprite panel works exactly as it should, as much as it may sound like it, I am not rushing into anything blindly. I have the game working except for displaying the dialogs in an effective way.
EDIT 2: Ok maybe I am being unclear, my basic concern is finding the best Java component to draw strings to the bottom panels. The strings will be changing regularly, so some methods that I have tried such as the Graphics drawString() are not very effective.
Thank you,
roflha
Well, your original question statement lacks any actual cohesive question, other than "Can anybody start me off or lend me a hand?" which makes it rather hard to figure out what you really need. I discerned that what you want help from us about is displaying dialogues that popup to the user when some event happens. If you don't care too much about special effects, there are three easy ways to do this:
1) Simply have sprites for your messages, and set them to visible as needed. If you have a limited number of important messages, this makes it easy to control the visibility/flashiness of the message.
2) JTextArea allows you to simply print some text to a box. It is useful if you have a wordy console or messages that can't simply be a few images. You would just have a JTextArea in your panel, and update it as needed:
JTextArea messageBox;
messagePanel.add(messageBox);
//displays a message
messageBox.setText("CRITICAL HIT!!!");
But the user may not notice when the text changes, since it changes instantly. Whether you want to flash the text, or display some animation on top of the text area is up to you.
3) If you want a more intrusive message, you can actually have a popup dialogue where the user would have to click "OK" to continue. This is relatively easy to do, and you can even put custom icons for the message:
http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html
JOptionPane.showMessageDialog(myFrame,
"You got a critical hit!!!",
"Critical Hit",
JOptionPane.INFORMATION_MESSAGE,
criticalHitIcon);

Categories