从另一个类访问静态变量

RK.*_*RK. 5 java oop swing static

我在同一个包中有两个类.我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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我想要访问变量的代码

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我可以将第一类中的变量作为参数传递.但问题是,当我将运行程序时,值第一次为空,我不想要.我想当我输入值textfield 然后它应该去另一个类.

谢谢.

Hov*_*els 2

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

public Game(WampusGUI w) {
  gui = w;

  gui.addPropertyChangeListener(new PropertyChangeListener() {
     // ....
  }
Run Code Online (Sandbox Code Playgroud)

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

然后,您需要将 gui 的 userCommand String 设置为“绑定属性”,这意味着为其提供一个 setter 方法,该方法将触发属性更改支持,通知所有侦听器发生更改。我会这样做:

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);
   } 
Run Code Online (Sandbox Code Playgroud)

那么你只能通过这个 setter 方法更改这个字符串的值:

private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
  setUserCommand(commandText.getText());
}
Run Code Online (Sandbox Code Playgroud)

游戏的属性更改侦听器将像这样响应:

  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);

        }

     }
  });
Run Code Online (Sandbox Code Playgroud)

该技术的优点之一是被观察类(GUI)不需要了解观察者类(游戏)的任何知识。一个小的可运行示例如下所示:

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

}
Run Code Online (Sandbox Code Playgroud)