开发者

Using Different Java Code in a Project (How to reach variables)

I wrote a simple drawing program, and for to create a menu, I used this source, http://download.oracle.com/javase/tutorial/displayCode.html?code=http://download.oracle.com/javase/tutorial/uiswing/examples/components/MenuLookDemoProject/src/components/MenuLookDemo.java

Therefore in my program to show the menus, I only added these lines:

    MenuDemo demo = new MenuDemo();
    frame.setJMenuBar(demo.createMenuBar());

When I started the program, menu successfully works, but on the other hand, for example, when I click sth on menu, in method "actionPerformed" I want to change my program's boolean variable. But "actionPerformed" is exist in "MenuLookDemo.java", therefore I cannot reach the variabl开发者_高级运维es.

Can you suggest a solution please ?

Thanks


Maybe you can rewrite the class MenuDemo and pass your Object to MenuDemo to access your variable.

class MenuDemo{
  YourType obj;
  MenuDemo(YourType obj){
    this.obj = obj;
  }
  // Now you can access elements of obj
}


Building off of what Pikaurd has above, do this:

public class MyType {
  int x;
  public void doTheNeedful() {
    x = 5;
  }
}

Then make sure MenuDemo contains a field obj of class MyType. Inside actionPerformed(), call obj.doTheNeedful().

I'm deliberately not just giving you the code on this; the sentence above should be enough for you to figure it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