简体   繁体   English

Java:看不到我的变量

[英]Java: can't see my variable

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. 我有这么小的代码,但是我不知道为什么它不能从ab类中的aa类读取aa.width的值。

I am trying to create a basic game. 我正在尝试创建一个基本的游戏。 The file ab.java has the print statement. 文件ab.java具有print语句。 I know I am not calling the function in aa , but that's how java works. 我知道我没有在aa调用该函数,但这就是java的工作方式。 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.width ,我会得到值,因为它是一个公共变量...感谢您的帮助

aa.java : 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 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!

You are setting aa.width variable after calling ab() constructor. 您要在调用ab()构造函数之后设置aa.width变量。 Move the public static int width = 600; 移动public static int width = 600; one line up and you are done. 一排,您就完成了。

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. 我想建议您也不要使用过多的公共变量,而是每个对象都应具有其私有变量和setter / getter方法。 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. 我建议您还检查游戏的结构以及尝试创建游戏的方式,如果您是Java GUI和/或MVC(模型视图控制器)的新手,也许您只想用自己的内容创建一个类需要所有内容,或者更进一步,需要一个类处理逻辑,并一个类处理所有图形。 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. 我无法告诉您更多信息,因为我无法理解您的代码想要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM