Reaching object on other jFrame - java

How can I reach jPanel on an other jFrame ?
I want to impel users question.According to answer(yes),I want to get jPanel.setVisible(true)
on an other jFrame

I want to impel users question. According to answer(yes), I want..
See the overloaded methods of JOptionPane.showConfirmDialog(..).

Use some kind of model, which can be altered by your first frame, but which your second frame is listening to.
You should very rarely try and access UI elements that are outside the scope of your current class, as this leads to no end of issues with trying to figure out who is control.
This is at the core of the Model-View-Controller paradigm and observer pattern
You should also have a look at The Use of Multiple JFrames: Good or Bad Practice?

First of all, please change your question because it is very hard to understand what you want from us.
Now to your problem:
I think you want to access a jPanel that is located at the other JFrame.
My Solution:
Just make a reference to it!
So if you have a class MyFrame, just make it look like this one:
public class MyFrame{
private JPanel panelThatIsLocatedAtTheSecondFrame
//Setter and Getter and the other bullshit :D
}
public static void main(String[] args){
MyFrame frame1 = new MyFrame();
MyFrame frame2 = new MyFrame();
JPanel panelIWantToObserve = new JPanel();
frame2.add(panelIWantToObserve);
frame1.setPanelThatIsLocatedAtTheSecondFrame(panelIWantToObserve);
}

Related

Basic JPanel/JFrame class problem in Java

I started not so long ago learning Java through tutorials and videos, and after understanding a few things (how buttons, layouts, audio, and a few other things work) one of my goal now is to create a little interactive game.
I wrote a pretty big part of the game in the Main Class and it was working good, but it got messy after a while.
So I decided to try another time from the beginning using different classes for every part of the game to make the code look more clear and understandable.
But I have a problem from the very beginning and after a few hours of searching tutorials, answers on forums and not finding a precise answer, I think it's the best if you will see exactly my problem (which is very simple!)
-So I just constructed the JFrame in a class (I use the main Class only to launch the frame, and it works fine) :
import javax.swing.*;
import java.awt.*;
public class principalFrame {
public principalFrame(){
JFrame mainFrame = new JFrame();
mainFrame.setVisible(true);
mainFrame.setSize(1200,750);
mainFrame.getContentPane().setBackground(Color.BLACK);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}
}
and I created a JPanel in another class :
import javax.swing.*;
import java.awt.*;
public class mainMenu{
public mainMenu(){
JPanel menuPanel = new JPanel();
menuPanel.setSize(300,300);
menuPanel.setBackground(Color.BLUE);
}
}
And my goal is to add the JPanel inside the JFrame. And... I don't understand how to do it.
I tried to add the menuPanel class as an object in the mainFrame class so I could add the JPanel but it did'nt work. Then tried a bunch of other solutions from what I read on older questions but nothing really helped me.
PS : I know that I didn't add any layout manager or any other things in the code here because I want to keep the code very simple for the question.
So if you want to make a separate class for mainMenu, you should make it extend JPanel. This way, your mainFrame class can instantiate it.
Here is what I would tell you about the lessons I learned in building things in swing:
You (almost) never need a separate class to create a JFrame. If you create a class that extends JPanel, it is easy enough to create a JFrame in a static method (like main) to put your JPanel in. That being said, if you also want to use the JLayeredPane or want to add menus on a JMenuBar, there might be a case of subclassing JFrame. The advantage of not subclassing JFrame is that it makes it easier to stick your JPanel into a JFrame, a JDialog (via JOptionPane) or a JWindow.
Unless you have a Component that you think could be useful in other applications, you should build your entire GUI in one class, and also use that class as the Controller. What is an example of a Component that could be used in other applications? Back in the day, I made a "ColorButton" swing class, for color picking. This component has a self-contained model, has its own controller and an API to get the picked color. (https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/ex/) which makes it reuseable. But normally, the elements of the GUI you are building aren't really reuseable outside of what you are doing in that class.
With that said, to the code you posted above:
Your mainMenu JPanel isn't accessible outside the class, so that is probably a problem. As I said in the paragraph above, if you're not sure that the Component you are creating could be used in another place, it is better to put the entire view and model building in the same class as the controller
You were close. You have to be able to get the JPanel from the MainMenu class.
The JFrame methods must be called in a specific order. This is the order I use for my Swing applications.
Class names start with an upper case character.
Here's one way you could code your MainMenu class.
public class PrincipalFrame {
public PrincipalFrame() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainMenu().getMenuPanel(), BorderLayout.CENTER);
mainFrame.setSize(1200, 750);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
public class MainMenu {
private final JPanel menuPanel;
public MainMenu() {
this.menuPanel = new JPanel();
this.menuPanel.setPreferredSize(300, 300);
this.menuPanel.setBackground(Color.BLUE);
}
public JPanel getMenuPanel() {
return menuPanel;
}
}

Swing: Visual interface connect to second frame

