Passing variables within several JFrames and classes - java

sorry guys, but I got confused after many hours sitting ang writting the code.
Situation:
I have two JFrames. These are different Java classes - one of them is the FirstGUI, from which we can call the other JFrame called SecondGUI. OK - that's clear.
I also have one class called Processor in which i have specific methods like "connectToPort" or "disconnectFromPort".
Also, in the FirstGUI (which has the main method) I'm creating SecondGUI object (and set setVisible to false) and Processor object with FirstGUI and SecondGUI as parameters.
Problem:
From the FirstGUI in I want to call out SecondGUI (by setVisible to true) - OK, done. But what about calling out the created at the beginning Processor object from the SecondGUI JFrame? It's important to call the SAME object, because Processor methods can for example set text in the FirstGUI JFrame.JTextPane component, and add items to JComboBox of the SecondGUI.
I don't know how to solve this, I'm always getting NullPointerException.
EDIT:
I want to add that I can't pass the Processor object as an argument while creating SecondGUI, because Second GUI is created earlier and it is an argument while creating Processor... That's the problem.

When constructing the second GUI (child), the initiating class (FirstGUI) can pass self in constructor, and also retain the reference to the constructed object. Now both GUIs have the reference to each other:
class F1 extends JFrame {
F2 child;
void createF2() {
child = new F2(this);
child.setVisible(true);
}
}
class F2 extends JFrame {
final F1 parent;
F2(F1 parent) { this.parent = parent; };
}

If you've searched out your problem or for similar problems on this site, you'll know that the most common recommendation is not to use multiple JFrames, that it is suggestive of a bad design. Better to either swap views with a CardLayout or use JDialogs of the appropriate modality.
As for your question, having one class pass information dynamically to another class, there are two main options depending on program structure.
If one class is in a modal JDialog, then the first class can pull information from the second modal class by calling appropriate getter methods after the second window is no longer visible.
If one class is displayed non-modally, then you'll want to use some type of listener such as a PropertyChangeListener to have the listening class be notified by the observed class when state changes occur.
Edit
Regarding:
From the FirstGUI in I want to call out SecondGUI (by setVisible to true) - OK, done. But what about calling out the created at the beginning Processor object from the SecondGUI JFrame? It's important to call the SAME object, because Processor methods can for example set text in the FirstGUI JFrame.JTextPane component, and add items to JComboBox of the SecondGUI.
Audrius gives you an answer for that. 1+ up-vote given to his answer.
I don't know how to solve this, I'm always getting NullPointerException.
If you get a NPE, should carefully inspect the line that throws the NPE to see which variable is null and then trace back in your code to see why. If your still stuck on a NPE and need our help, then you'll want to show pertinent code and give us more detail on the problem including noting which variable is null and why you think that it shouldn't be null.
EDIT: I want to add that I can't pass the Processor object as an argument while creating SecondGUI, because Second GUI is created earlier and it is an argument while creating Processor... That's the problem.
This is a non-issue. Since the dependent window is displayed dynamically, you can always pass a reference just prior to displaying it using a setter method.

Related

2D Game not repainting

I checked the other questions and couldn't find one with the same case as me so here's my question.
I am making a 2 player stick fighting game that you can play on the same computer using different keys. Everything's fine but when I try to move the oval on the screen with the keys, it's not moving.
Here's the code for my first class - http://pastebin.com/wA0JXdzr
second class - http://pastebin.com/ArByyirt
I think I need to call repaint in my second class in the gameloop, but it's saying that it can't make a static reference to it.
You are trying to call a non static method directly from another class which is not legal in java. The paint() method in your first class is the non-static method. You were able to use the variables stickx2 and such because they are static as defined in your first class.
Thus, I suggest you create an object of stickFrame() in the gameLoop class and copy all your code in your stickframe main method and put it in your gameLoop main method. It is highly not recommended that you have two main methods.
Declare a Stick Frame variable below your Serialization ID.
StickFrame s;
Then instantiate it in your gameLoop constructor
s = new StickFrame();
Now we need to fix the repaint from another class problem.
To do this we need a method in the gameLoop Class.
public void repaintStickFrame()
{
s.repaint();
}
Then call it by
s.repaintStickFrame() in your loop.
or you can just call
s.repaint();//place in loop
Heres a link to a question that is similar to yours and has solutions as well
Calling repaint from another class JFrame
Heres a link that explains how you can call an objects method once you've created one (Like we did above, which allowed us to call the repaint() method from a different class):
https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html

Access Java JFrame from another class

