java estática vs no estático usando esto y controladores de eventos
-
11-09-2019 - |
Pregunta
Estoy tratando de aprender acerca de los controladores de eventos de Java y seguir recibiendo errores de Tipo Tipo métodos (estática / no estáticos) que creo. Algunos código que estoy tratando de escribir el siguiente aspecto:
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();
}
}
}
¿Qué se supone que configurar una interfaz gráfica de usuario leer en algunos enteros desde un archivo y luego calcular su promedio cuando se pulsa un botón. Sin embargo, me siguen dando problemas con la materia estática / no estático y los lanzadores de eventos. Mi error actual son:
Main.java:35: addActionListener (java.awt.event.ActionListener) en javax.swing.AbstractButton no se puede aplicar a (javax.swing.JButton)
avgBtn.addActionListener (avgBtn);
Main.java:91: no se puede encontrar el símbolo
símbolo: avgBtn variables
Localización: Clase principal
si (e.getSource () == avgBtn) {
Yo entiendo que el compilador no puede encontrar avgBtn porque su definido dentro de otra función (Principal ()), pero ¿alguien puede arrojar algo de luz sobre cómo colocar un controlador de eventos a ella? tratado 'esto' en vano también ... Gracias de antemano, y si ves cualquier otra cosa equivocada Me encantaría escuchar cómo puedo hacerlo mejor.
Solución
Su código es un poco desordenado, habrá más errores de sintaxis si se compila. No hay que mezclar los componentes Swing / AWT, por ejemplo:. En lugar de utilizar la etiqueta utilizar JLabel en columpio, Panel de utilizar JPanel
Tome nota del prefijo "J" de oscilación, que debería estar leyendo los libros tal vez si usted quiere saber más sobre Java (Swing) o incluso leer algunos tutoriales básicos.
No utilice los métodos estáticos a menos que tenga comprender su propósito.
De todos modos aquí está el código más cerca de lo que quiere:
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);
}
}