이 이벤트 핸들러를 사용하는 Java STATIC vs Non-Static을 사용합니다
-
11-09-2019 - |
문제
Java의 이벤트 처리기에 대해 배우려고 노력하고 있으며 유형 유형 (static/non-static) 메소드로 오류가 계속됩니다. 내가 쓰려고하는 일부 코드는 다음과 같습니다.
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();
}
}
}
파일에서 일부 INT로 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) {
컴파일러는 다른 함수 (main ()) 내에 정의되어 있기 때문에 AVGBTN을 찾을 수 없다는 것을 이해하지만, 이벤트 핸들러를 첨부하는 방법에 대해 누군가를 밝힐 수 있습니까? '이것'도 아무 소용이 없도록 시도했습니다 ... 미리 감사드립니다. 그리고 다른 잘못된 것을 본다면 어떻게 더 나아질 수 있는지 듣고 싶습니다.
해결책
코드는 약간 지저분합니다. 컴파일 된 경우 더 많은 구문 오류가 발생합니다. 예를 들어 스윙/AWT 구성 요소를 혼합해서는 안됩니다.
스윙을위한 "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);
}
}