Can setDefaultCloseOperation work without specifying any object? - java

I came across a code which calls setdefaultcloseoperation() without reference to any object. I read that methods are called with reference to object. Here is the code
public class Mainpage extends JFrame implements ActionListener{
JFrame f = new JFrame("Mainpage");
public Mainpage() {
super("Mainpage");
f.setSize(1000,6000);
f.getContentPane().setLayout(null);
f.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); // how is this happening?
}
I want to know how setDefaultCloseOperation(EXIT_ON_CLOSE); is working. Thanks.

Well you extended JFrame. So in essence you are doing this.setDefaultOperation(EXIT_ON_CLOSE).
Also it doesn't make sense that you are creating a JFrame inside a JFrame.. unless this was an experiment of yours. Simple answer would be don't extend JFrame, and use
f.setDefaultOperation(EXIT_ON_CLOSE).

The method setDefaultCloseOperation refers to the current instance of JFrame.
Some side notes:
1) The second JFrame f is unnecessary here:
public class Mainpage extends JFrame implements ActionListener{
public Mainpage(){
super("Mainpage");
setSize(1000,6000);
...
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
2) Avoid using the null layout. See Doing Without a Layout Manager.

Related

Cannot change public variable type in a subclass

I need to make a subclass changing variable type.
My purpuse is to create a class that dynamically loads objects onto a form. This form can be a JFrame or JInternalFrame, so I want a class leading a property form that can be one of JFrame / JInternalFrame, so I can write methods and functions without duplicate code.
Something like
public class form {
public javax.swing.JFrame frm;
...... methods and functions.
public void init(String title)
{
frm = new JFrame(title);
}
}
and
class form_children extends form {
public javax.swing.JInternalFrame frm;
public void init(String title)
{
frm = new JInternalFrame(title);
}
}
so that when I use them I can do something like this
public form_to_create (String title, Boolean mdi_child)
{
if (mdi_child)
frm = new form_children();
else
frm = new form();
frm.init();
frm.dosomething -----> error for null object
}
but when I use an mdi_child, it gives me error for null object.
It seems that frm variable for super class is present, but frm for subclass is not.
Why?
I need to make a subclass changing variable type.
My purpose is create a class that dynamically loads objects onto a form. This form can be a JFrame or JInternalFrame, so I want a class leading a property Form that can be one of JFrame / JInternalFrame, so I can write methods and functions without duplicate code.
You are painting yourself in a corner by having your class extend JFrame, JInternalFrame or other top-level (or internal top-level) window, as this forces you to create and display these types of windws, 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, JInternalFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
Your child object has two "frm" properties. The JInternalFrame frm you added in its own definition and the Frame frm it inherited from its father.
Because of polymorphism in form_to_create you are accessing the frm from the superclass, which is not initialized, instead of the JInternalFrame one.
A solution would be to encapsulate the behaviour in methods.
public class Form {
JFrame frm;
public void init(String title){
frm = new JFrame(title);
}
public void doSomething(){
frm.doSomething();
}
}
public class Form_child{
JInternalFrame frm;
public void init(String title){
frm = new JInternalFrame(title);
}
public void doSomething(){
frm.doSomething();
}
}
And your form_to_create would look like this now:
public static void form_to_create(String title, Boolean mdi_child){
Form frm;
if (mdi_child) {
frm = new Form_child();
}else{
frm = new Form();
}
frm.init(title);
frm.doSomething();
}
By doing it this way, you are only exposing the behaviour through the doSomething() method, and the rest of the program doesn't care if a JFrame or a JInternalFrame is the one behind.
Even better, make an Interface that defines the common behaviour and have both form classes implement it. That way Form_child doesn't inherit a JFrame property it doesn't use.
Thanks.
I want to dynamically create my form, and view that as mdichild window or not child window.
Read an file from disk, analyze it and add panels, controls to my form, so decide if my form has to be a child in a jDesktopPanel as JInternalFrame or simply a JFrame without dependencies.
I thought Java was powerful... but I guess it is not possible.

How to add an anonymous instance off a class as an ActionListener

Im working on a lab that requires me to make a JFrame with 2 inner classes. One that entends JPanel, has a text area and a jbutton. And another that implements action listener. How do i add an anonymouse instance of the second class to my JButton that is already in an inner class. Here is the brief to get a better understanding.
here is the code i have written so far. I can get the Frame to appear, but the JPanel doesnt appear, nor does the JButtons or JTextArea.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class FormFrame extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new FormFrame();
frame.setLocationRelativeTo(null);
}
public FormFrame()
{
Container contentPane = getContentPane();
RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder());
//
// Here is where im lost...
//
contentPane.add(p);
setSize(300, 200);
setVisible(true);
}
class RegisterPanel extends JPanel
{
JPanel panel = new JPanel();
JTextField text = new JTextField();
JButton button = new JButton("Submit");
}
class SubmitResponder implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== RegisterPanel.button) //Asks me to make button static here
{
//Shows "No enclosing instance of the type FormFrame.RegisterPanel is accessible in scope"
RegisterPanel.this.text.setText("Submit Complete");
}
}
}
}
Any help with this would be much appreciated
You could pass the RegisterPanel instance to the action listener:
class SubmitResponder implements ActionListener {
private final RegisterPanel rp;
public SubmitResponder(RegisterPanel rp) {
this.rp = rp;
}
#Override
public void actionPerformed(ActionEvent e) {
rp.text.setText("Submit Complete");
}
}
There's no need to check the source btw. The AL is only listening to 1 source.
RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder(p));
p.button.addActionListener(new SubmitResponder());
Here the SubmitResponder is already an anonymous instance, quite literally, because it has no name.
Your error about "no enclosing instance" is unrelated. Since SubmitResponder is not an inner class of RegisterPanel (it's a sibling) it doesn't belong to an instance of RegisterPanel and so it cannot logically refer to RegisterPanel.this. How would it know which instance that is? There might be many, or even zero, depending on how many the parent FormFrame decides to create. It so happens that there's only one, but that's not the point. On the other hand if you said FormFrame.this there would be no doubt what that meant no matter the code did, unless RegisterPanel stopped being an inner class or it became static. Does that make sense?
To do what you want, the SubmitResponder needs to talk to RegisterPanel via a method in FormFrame. Incidentally you don't actually need to say FormFrame.this.doSomething() unless SubmitResponder also has a method called doSomething.
The instructions tell you that the RegisterPanel should be a field in the FormFrame class, which you haven't done. Something like this:
public class FormFrame extends JFrame
{
RegisterPanel panel;
...
public FormFrame()
{
panel = new RegisterPanel();
...
}
...
class SubmitResponder implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == panel.button)
{
panel.text.setText(...);
}
}
}
}
Now you can access panel from inside the SubmitResponder class.
As a side note, the instructions are using some terminology in an ambiguous and incorrect way:
"Anonymous instance" is not an official term with a precise meaning.
Using official definitions, "class field" would imply the static modifier. Given the context of the assignment, I doubt that's correct. It should probably have said "instance field".

