静态和非静态问题

时间:2013-04-25 09:23:56

标签: java static-methods non-static

我是Java新手,现在正在学习初学者课程。非常好,我正在尝试各种各样的东西,但现在我卡住了。 这段代码不起作用。它应该以相反的顺序(通过单词)输出输入。

翻转它的代码工作在我没有GUI编写的一段代码中,现在我试图让它在带有固定按钮,标签等的GUI中工作。 为此,我从互联网上复制了一个例子并尝试以这样的方式改变它,它将起作用。但它似乎没有找到我在actionPerformed中使用的变量,并在AddComponentsToPane中设置。它必须做一些静态和非静态的东西,我似乎无法弄清楚

任何帮助都将非常感谢。

继承代码。

package flipit;


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.*; //ArrayList;
import javax.swing.*;

public class FlipIt extends JFrame implements ActionListener {

public static void addComponentsToPane(Container pane) {

  pane.setLayout(null);

  JLabel     greetingLabel   = new JLabel("Enter your array ");
  JTextField inField         = new JTextField();
  JTextField commentaryField = new JTextField();
  JTextField strLen          = new JTextField();
  JButton    button          = new JButton("FlipIt");

  pane.add(greetingLabel);
  pane.add(inField);
  pane.add(commentaryField);
  pane.add(button);        

  Insets insets  = pane.getInsets();
  Dimension size = button.getPreferredSize();

  greetingLabel.setBounds (   5 + insets.left, 35 + insets.top,size.width + 40, size.height);
  inField.setBounds        (120 + insets.left, 33 + insets.top,size.width + 200, size.height);
  //size = commentaryField.getPreferredSize();
  commentaryField.setBounds(120 + insets.left, 80 + insets.top,size.width + 200, size.height);
  size = button.getPreferredSize();
  button.setBounds         (  5 + insets.left, 80 + insets.top,size.width + 40, size.height);

}

private static void createAndShowGUI() {
    //Create and set up the window.

    JFrame frame = new JFrame("Reverse the input string.");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    addComponentsToPane(frame.getContentPane());

    //Size and display the window.
    Insets insets = frame.getInsets();
    frame.setSize(500 + insets.left + insets.right,
                  425 + insets.top + insets.bottom);
    frame.setVisible(true);
}

    public static void main(String[] args) {
     Scanner input = new Scanner(System.in);

    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

public void actionPerformed(ActionEvent event) {

    String InputStr = inField.getText();
    int length = InputStr.length(); 

    if (InputStr.compareTo("") == 0 || InputStr == null) {
        commentaryField.setText("Please enter some data, this array is empty");
    }
    else {

        // Convert string variable to an ArrayList.
        List<String> list = new ArrayList<String>(Arrays.asList(InputStr.split(" ")));            
        // Converting ArrayList to a String Array
        String [] InputList = list.toArray(new String[list.size()]);

        int i = 0 ;
        String ReverseOrder = "" ;

        // starting for loop to print the array in reversed order.
        for (i=InputList.length-1;i>=0; i--)
            {ReverseOrder = ReverseOrder + " " + InputList[i] ;
           }
        // print result.
          commentaryField.setText(ReverseOrder);   
          strLen.setText("Lengte string : "+ length);  
     }
   }  
}

谢谢, 罗布。

1 个答案:

答案 0 :(得分:3)

主要问题是范围界定问题。由于您在addComponentsToPane方法中声明 小部件,因此从方法外部无法看到它们。

尝试将窗口小部件声明移到addComponentstoPane方法之外:

JLabel     greetingLabel   = new JLabel("Enter your array ");
JTextField inField         = new JTextField();
JTextField commentaryField = new JTextField();
JTextField strLen          = new JTextField();
JButton    button          = new JButton("FlipIt");

public static void addComponentsToPane(Container pane) {

  pane.setLayout(null);

  pane.add(greetingLabel);
  pane.add(inField);
  pane.add(commentaryField);
  pane.add(button);     
  // etc
}

正如你所指出的那样(抱歉,我的坏!)你的静态方法将无法访问小部件(因为它们现在是类实例的一部分)。

考虑静态与非静态的简单方法是,如果将某些内容声明为静态,则需要一个类实例才能访问它。因此,在您的代码中,为什么您可以这样做:

public void run() {
    createAndShowGUI();
}

实际上,这与执行此操作相同:

public void run() {
    FlipIt.createAndShowGUI();
}

请注意,您尚未创建FlipIt类的实例;您不需要,因为createAndShowGUI方法是static。但是,如果不是静态,则必须创建一个新的类实例,如下所示:

public void createAndShowGUI() {
    // do your thing - note NO LONGER STATIC
}

public void run() {
    // Create instance
    FlipIt flipper = new FlipIt();

    // Invoke method against class instance
    flipper.createAndShowGUI();
}

所以 - 为了使代码正常工作,最好的解决方案是使所有内容都是非静态的(当然除了main方法,必须是静态的)。< / p>

以下是整个代码示例全部放在一起 - 请注意,您可能需要制作createAndShowGUI方法public - 但我不这么认为。我用java编码已经有一段时间了,所以我无法确定。

package flipit;


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.*; //ArrayList;
import javax.swing.*;

public class FlipIt extends JFrame implements ActionListener {
  JLabel     greetingLabel   = new JLabel("Enter your array ");
  JTextField inField         = new JTextField();
  JTextField commentaryField = new JTextField();
  JTextField strLen          = new JTextField();
  JButton    button          = new JButton("FlipIt");

  public void addComponentsToPane(Container pane) {
    pane.setLayout(null);

    pane.add(greetingLabel);
    pane.add(inField);
    pane.add(commentaryField);
    pane.add(button);        

    Insets insets  = pane.getInsets();
    Dimension size = button.getPreferredSize();

    greetingLabel.setBounds (   5 + insets.left, 35 + insets.top,size.width + 40, size.height);
    inField.setBounds        (120 + insets.left, 33 + insets.top,size.width + 200, size.height);
    //size = commentaryField.getPreferredSize();
    commentaryField.setBounds(120 + insets.left, 80 + insets.top,size.width + 200, size.height);
    size = button.getPreferredSize();
    button.setBounds         (  5 + insets.left, 80 + insets.top,size.width + 40, size.height);
  }

  private void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Reverse the input string.");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    addComponentsToPane(frame.getContentPane());

    //Size and display the window.
    Insets insets = frame.getInsets();
    frame.setSize(500 + insets.left + insets.right,
                  425 + insets.top + insets.bottom);
    frame.setVisible(true);
  }

  public void actionPerformed(ActionEvent event) {
    String InputStr = inField.getText();
    int length = InputStr.length(); 

    if (InputStr.compareTo("") == 0 || InputStr == null) {
      commentaryField.setText("Please enter some data, this array is empty");

    } else {

      // Convert string variable to an ArrayList.
      List<String> list = new ArrayList<String>(Arrays.asList(InputStr.split(" ")));            
      // Converting ArrayList to a String Array
      String [] InputList = list.toArray(new String[list.size()]);

      int i = 0 ;
      String ReverseOrder = "" ;

      // starting for loop to print the array in reversed order.
      for (i=InputList.length-1;i>=0; i--) {
        ReverseOrder = ReverseOrder + " " + InputList[i] ;
      }

      // print result.
      commentaryField.setText(ReverseOrder);   
      strLen.setText("Lengte string : "+ length);  
    }
  }  

  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      //Schedule a job for the event-dispatching thread:
      //creating and showing this application's GUI.
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          FlipIt flipper = new FlipIt();
          flipper.createAndShowGUI();
        }
      });
    }
  }
}

希望有所帮助!