Reputation: 685
I have this small little code but I don't know why it cannot read the value of the aa.width
from aa
class in ab
class.
I am trying to create a basic game. The file ab.java
has the print statement. I know I am not calling the function in aa
, but that's how java works. I thought I could just do aa.width
and I will get the value as it is a public variable...thanks for your help
aa.java :
package com.Game;
import javax.swing.JFrame;
public class aa {
public static ab f= new ab();
public static int width = 600;
public static int height = 400;
public static void main(String args[]){
f.setSize(width,height);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("game first");
f.setLocationRelativeTo(null);
System.out.println("main window running!");
}
}
ab.java
package com.Game;
import java.awt.GridLayout;
import javax.swing.*;
public class ab extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public ac panel;
public ab() {
panel = new ac(this);
setLayout(new GridLayout (1,1,0,0));
add(panel);
System.out.format("the value of width %d\n", aa.width);
}
}
it prints out :
the value of width 0
main window running!
Upvotes: 0
Views: 181
Reputation: 2552
I would like to suggest you also not to use too much public variables, instead each object should have its private variables and a setter/getter method. I suggest you also to check the structure of your game and the way you are trying to create it, if you are very new to java GUI and/or MVC (model view controller) maybe you want only to create a single class with what you need all inside or, one step further, a class handling the logic and a class handling all the graphics. If you do a great thinking before coding you probably will have a faster coding and debugging.
I cannot tell you more because I cannot understand what your code wants to do.
Upvotes: 0
Reputation: 10497
You are setting aa.width
variable after calling ab()
constructor.
Move the public static int width = 600;
one line up and you are done.
Upvotes: 6