使用this和事件处理程序的java静态与非静态
我试图学习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,从文件中读取一些int,然后在按下按钮时计算它们的平均值。然而,我总是遇到静态/非静态的东西和事件处理程序的问题。我当前的错误是:
主要的java:35:javax中的addActionListener(java.awt.event.ActionListener)。摆动AbstractButton无法应用于(javax.swing.JButton)
avgBtn。addActionListener(avgBtn)
梅因。java:91:找不到符号
符号:变量avgBtn
位置:主类
如果(e.getSource()==avgBtn){
我知道编译器找不到avgBtn,因为它是在另一个函数(Main())中定义的,但是有人能解释一下如何将事件处理程序附加到它吗?试过“这个”也没用。。。提前谢谢你,如果你觉得还有什么不对劲的话,我很想听听我如何能让它变得更好
# 1 楼答案
你的代码有点乱,如果编译的话会有更多的语法错误。 您不应该混合使用swing/awt组件,例如:不要在swing中使用Label use JLabel,而要在Panel中使用JPanel
请注意swing的前缀“J”,如果您想了解更多关于Java(swing)的知识,甚至想阅读一些基本教程,您应该阅读一些书籍
除非您了解静态方法的用途,否则不要使用静态方法强>
无论如何,这里是你想要的最接近的代码: