java 静态与非静态使用 this 和事件处理程序

发布于 2024-08-13 07:38:35 字数 2973 浏览 5 评论 0原文

我正在尝试了解 java 的事件处理程序,并不断收到我创建的类型(静态/非静态)方法的错误。我试图编写的一些代码如下所示:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Main extends JFrame implements ActionListener{

  static private int[] intArray = new int[10000];
  static private int numOfInts = 0;
  static private int avg = 0;

  public static void main(String[] args) {

    //create main frame
    JFrame frame = new JFrame();
    frame.setTitle("Section V, question 2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(350, 250);
    frame.setLayout(new GridLayout(4, 1));
    frame.setVisible(true);

  //create instruction label and add to frame
  Label instructions = new Label("Follow the instructions on the exam to use this program");
  frame.add(instructions);

  //create textfield for index entry and add to frame
  JTextField indexEntry = new JTextField();
  frame.add(indexEntry);

  //create button for average and add to frame
  JButton avgBtn = new JButton("Click for Average");
  frame.add(avgBtn);
  avgBtn.addActionListener(avgBtn);

  //create panel to display results and add to frame
  JPanel resultsPanel = new JPanel();
  resultsPanel.setBackground(Color.BLUE);
  frame.add(resultsPanel);

  //read in from file
  readFromFile();

  //compute average
  computeAverage();

  System.out.println(avg);

}

static private void readFromFile(){
  try{
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream("numbers.dat");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    int i = 0;
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
      intArray[i] = Integer.parseInt(strLine);
      numOfInts++;
      i++;
    }
    //Close the input stream
    in.close();
    System.out.println ("numOfInts = " + numOfInts);
  }
  catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
  }
}

static private void computeAverage(){
  int sum = 0;

  for(int i = 0; i < numOfInts; i++)
    sum += intArray[i];

  avg = sum/numOfInts;

  //return avg;
}

public void actionPerformed(ActionEvent e){
      if(e.getSource() == avgBtn){
        computeAverage();
  }
}

}

应该设置一个 GUI,从文件中读取一些整数,然后在按下按钮时计算它们的平均值。但是,我不断遇到静态/非静态内容和事件处理程序的问题。我当前的错误是:
Main.java:35: javax.swing.AbstractButton 中的 addActionListener(java.awt.event.ActionListener) 无法应用于 (javax.swing.JButton)
avgBtn.addActionListener(avgBtn);

Main.java:91: 找不到符号
符号:变量 avgBtn
位置:主类
if(e.getSource() == avgBtn){

我知道编译器找不到 avgBtn 因为它是在另一个函数 (Main()) 中定义的,但是任何人都可以阐明如何将事件处理程序附加到它吗?尝试了“这个”也无济于事......提前致谢,如果您发现任何其他问题,我很想听听如何做得更好。

I'm trying to learn about java's event handlers and keep getting errors with type type (static/non-static) methods I create. Some code I'm trying to write looks like:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Main extends JFrame implements ActionListener{

  static private int[] intArray = new int[10000];
  static private int numOfInts = 0;
  static private int avg = 0;

  public static void main(String[] args) {

    //create main frame
    JFrame frame = new JFrame();
    frame.setTitle("Section V, question 2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(350, 250);
    frame.setLayout(new GridLayout(4, 1));
    frame.setVisible(true);

  //create instruction label and add to frame
  Label instructions = new Label("Follow the instructions on the exam to use this program");
  frame.add(instructions);

  //create textfield for index entry and add to frame
  JTextField indexEntry = new JTextField();
  frame.add(indexEntry);

  //create button for average and add to frame
  JButton avgBtn = new JButton("Click for Average");
  frame.add(avgBtn);
  avgBtn.addActionListener(avgBtn);

  //create panel to display results and add to frame
  JPanel resultsPanel = new JPanel();
  resultsPanel.setBackground(Color.BLUE);
  frame.add(resultsPanel);

  //read in from file
  readFromFile();

  //compute average
  computeAverage();

  System.out.println(avg);

}

static private void readFromFile(){
  try{
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream("numbers.dat");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    int i = 0;
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
      intArray[i] = Integer.parseInt(strLine);
      numOfInts++;
      i++;
    }
    //Close the input stream
    in.close();
    System.out.println ("numOfInts = " + numOfInts);
  }
  catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
  }
}

static private void computeAverage(){
  int sum = 0;

  for(int i = 0; i < numOfInts; i++)
    sum += intArray[i];

  avg = sum/numOfInts;

  //return avg;
}

public void actionPerformed(ActionEvent e){
      if(e.getSource() == avgBtn){
        computeAverage();
  }
}

}

Which is supposed to setup a GUI read in some ints from a file and then compute their average when a button is pressed. However, I keep getting problems with the static/non-static stuff and the event handers. My current error are:
Main.java:35: addActionListener(java.awt.event.ActionListener) in javax.swing.AbstractButton cannot be applied to (javax.swing.JButton)
avgBtn.addActionListener(avgBtn);