I have a class that creates a JFrame. When the JFrame is created it has a start button. When the start button is clicked, it runs two threads until the stop button is clicked. The two threads are in another class file. From the class that contains the threads, how can I access the JFrame instance in order to change value that are displayed?
In order to acheive this you have to pass the reference of JFrame using this keyword.
To have access to a private instance within another class, I think you should use agetter.
Example:
//JFrame declaration
private JFrame frame;
//Getter
public JFrame getFrame() {
return frame;
}
As noted by one answer, you can pass in a reference of the GUI or view into any class that needs it, for instance by passing the GUI class into the other class's constructor parameter, and using the parameter to set a field, but having said that, there are caveats:
Always be sure to make Swing state changes on the Swing event thread (the EDT). Since you're using background threading, this means that you will either
use a SwingWorker as your background thread, and notify the GUI of changes via the publish/process method pair, or
your SwingWorker can notify observers of change via PropertyChangeListeners and "bound" properties, or
if using a standard Thread/Runnable, you will need to be sure to queue Swing calls onto the EDT using SwingUtilities.invokeLater(someRunnable)
Even better is to use a Model-View-Control type structure, but even if you do this, the model should be changed on the EDT for the same reasons above.
As a side recommendation in general I try to avoid making classes that extend JFrame as that unnecessarily restricts my code to creating just JFrames.
Note that this help is very general, but if you need more specific help, then you will want to post more specific information regarding your problem and your pertinent code.

Instead of getting two similar JFrames, I get one whith double component

I created a JFrame with buttons, labels and texts and I want to show it two times when I execute the main program, so I did like that:
import java.net.SocketException;
public class Main {
public static void main(String[] args) throws SocketException {
new MyFrame("client1");
new MyFrame("client2");
}
}
The result: I get two frames: one with the component of the other one inside, and one empty.
How to resolve this issue?
You are using static instance fields with your MyFrame for your components
A component can only reside within a single container, the moment you create your second frame, the static components are removed from the first container before been added to the second.
The solution, don't do this, ever...
I assume you are using static because you want to access these fields from another class, in that case, you should appropriate getters in the MyFrame class and pass a reference of it to those classes that need it.
Alternatively, you could establish a series of observers who monitor for changes and take appropriate action, this helps to decouple the code.
Personally, if you need to modify the MyFrame instances in some way, I'd provide setter methods that update your components instead, as I don't like exposing UI elements without good reason, to much opportunity for others to mess with them in appropriately

Swing - Organization of JFrames (or JDialogs???) in my program

I have a main controller class that shows a JFrame containing a JTable and, for each row in this table, I have to show a specific "form" on doubleclick.
This secondary window will need information about the specific row selected on the main JTable, as well as some objects saved as fields in the controller class.
An conceptual example of what I need to do is the following:
I have a set of Shops (listed in the JTable in the main JFrame) and, on double click on a row, another window has to appear, allowing for a management of the Shop (sending orders, checking deliveries, etc...).
My question, me being such a newbie with Swing, is: what is the best organization for a common pattern like this one?
Should I model another JFrame and pass as arguments all the data that I could happen to need (I really don't like this), or should I pass only a reference to the Controller class (this would be against the MVC pattern, I think).
Or maybe I should use a JDialog instead of another JFrame? The thing is that, really, the functionality that I need from this second window are a little too big for a dialog, I think...
I am confused, any tip/suggestion/advice will be much appreciated!
Thank you
Regards
Or maybe I should use a JDialog instead of another JFrame?
Bingo.
I actually don't like the idea of having a listener inside my Model class (aka Shop) – implementing the ActionListener. I think I would extend the JDialog class (let’s call it MyJDialog) then when a row is double clicked … create a new instance of MyJDialog class and pass in the Shop object in the constructor. Within the MyJDialog class you can modify the Shop object by calling mutators (setters). Moreover, the Shop class should have a way of notifying observers when a property is changed – take a look at PropertyChangeSupport.

Parsing data back to mainPanel (java/swing)

Set up:
I have a mainPanel with a tabbedPane on it, i have a separate JPanel 'extra', extra creates an objects and i wish to pass that object back through to the mainPanel where i can actually use it/add it to the data structure.
Frame > Panel > TabbedPane > Panel (Separate Class, instantiated as new object)
I tried to add a listener in mainPanel that checks if a boolean in PanelExtra changes and then runs a method etc, but it didn't work.
I would make a method in mainPanel to accept the object but i don't know how to refer back to it. (getRootPane() didn't return anything)
Also im not sure if im using correct terminology, while i was taught Java in a command line Unix environment, Swing is very new to me.
I tried Listeners, Observers and am currently considering an object created at root and passed DOWN through all objects (As java passes by reference, i could pass information back as far as i want) If that isn't an entirely stupid idea, let me know and we can all go about our lives. If there is a better way to do it that'd be great.
(File overview)
[programApp]>[programView>tabbedPane]>[panel]
Panel is created using new, and exists in a separate class.
I want to pass data back from Panel to programView (projectNameView as it is in netbeans)
I will attempt to add as much information as i can.
You can use the MVC-pattern for that.
Actually there are couple of variants depending on your preferences or exact task.
For very simple case you can just use class with static fields to pass objects.
Another way is to define your own listeners like:
private myPanel extends JPanel implements Notification {
...
and where you create that panel:
myPanel.addNotificationReciever(mainPanel);
Later you just call fireNotification or whatever and implement similar listener for your mainPanel.
SirVaulterScoff gave the best answer in my opinion, but I thought I'd add some more (can't add comments yet, so I'm creating a new answer).
You should also read the Observer-Observable pattern (Wikipedia article), which is used along with the MVC pattern. It will be useful when linking your MVC classes together, to make sure everything is as loosely coupled as possible.
As a side comment: MVC is really a pattern you should focus on if you are to create applications with a user interface. It will save you many headaches, and will make your application easier to maintain and extend.

Categories

Resources