从另一个类访问静态变量 [英] Access static variable from another class

查看:112
本文介绍了从另一个类访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个程序包中有两个类.我已经在一类中声明了static variable,并想在另一类中访问该变量.

I have two classes in same package. i have declared a static variable in one class and want to access that variable in another class.

这是我在其中声明静态变量的代码

Here is my code in which i have declared the static variable

public class wampusGUI extends javax.swing.JFrame {

    static String userCommand;

    public wampusGUI() {
        initComponents();
    }

    public void setTextArea(String text) {
        displayTextArea.append(text);
    }

    private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
        userCommand = commandText.getText();
    }

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                wampusGUI w = new wampusGUI();
                w.setVisible(true);
                Game g = new Game(w);
                g.play();
            }
        });
    }
}

这是我要访问变量的代码

Here is the code in which i want to access variable

public class Game {

    private wampusGUI gui;

    public Game(wampusGUI w) {
        world = new World();
        world.start();
        gui = w;
    }

    public void play() {
        gui.setTextArea(welcome());
        gui.setTextArea(describe());
        for (;;) {
            String s = userCommand; // here value should come should 
            System.out.println(userCommand);
            Command c = Command.create(s);
            String r = c.perform(world);
            // is game over?
            if (r == null) {
                break;
            }
            System.out.println(r);
        }
        System.out.println("Game over");
    }
}

但是,我可以将第一类的变量作为参数传递.但是问题是,当我将要运行程序时,该值第一次会为null,这是我不希望的.我想在textfield中输入值时,它应该转到另一个类.

However, i can pass the variable from first class as a argument. but the problem is that, when i will run program the value is going null first time, which i dont want. i want when i enter value in textfield then it should go to another class.

谢谢.

推荐答案

我建议您使用一种或多种侦听器,以允许Game对象侦听并响应GUI对象状态的变化.有几种方法可以做到这一点,但是我发现的最优雅,最有用的方法之一就是使用Swing固有的PropertyChangeSupport来允许您使用PropertyChangeListeners.所有Swing组件都将允许您向其添加PropertyChangeListener.因此,我建议您执行以下操作,让Game向WampusGUI类(应大写)中添加一个对象,如下所示:

I suggest that you use a listener of one sort or another to allow the Game object to listen for and respond to changes in the state of the GUI object. There are several ways to do this, but one of the most elegant and useful I've found is to use Swing's own innate PropertyChangeSupport to allow you to use PropertyChangeListeners. All Swing components will allow you to add a PropertyChangeListener to it. And so I suggest that you do this, that you have Game add one to your WampusGUI class (which should be capitalized) object like so:

public Game(WampusGUI w) {
  gui = w;

  gui.addPropertyChangeListener(new PropertyChangeListener() {
     // ....
  }

这将允许Game监听gui状态的变化.

This will allow Game to listen for changes in the gui's state.

然后,您要使gui的userCommand字符串成为绑定属性",这意味着给它提供一个setter方法,该方法将触发属性更改支持,通知所有侦听器更改.我会这样:

You'll then want to make the gui's userCommand String a "bound property" which means giving it a setter method that will fire the property change support notifying all listeners of change. I would do this like so:

public class WampusGUI extends JFrame {
   public static final String USER_COMMAND = "user command";
   // ....

   private void setUserCommand(String userCommand) {
      String oldValue = this.userCommand;
      String newValue = userCommand;
      this.userCommand = userCommand;
      firePropertyChange(USER_COMMAND, oldValue, newValue);
   } 

然后,您只能通过以下setter方法更改此String的值:

Then you would only change this String's value via this setter method:

private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
  setUserCommand(commandText.getText());
}

然后,游戏的属性更改侦听器将做出如下响应:

The Game's property change listener would then respond like so:

  gui.addPropertyChangeListener(new PropertyChangeListener() {

     @Override
     public void propertyChange(PropertyChangeEvent pcEvt) {

        // is the property being changed the one we're interested in?
        if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {

           // get user command:
           String userCommand = pcEvt.getNewValue().toString();

           // then we can do with it what we want
           play(userCommand);

        }

     }
  });

此技术的优点之一是,被观察的类GUI不必对观察者类(游戏)有任何了解.一个小的可运行示例如下:

One of the beauties of this technique is that the observed class, the GUI, doesn't have to have any knowledge about the observer class (the Game). A small runnable example of this is like so:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;

public class WampusGUI extends JFrame {
   public static final String USER_COMMAND = "user command";
   private String userCommand;
   private JTextArea displayTextArea = new JTextArea(10, 30);
   private JTextField commandText = new JTextField(10);

   public WampusGUI() {
      initComponents();
   }

   private void setUserCommand(String userCommand) {
      String oldValue = this.userCommand;
      String newValue = userCommand;
      this.userCommand = userCommand;
      firePropertyChange(USER_COMMAND, oldValue, newValue);
   }

   private void initComponents() {
      displayTextArea.setEditable(false);
      displayTextArea.setFocusable(false);
      JButton enterButton = new JButton("Enter Command");
      enterButton.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent evt) {
            enterButtonActionPerformed(evt);
         }
      });
      JPanel commandPanel = new JPanel(); 
      commandPanel.add(commandText);
      commandPanel.add(Box.createHorizontalStrut(15));
      commandPanel.add(enterButton);

      JPanel mainPanel = new JPanel();
      mainPanel.setLayout(new BorderLayout());
      mainPanel.add(new JScrollPane(displayTextArea));
      mainPanel.add(commandPanel, BorderLayout.SOUTH);
      add(mainPanel);
   }

   public void setTextArea(String text) {
      displayTextArea.append(text);
   }

   private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
      setUserCommand(commandText.getText());
   }

   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            WampusGUI w = new WampusGUI();
            w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            w.pack();
            w.setLocationRelativeTo(null);
            w.setVisible(true);
            Game g = new Game(w);
            g.play();
         }
      });
   }
}

class Game {
   private WampusGUI gui;

   public Game(WampusGUI w) {
      gui = w;

      gui.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {

            // is the property being changed the one we're interested in?
            if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {

               // get user command:
               String userCommand = pcEvt.getNewValue().toString();

               // then we can do with it what we want
               play(userCommand);

            }
         }
      });
   }

   public void play() {
      gui.setTextArea("Welcome!\n");
      gui.setTextArea("Please enjoy the game!\n");
   }

   public void play(String userCommand) {
      // here we can do what we want with the String. For instance we can display it in the gui:
      gui.setTextArea("User entered: " + userCommand + "\n");
   }

}

这篇关于从另一个类访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