Main.java:91: cannot find symbol
symbol : variable avgBtn
location: class Main
if(e.getSource() == avgBtn){

I understand that the compiler can't find avgBtn because its defined within another function (Main()), but can anyone shed some light on how to attach an event handler to it? tried 'this' to no avail also...Thanks in advance, and if you see anything else wrong I'd love to hear how I can make it better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海之角 2024-08-20 07:38:35

你的代码有点乱,编译的话会出现更多语法错误。
您不应该混合使用 swing/awt 组件,例如:在 swing 中不要使用 Label,使用 JLabel,而对于 Panel,则使用 JPanel。

请注意 swing 的“J”前缀,如果您想了解更多有关 Java(Swing)的信息,或者甚至阅读一些基础教程,也许您应该阅读书籍。

除非您了解静态方法的用途,否则不要使用静态方法。

无论如何,这里是最接近您想要的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main extends JFrame implements ActionListener {
    private int[] intArray = new int[10000];
    private int numOfInts = 0;
    private int avg = 0;

    protected JButton avgBtn;
    protected JTextField indexEntry;
    protected JLabel instructions;
    protected JPanel resultsPanel;

    //constructor - construct the components here and do the initializations
    public Main(){
        //create main frame     
        this.setTitle("Section V, question 2");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(350, 250);
        this.setLayout(new GridLayout(4, 1));
        //this.setVisible(true);

        //create instruction label and add to frame
        instructions = new JLabel("Follow the instructions on the exam to use this program");
        this.add(instructions);

        //create textfield for index entry and add to frame
        indexEntry = new JTextField();
        this.add(indexEntry);

        //create button for average and add to frame
        avgBtn = new JButton("Click for Average");
        this.add(avgBtn);
        avgBtn.addActionListener(this);

        //create panel to display results and add to frame
        resultsPanel = new JPanel();
        resultsPanel.setBackground(Color.BLUE);
        this.add(resultsPanel);

        //read in from file
        readFromFile();

        //compute average
        computeAverage();
        System.out.println(avg);
    }

    private void readFromFile() {
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("numbers.dat");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            int i = 0;
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println (strLine);
                intArray[i] = Integer.parseInt(strLine);
                numOfInts++;
                i++;
            }
            //Close the input stream
            in.close();
            System.out.println ("numOfInts = " + numOfInts);
        }
        catch (Exception e) {
            //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
    private void computeAverage() {
        int sum = 0;
        for (int i = 0; i < numOfInts; i++)
        sum += intArray[i];
        avg = sum/numOfInts;
        //return avg;
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == avgBtn) {
            computeAverage();
        }
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.setVisible(true);
    }
}

Your code is a bit messy, there will be more syntax errors if compiled.
You should not mix swing/awt components, for instance: instead of using Label use JLabel in swing, for Panel use JPanel.

Take note of the "J" prefix for swing, you should be reading books perhaps if you want to know more on Java(Swing) or even read some basic tutorials.

Do not use static methods unless you have understand its purpose.

Anyhow here is the closest code of what you want:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main extends JFrame implements ActionListener {
    private int[] intArray = new int[10000];
    private int numOfInts = 0;
    private int avg = 0;

    protected JButton avgBtn;
    protected JTextField indexEntry;
    protected JLabel instructions;
    protected JPanel resultsPanel;

    //constructor - construct the components here and do the initializations
    public Main(){
        //create main frame     
        this.setTitle("Section V, question 2");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(350, 250);
        this.setLayout(new GridLayout(4, 1));
        //this.setVisible(true);

        //create instruction label and add to frame
        instructions = new JLabel("Follow the instructions on the exam to use this program");
        this.add(instructions);

        //create textfield for index entry and add to frame
        indexEntry = new JTextField();
        this.add(indexEntry);

        //create button for average and add to frame
        avgBtn = new JButton("Click for Average");
        this.add(avgBtn);
        avgBtn.addActionListener(this);

        //create panel to display results and add to frame
        resultsPanel = new JPanel();
        resultsPanel.setBackground(Color.BLUE);
        this.add(resultsPanel);

        //read in from file
        readFromFile();

        //compute average
        computeAverage();
        System.out.println(avg);
    }

    private void readFromFile() {
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("numbers.dat");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            int i = 0;
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println (strLine);
                intArray[i] = Integer.parseInt(strLine);
                numOfInts++;
                i++;
            }
            //Close the input stream
            in.close();
            System.out.println ("numOfInts = " + numOfInts);
        }
        catch (Exception e) {
            //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
    private void computeAverage() {
        int sum = 0;
        for (int i = 0; i < numOfInts; i++)
        sum += intArray[i];
        avg = sum/numOfInts;
        //return avg;
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == avgBtn) {
            computeAverage();
        }
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.setVisible(true);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文