I have 2 frames. I want from the first frame to open the second. I tried this, but it leads to an exception.
class aboutaction implements ActionListener {
public void actionPerformed(ActionEvent e) {
frame.dispose();
aboutInfo about = new aboutInfo();
about.frame.setVisible(true);
}
}
about.addActionListener(new aboutaction());
This is the full program: https://github.com/Zhelyazkov97/Fuel-calculator.git.
You're basic problem is a NullPointerException create from a misunderstanding of how Swing works and a bad design.
Basically, you define your class as...
public class aboutInfo extends JFrame {
private JPanel contentPane;
javax.swing.JFrame frame;
Now, here the confusion starts, you basically have two frames, but you only ever add components to the instance of aboutInfo.
The basic answer here is, get rid of frame, it's just confusing the issue. In fact, you shouldn't be extending from JFrame in the first place, you should really use something like JPanel and simply add instances of the class to instances of JFrame or JDialog or what ever container you want

java: how can i pass a variable from the starter JFrame to the last without having to pass it through all JFrames?

I have this problem: I have an ArrayList that contains a few items that I want to use in a particular frame, the problem is that the array list gets full by initializing it in the main class of my project. In this class I also launch my starting frame that is chained with other frames (login frame -> middle frame --> last frame). I want to carry this ArrayList without having to carry it on through all frames and get it directly usable from main --> last frame. How can I do this?
EDIT
Wat I did it was like first frame start with this ArrayList as parameter:
Jframe jf = new LoginFrame(arraylistvariable,"Login Window");
Then in all ActionListener calls on the buttons that create new frames, disposing old ones, I set it like:
Jframe jo = new MiddleFrame(arraylistvariable,"Middle Window");
Passing this variable all over the frames but I want this to be like called only by the frame that needs this, because login frame doesn't need this variable. However, it is necessary to start the program by the login frame.
"However, it is necessary to start the program by the login frame."
No it's not.
public class MiddleFrame() {
private LoginFrame;
}
...
public static void main(String[] args){
new MiddleFrame();
}
Make the middle frame not visible upon instantiation, but make the LoginFrame visible. If the login is successfful, but make the MiddleFrame visible.
Note You don't need to use to many frame. Make use of JDialogs. See this answer for How to make a Login with a JDialog
one from the easiest way it to pass it/them trough system properties
You might want to create some class like ArrayListVariableProviderService and make it accessible either to all classes (JFrames) or via static call.
This can act as a container to many things, yet it'll abstract out all peculiarities.
Good luck.

How can I pass "this" into an action listener

I have a MainWindow class that extends JFrame and is the only frame in my application. I have several JPanels to change its content though. I would like to pass the MainWindow around so I won't have to make a global copy of it.
Here is the problem. I have a fake JMenuBar in MainWindow that I use to go around and look for screens. In their JMenuItem listeners, I cannot pass MainWindow as this to the JPanels.
Is there a way I can do that, like maybe marking the class final or do I have to create a new MainWindow each time I have to pass in one. It doesn't carry around any data so its not crucial and the performance isn't a major concern for a small final project like this but I want to know if there is a better way?
Are you unable to pass this because it would reference the listener? If so, you should be able to use MainWindow.this.
Or create a reference to this outside the listener and pass that as the parameter.
Create the MainWindow class as the Outer class and extend this to JFrame which u already did, . Now in the MainWindow class, create as many inner classes as you want and let the handle the ActionListener method in different way..
eg:
MainWindow extends JFrame {
MainWindow(){
}
class panel1 extends JPanel implements ActionListener{
}
class panel2 extends JPanel implements ActionListener{
}
}
You can also implement Singleton Pattern, so that makes sure there is only one instance of MainWidow.
Try any of this approaches:
Make MainWindow singleton.
Mark as final a variable in the method when you create the listener.
Use MainWindow.this
For your case use the singleton approach, with that you can access freely from any place of your project.

Passing a value from a JFrame to a JPanel

I have an annoying problem using JFrames and JPanels. I have a class extending a JFrame and in the contructor I have a string. I want to pass this value into the JPanel also in the contructor. I cant think how to do it. This is what I did:
public class NewFileMaker extends JFrame{
private String name;
public NewFileMaker(JPanel j, String newfilename){
setTitle("New File");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(j);
this.pack();
this.name = newfilename;
}
Is there a way of passing the value "name"? I could extend JPanel and create a new class and a new method, but it would require a lot of reworking a lot of other classes.
MORE INFO:
I took the advice and extended JPanel, which was actually really painless.
The NewFileMaker class is called in another class like this
new NewFileMaker(new GeneratePanel(getFileName()));
where getfileName() gets the name I wanted. Actually the solution is so simple I have to apologize to everybody. Sorry for wasting your time!
i think that the best solution would be extending jpanel.
Anyway if you can't do that maybe you can add to jframe a PropertyChangeListener.
JPanel doesn't have a string constructor, so you can't pass it in that way.
You can try calling panel.setName(name) instead.

Categories

Resources