actionPerformed inside the actionPerformed method in Java - java

I am working on a java swing project and I have a frame with multiple buttons and when someone clicks any of that button,user is asked for an input(say the user enters n) and a new frame is created with n text fields with another button "Ok"
{new frame is created inside the actionPerformed method.So my question is how to handle the action events for this Ok button.I tried using an anonymous class but I can't do much with variables inside it.
Source File:http://www.mediafire.com/file/9ed2h0yeyis5tk6/OSProject.txt

Use a modal JDialog or JOptionPane. See How to Make Dialogs
Define the functionality for the second window within it's own class, so you can isolate the functionality and management in more easily manageable manner. Provide setters and getters to allow information to passed between it and the class which needs to use it. If you're using a JOptionPane, this step makes it easier to define a custom component which can be displayed by it

Related

Unable to get values from another jFrame

I want to fill values of multiple jTextBox from a jFrame into another, using accessor methods like
String getNameVal()
{
return jTextBox1.getText();
}
How to call these methods from another jFrame?
Suggestions:
It sounds like your GUI code is geared towards making JFrames, and if so, you will want to avoid this. You are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this.
More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
This question has direct bearing on your problem. I will guess that your main problem isn't how to give classes getter methods, and how to have other classes call the getter methods. More often then not, when faced with the issue of extracting information from one GUI view to another, the issue is one of when to extract the information. If you displayed your second window as a non-modal JFrame, and then had the calling class immediately extract the data from that second JFrame, you'd get nonsense data, because you'd be extracting data before the user would have time to interact with the 2nd window and enter data.
One possible solution to this when using non-modal windows to get information from the user is to use a WindowListener so you can be notified when the user has completed his dealing with the second window, and so now data can be safely extracted.
Often better is for the 2nd window not be non-modal, as JFrames are, but instead to be a modal window such as a modal JDialog. When the calling code displays a modal dialog, all code flow in the calling code stops until the dialog is no longer visible. In this situation, no WindowListener is needed since you will know exactly when the dialog has been dealt with -- on the code line immediately after you set it visible -- and so can extract your data from it with ease.
A nice variant on this has already been mentioned in by Andrew Thompson in comments -- use a JOptionPane. Don't poo-poo this option since JOptionPanes are powerful tools, likely much more powerful than you realize as they can hold fully formed complex JPanel views, and behave just as described above, as modal dialogs.
If you need more specific help, then please don't hesitate to comment to this answer. Also if so, then consider creating and posting a Minimal, Complete, and Verifiable Example Program where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.
Edit
For my mcve code examples of the above suggestions, please my answers to the following StackOverflow Questions:
Using a modal JDialog to extract information
Using a JOptonPane to extract information
I assume the textfields are present in frame1 and you want to access them in frame2. The following can be a way to achieve this:
First create getters for all JTextFields that you have in your frame1. Alternatively you can have them in a panel and call getComponents() method.
Create a private variable of JFrame type in your frame2.
Modify the constructor of frame2 to receive the frame1 object and assign it to the private variable of JFrame type.
Now you can create a close() method in frame2 which disposes the frame2 and sets frame1 to visible.
But in my opinion you should create a class which handles the data in these textfields. Initialize the class object in any button click of frame1 and check for any inconsistency in the input. I can guess there is something wrong with your design.

Adding a GUI to existing Java console based program

I've been working on a console based program that acts as an inventory of Plant objects.
I have a parent class "Plant" that has child classes of "Flower", "Weed", etc... These objects are added, removed, displayed, searched through another class containing the main method and methods for the actions above.
The methods/actions are chosen by the user via console input processed with a switch statement.
My question is this: We are adding a GUI to this console based program using a JFrame, JPanels, etc... Would the proper way to go about this be to create a new class for the interface and a new main method in that class to run the program? I would of course change the former main method to a method called by the new main.
Moving from a console program requires a lot more than just changing main methods. GUI programs are event driven. So you're not going to be running endless loops like you would in a console program.
What I mean by event driven is, for example, a button get pressed, an event is fired. You as the programmer are responsible for coding what happens when that event is fired.
So some advice.
You should go through the tutorials and learn some of the basic components and how they work. Some of the basic ones are JLabel, JTextField, JButton
You will definitely need to focus on how to write event listeners. Some of the basic ones you may want to focus on are ActionListener for button presses MouseListener for mouse events.
Should learn to layout out components correctly. Some of the basic layouts you may want to focus on are GridLayout, BorderLayout, and FlowLayout
You want to learn about the basic containers like JFrame and JPanel and learn their capabilities
The Swing tutorials are always a good place to start. Once you pick up on the basics, then move on to some more complex material.

How to set ActionListener to listen to another ActionListener to fire an event in a different class?

I'm trying to figure out how I can have a class listen to another. So this is the idea.
I have a MainFrame class, which is simply a container class, JFrame container, that takes an argument of type JPanel. Basically I want this container class to be able to switch between frames depending on what my other class, FrameSwitcher, will tell it to do.
The other classes are: FrameSwitcher, MainMenu and ScoreBoards.
The idea is that, let's say MainMenu, will contain 4 buttons, each one will listen, BUT will NOT change the frames. Rather it will somehow - and this is the part I need help with - send to the FrameSwitcher what button was clicked, and this information will then be sent to MainFrame to switch to the appropriate frames.
You may be looking for the observer pattern, discussed here. In particular, a PropertyChangeListener, illustrated here, may be a useful approach to loose coupling.
Also consider letting each view export an Action that selects itself from a CardLayout, as suggested in How to Use Actions and How to Use CardLayout.
FrameSwitcher should keep ActionListeners added to the menu. On click it changes it's state and call MainFrame's method switchTo(argumentWhereToSwitch);

How to use setVisible in JFrames?

In my program I have two JFrame instances. When I click next button I want to show next frame and hide current frame. So I use this.setVisible(false) and new Next().setVisible(true). But in Next window if I click back button I want to set previous frame to be visible again and next frame must be ended (which means it must be exited).
Is there any special method(s) to do this? How can I do it?
Consider using CardLayout instead of hunting for how many JFrames there are. Then..
only one JFrame would be needed
any of Next/Back Actions will be only switching between cards
There are lots of examples in this forum - e.g. as shown here.
That is an odd & quirky GUI. I suggest instead to run a JFrame for the main GUI, and when the user wants to search, pop a JOptionPane (or modal JDialog) to accept the details to search for. This will not have the effect described above, but will follow the 'path of least surprise' for the end user.
If you want to destroy a JFrame releasing all associated resources you shold call dispose() method on it.
You may place your JFrames on a list data structure and keep a reference to current position according to the window you are displaying. In that way it will be easy to move to next and previous. But note that each frame added to the list will use memory and will have its state as you placed it in to the list.
If you are trying to create a wizard like UI, you should look up Sun(oracle)tutorial here.
create the instance of your main window in next() window.. and use same method which you chosed befoe to hide your main window, for example if your main window is named as gui then what we have to do is.
gui obj = new gui();
and if you click on back button now than do these also
this.setVisibility(false);
obj.setVisibility(true);
that's all you need.
good luck.

Where is the best place to register listeners to JButtons created from arrays?

I'm creating some JButtons from a String array for a menu. Those buttons are created in a class that extends JButton. On creation, the buttons call a method to create some children buttons (if the parent button has a submenu to display).
I'd like to be able to register listeners to every single button. Each button is going to either change the JPanel currently displayed or open up its submenu. I thought I'd register the listener in the constructor, but I read some articles I found on Google that it was bad practice to do so.
What I'd like to know is where the best place to do this would be, because I have no idea what's good practice and what's not when registering listeners.
I think I know what's confusing you. This article: Java theory and practice: Be a good (event) listener states that it is bad practice to register a listener from its constructor, but what they mean is the listener's constructor, not the button' constructor. It should be fine to register a listener from within the JButton's constructor. Your listener will likely be an anonymous inner class or an inner private class (or if complex, a stand alone class), so this is not really an issue.
edit
Except you can have problems if you do this and then subclass your buttons.

Categories

Resources