How do I set JFrame size from different class - java

I've got two classes. My QuizatMainClass class and a class called window. I'm trying to create a window from the Quizat class with a set size but it won't compile. I've set the parameter to (x and y) e.g (1080 and 720). But it does'nt like that. I'm new to Java and don't really understand why I can't do this. The way the IDE fixes it is with something about superclass stuff. If someone could explain what this means to me or a more simple way to do what I'm trying to run I'd appreciate it. Layman's terms please.
QuizatMainClass:
package Quizat;
public class QuizatMainClass extends Window{
public static void main(String[] args) {
Window QuizatHomeScreen = new Window(1080, 20);
}
}
Window Class:
package Quizat;
import javax.swing.JFrame;
public class Window{
public Window(int x, int y){
JFrame window = new JFrame();
window.setSize(x,y);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
}

The explanation for your problem is that since QuizatMainClass extends the Window class, and Window has a specific parameter-using constructor, the QuizatMainClass will either need to create a constructor that specifically calls Window's super constructor with parameters, or else give Window a default no-arg constructor.
Having said that your real problem is that you're misusing inheritance. QuizatMainClass shouldn't extend the Window class, that's it.

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.

Why isn't my code being read after the Frame construction?

Right after I create a new Frame object to attach future JPanels to, the references to the object "j" aren't recognized.
package engine;
import javax.swing.*;
public class GamePanel extends JFrame{
final int HEIGHT=700, WIDTH=500;
JFrame j= new JFrame("LittleRPG");
j.setSize(HEIGHT, WIDTH);
}
the j.setSize(); isn't accepted and an error appears (this applies to all object references after the initial construction of them). I need help identifying why; fresh eyes always help. -Thank you
You dont need to create separate object of JFrame to set size because you already extended the GamePanel Class From JFrame. So, You can directly set it in the constructor GamePanel as your code look like:
package engine;
import javax.swing.*;
public class GamePanel extends JFrame
{
final int HEIGHT=700, WIDTH=500;
GamePanel ()
{
setSize(HEIGHT, WIDTH);
}
}
Your setSize(HEIGHT, WIDTH); method has to be inside of a constructor or another method. Like #Vikas Suryawanshi said, you could just call the methods of JFrame, you dont need to create a new Object of it.
The answers of #Tupfer and #Vikas are correct.
Still you want to do it using the object of Jframe then
package engine;
import javax.swing.*;
import java.awt.Color;
public class GamePanel extends JPanel{
final int HEIGHT=700, WIDTH=500;
public static void main(String[] args){
JFrame j= new JFrame("LittleRPG");
j.setSize(HEIGHT, WIDTH);
j.getContentPane().add(new GamePanel());
j.setVisible(true);
j.setLocationRelativeTo(null);
j.setBackground(Color.BLUE);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also you do not need to extend JFrame

Java: Cannot be Referenced From a Static Context

I'm trying to make a frame with a panel consisting of two buttons which reside at the bottom of the frame.
public class ControlledBall extends JPanel {
public static void main(String[] args) {
JFrame Frame = new Viewer();
Frame.setSize(1000, 500);
Frame.setTitle("Bouncing Ball");
Frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
Frame.setVisible(true);
}
public class Viewer extends JFrame {
JButton buttonGo = new JButton("GO");
JButton buttonStop = new JButton("STOP");
JPanel aPanel = new JPanel();
public Viewer() {
aPanel.add(buttonGo);
aPanel.add(buttonStop);
this.add(aPanel, BorderLayout.SOUTH);
}
}
}
The problem here is this:
JFrame Frame = new Viewer();
It is telling me
ControlledBall.this cannot be referenced from a static context
How do I fix it?
You could do something like:
JFrame Frame = new ControlledBall().new Viewer();
instead of:
JFrame Frame = new Viewer();
But I'm not sure this is really what you want since ControlledBall is a JPanel...
Instances of non static inner classes hold a pointer to their enclosing object to be able to reference its members. See for example Java inner class and static nested class One side effect is that they cannot be instatiated from static methods, which have no relation to an actual instance of the enclosing class except by instatiating an intermediate object of your ControlledBall class.
PS: Another side effect to keep in mind (not so relevant for your use case) of this implicit this pointer is that it may cause resource leaks because it keeps the outer instance alive as long as the inner one lives.
You've created an public inner class inside the ControlledBall class, which is why you can't access it, as you don't have an instance of the ControlledBall class.
Guessing from the indentation and your code though, what you probably meant to do was create two seperate classes and instantiate the Viewer class from the main method of ControlledBall. To do that, move the Viewer class to its own file named Viewer.java and it should work.
The "main" method is static and when executed, its "containing" class might not yet been instantiated and so class Viewer might not yet exist. Since this example is apparently the program's entry point, "Viewer" most certainly does not yet exist.
There are many ways to resolve this, such as creating an instance of ControlledBall and then use that instance to create "Viewer".
It is my personal style to "get out of static" ASAP in a Java program by instantiating an instance of "main"s container and then running from there. I was taught that "main" is static so it exists to be called by the parent system and not much more use than that, I'm sure there are other opinions. Here is a brief example, which lacks many details:
public static void main(String[] args) {
// Pass 'args' to which ever method you prefer
ControlledBall app = new ControlledBall(args);
app.run(args);
}
private void run(String[] args) {
JFrame Frame = new Viewer();
}
I use 'run' because of Thread. I know many darts can be thrown at this, its just an example.
Make the inner class (Viewer) static
public static class Viewer extends JFrame
you can not acces non-static things from static methods

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

Methods in built-in classes

I am kinda new to java. I was reading java codes to learn more about it, and this had me confused. A method would only be performed if only it is called, right? But how about those methods of built-in classes like paint(), paintComponent(), run() in Runnable class, etc. Are these methods performed without explicitly calling them, once a class that implements these methods is used to instantiate an object? Is that really how it works?
Like for example in this code, method paint() was not really called.
import javax.swing.*;
import java.awt.*;
public class FrameExampleTest{
public static void main(String args[]){
FrameExample frame = new FrameExample();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class FrameExample extends JFrame{
PanelExample panel;
public FrameExample(){
Container c = getContentPane();
panel = new PanelExample();
c.add(panel,BorderLayout.CENTER);
}
}
class PanelExample extends JPanel{
public PanelExample(){
setSize(300,200);
}
public void paint(Graphics g){
g.fillArc(20,20,30,30,0,360);
}
}
You don't call paint or run yourself, but other code in the JVM does call it for you. For instance code inside the Thread class will call your run method. Code inside the event loop will call paint or paintComponent. Over time, you will see that there's nothing magical. Whenever a method is called, some other code calls it.
Yes. The window framework calls paint and paintComponent methods for you. It figures out when the paint/repaint is required (e.g. when window is moved, opened, re-opened, resized, etc). Javadoc to these methods sometimes mentions it isn't advised/not required to call them directly, but is required to implement them to do such and such things.

Categories