Passing a value from a JFrame to a JPanel - java

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.

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;
}
}

Reaching object on other jFrame

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);
}

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.

java pass object from JFrame to JPanel

I am developing a standalone application, in Java using NetBeans, that gets and sends data via Serial Port. I am using a great API for Serial communication called java simple serial connector http://code.google.com/p/java-simple-serial-connector/
Please download the following NetBeans project that I created:
http://netload.in/dateiN9xmwRtn19.htm
Even if you do not have netbeans you can still view the code.
The above is a small example project that I made to explain what I wish to accomplish. The example contains a JFrame that contains the main method. This JFrame contains 2 panels: a Panel with navigation buttons, and a Panel that displays Panel 1 and Panel 2 using CardLayout.
In the JFrame I have a method that gets port names list using the getPortNames() method of the jssc API. My question is, how do I pass these port names String values from JFrame to my Panel 1, without using the following since it will not work:
MyJFrame myjframe = new MyJFrame();
myjframe.getPortNames();
Hovercraft Full Of Eels
Once again thank you very much for your explanation, it is worth gold. I now realize that my problem is NetBeans rather than Java. I am not familiar with it enough but I would still prefer to use it due to the size and complexity of my project. I have uploaded 2 more screenshots below, that show how I tried to pass the "this" reference of the JFrame object to my JPanel object in NetBeans. As you can see in the MyJFrame.java screenshot, NetBeans has underlined "this" reference as an error. Would you please be able to help me with this problem? Also, in the first sentence of your explanation you mention that the serial port methods should be in a separate class, not in JFrame, since they are non-GUI methods. I fully agree with you and I would prefer to do it that way since it is the correct object-oriented approach. But doing it that way, I am once again facing the same problem in NetBeans. How do I now pass the object reference from SerialPorts.java class to JFrame, JPanel etc in a way so that I am not creating a new SerialPorts object all the time, remember I need the connection to stay open all the time (ex. without using SerialPorts sp = new SerialPorts();). Thank you so so so much for your help.
Adding "this" in code customizer for Panel 1
MyJFrame.java - editor underlines reference "this" as error
I wonder if you should have the port names held by a non-GUI model class and obtained from it rather than from the "JFrame", but regardless your question is a specific example of a more of a general question: how do you pass information from one GUI object to another, and that can be generalized further to: how do you pass information from one object to another.
The simple answer is to have one object call a method on the other, which is what you've tried, and which is what should work, but the problem with your attempt is that you're calling it on the wrong object. You have a JFrame object that has already been constructed, that is visible, and that holds the information you need, and that is the object which you should be calling your method on, not a new JFrame object. Sure the new object is built from the same class, but understand that it is a completely different object from the one that's displayed which is the one you want.
So now your problem boils down to this -- how do I get a reference to the visualized JFrame into another object? There are many ways to do this, but the easiest way to do this is to probably pass a reference from one class to the other via a constructor or method parameter.
...
So for instance, say you've got a class called FooFrame that extends JFrame, and it holds a FooPanel object that extends JPanel, and suppose you want the FooPanel object to call the someMethod() method of FooFrame:
public class FooFrame extends JFrame {
public String someMethod() {
return myTextField .getText();
}
}
You could have FooPanel create a new FooFrame object and call this method as you're trying to do:
class FooPanel extends JPanel {
public void otherMethod() {
FooFrame fooFrame = new FooFrame();
fooFrame.someMethod();
}
}
But then you run into the same problem you're running into above. The FooFrame object created here is not the one being displayed, and so the contents of the JTextField will be empty and not very helpful. The solution I'm suggesting is that you pass a reference from the original JFrame into the JPanel via a constructor parameter like so:
class FooPanel extends JPanel {
private FooFrame fooFrame;
// constructor accepts a reference to a FooFrame object
public FooPanel(FooFrame fooFrame) {
this.fooFrame = fooFrame; // and sets its field with it
}
public void otherMethod() {
// no longer needed!
// FooFrame fooFrame = new FooFrame();
// now method is called on the right object!
fooFrame.someMethod();
}
}
Then you can create your FooPanel object in FooFrame and pass the FooFrame object (this) into it.
public class FooFrame extends JFrame {
private JTextField myTextField = new JTextField(10);
private FooPanel fooPanel;
public FooFrame() {
// the current FooFrame object is this!
fooPanel = new FooPanel(this);
add(fooPanel);
}
public String someMethod() {
return myTextField .getText();
}
}

Java Swing - Why JComponent won't display?

I'm trying to extend a class to eventually make a custom button. I read in several places that it's best to extend as high as possible on the heirarchy (for better polymorphism?), so I'm trying to extend JComponent:
import javax.swing.*;
import java.awt.*;
public class TestButton extends JComponent {
private static final long serialVersionUID = 1L;
public TestButton() {
super();
}
}
And the code that calls this is:
b1 = new TestButton();
basePanel.add(b1,gbc); // (gbc is GridBagConstraints object)
The thing is, my JComponent isn't displayed in my layout. If I extend the class as JButton, it shows no problem. What's the deal?
Update:
FYI, this is sort of a noob conceptual question, I'm far from proficient here obviously.
Here's a picture to describe. The only thing changed is extends ______.
What should be happening is a purple-filled block, the same height as the yellow block on the bottom.
What is happening is a default sized block that has no background (the black is from the JFrame).
One of the main differences between JComponent and it's subclasses is that the latter have UI delegates, while JComponent does not. Note that the setBackground() "color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations." As a result, you "must override paintComponent() to honor this property."
What do you expect to see in the place where JComponent is supposed to be? when you extend JButton, you get all its graphic with it, but you created an empty component, with nothing in it. Try putting something in the component (such as a JLabel or similar)
You still need to extends JButton if you want JButton's functionality. Otherwise everybody can extend Object and expect everything.
It is a blank component (basically a template). It has no properties. You have to add your own graphical elements by overriding the paintComponent method and then add logical elements by overriding the update method.
Either use the JButton as it is:
JButton b1 = new JButton("Enter JButton text here");
basePanel.add(b1,gbc);
or extend the JButton class if you wish to change certain properties and customize it for your own preferences:
public class TestButton extends JButton {
private static final long serialVersionUID = 1L;
public TestButton(String buttonText)
{
super(buttonText);
}
}

Categories

Resources