Java add a jpanel in a jtabbed pane in a jframe from another class file

I am lost, can you please help?
I am trying to add a jPanel from a another class into a different file into a JTabbedPane in JFrame file.
Here is what I have so far.
jPanel1 = new javax.swing.JPanel();
One party needs a reference to the other in some way, for example, in your "other" class, you could provide a getter method...
public class OtherClass ... {
public JPanel getComponent() {
//...
}
}
Then in your main UI, you could use the instance of OtherClass to get a reference to the JPanel...
tabbedPane.addTab("My Awesome Tab", instanceOfOtherClass.getComponent());
But this is all hypernethtical and is just one possible solution...

Java Component With JPanel

I am trying to create a JFrame in Java, with a JPanel inside of it, which will hold a component.
I know how to add components using
panelname.add(component);
But I am making a class based off a JTextField and want to add the entire CLASS as a component into the JPanel, but when I do, Eclipse tells me:
The method add(Component) in the type Container is not applicable for the arguments (BetterText)
(BetterText been the name of the class)
So all it basically is, is a class with a JTextField setup with methods and such, but I want to add that class as a component to the JPanel. I looked at the JTextField.java class and cant see anything interesting there, it looks like an ordinary class like any other, but you are able to add an instance of that class to a JPanel, whereas with mine, you cant.
Any help will be appreciated, thankyou.
Also, if you know the solution, please post an example class.
Edit: Added code.
public BetterText(String defaultText) {
super();
//Sets up the textFields colours and the defaultText to display in it.
setProperties();
hasDefault = true;
this.defaultText = defaultText;
textField.addActionListener(this);
}
Another edit:
It also extends JTextField already.
public class BetterText extends JTextField implements ActionListener {
Make sure your JFrame, JPanel and JTextField extend the correct classes (if they are custom classes).
Some pseudo code:
public class BetterText() extends JTextField{
public BetterText(){
super();
}
}
And then to create the GUI:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
BetterText textField = new BetterText();
frame.add(panel);
panel.add(textField);
panel.pack();
panel.setVisible(true);
Verify that you are importing javax.swing.JComponent, then make your BetterText class inherit from JTextField.

Separate my ActionListener from my GUI class, doesn't work properly

This is how my code looked in the beginning: https://gist.github.com/anonymous/8270001
Now I removed the ActionListener to a separate class: https://gist.github.com/anonymous/8257038
The program should give me a little UI, but it just keeps running without any UI popup or errors.
Someone told me this:
In your GUI class constructor, you are creating a new nupuVajutus object, but since nupuVajutus extends the GUI class, when you create a nupuVajutus, you are also inherently calling the GUI class constructor by default, thus creating an infinite loop
If this is really the problem, then I have to say I am not that good and could use some help getting this program working with the classes separated.
You have indeed already been given the answer, although what you have is not an infinite loop, but infinite recursion, which will eventually cause a StackOverflowError.
Here's what happens:
new GUI() calls new nupuVajutus(). This creates a new nupuVajutus object by calling its constructor. Because nupuVajutus extends GUI, this means a nupuVajutus object is a GUI object with additional functionality. Therefore, because it is a GUI object, a GUI constructor needs to be called. The nupuVajutus constructor does not explicitly call a super constructor, so it implicitly calls the GUI() (no argument) constructor before executing. In this new call to the GUI() constructor, another new nupuVajutus() call is encountered, and so on, ad infinitum...
It seems to me you need to do some more research around Object Oriented Programming, in particular the topics of sub-classing, inheritance, object instances, and encapsulation. There are plenty of resources available to help you.
After you extracted your ActionListener into a separate file, you should not have changed it to extend GUI. That extends the class (which is like a blueprint) not an instance (which is like a something built using that blueprint) - remember: you can create multiple instances of a class.
Previously, the "nupuVajutus" ActionListener was an inner class, so it had access to all of the enclosing class' fields and methods. Now that it is no longer an inner class, it needs to be passed a reference to the GUI instance so that it can access its methods. Something like this:
public class NupuVajutus implements ActionListener {
private final GUI gui;
public NupuVajutus(GUI gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
// The GUI instance can now be accessed through the gui field, for example:
gui.something();
// ...
}
}
And in the GUI() constructor:
NupuVajutus nV = new NupuVajutus(this);
To be honest, though, there is nothing wrong with keeping your ActionListener as an inner class. If you're never going to use that class outside of the GUI class, then it is probably preferable for it to remain as an inner class.
What you are doing it extending the GUI class. This Does Not make then share the Same Fields Say you have a field field in your GUI class
public class GUI {
String field = "Hello";
}
Just because your Listener class extends GUI doesn't mean they will share the exact same field object. I think that's what you think is supposed to occur
public class Listener extends GUI implements ActionListener {
public void actionPerformed(ActionEvent e) {
field = "World";
}
}
The above does nothing the field in GUI. If you were to do this, you would need to access in a static way like line GUI.field = "World";. The above is also what causes in an infinite loop, as you need to instantiate the Listener in the GUI class. This is not really good practice or design.
One option would to use some sort of MVC pattern.
Another option would be to pass the values you need, to a constructor in your Listener class, and instantiate it in your GUI class with those values.
Run this example to see what I'm talking about. I have a MyListener class that I pass a Jlabel to, the same JLabel in the GUI class
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FieldTest {
private JLabel label = new JLabel(" ");
private JButton button = new JButton("Set Text");
public FieldTest() {
MyListener listener = new MyListener(label);
button.addActionListener(listener);
JFrame frame = new JFrame();
frame.add(label, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FieldTest();
}
});
}
}
class MyListener implements ActionListener {
JLabel label;
public MyListener(JLabel label) {
this.label = label;
}
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("Hello, FieldTest!");
}
}

Categories