Java 如何访问eventlistener类中的变量?

Java 如何访问eventlistener类中的变量?,java,scope,Java,Scope,我的代码是这样的: public class Application { public static void main(String[] args) { class openFileListener implements ActionListener { public String[] hex; public void actionPerformed(ActionEvent event) {

我的代码是这样的:

public class Application {


    public static void main(String[] args) {


        class openFileListener implements ActionListener {

            public String[] hex;

            public void actionPerformed(ActionEvent event) {


            try {
                // Read byte data of .bmp file
                byte[] data = Files.readAllBytes(pathname);

            } catch(IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    } //end of class

    openFileListener listener = new openFileListener();
    openButton.addActionListener(listener);



    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }
}
现在,我想访问byte[]数据中的内容,以便对其进行操作。 现在,我已经在事件侦听器中完成了所有工作,但我认为这不是很干净

我希望能够在main中调用类似System.out.printlndata[0]的函数。

字节[]数据应该是一个实例变量,就像字符串[]十六进制一样。另外,不要在函数中定义类。创建类的十六进制和数据私有实例变量,并为它们提供getter。另外,readAllBytes接受一个java.nio.file.Path类型的变量,您可能正在传入一个字符串

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Application {

    private static final int FRAME_WIDTH = 200;
    private static final int FRAME_HEIGHT = 200;
    private static String pathName = "...";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            JButton openButton = new JButton();
            frame.getContentPane().add(openButton);
            OpenFileListener openFileListener = new OpenFileListener();
            openButton.addActionListener(openFileListener);

            frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }

    static class OpenFileListener implements ActionListener {

        private String[] hex;
        private byte[] data;

        public String[] getHex() {
            return hex;
        }

        public byte[] getData() {
            return data;
        }

        public void actionPerformed(ActionEvent event) {
            try {
                data = Files.readAllBytes(Paths.get(pathName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用模型,它可以连接代码的不同方面。但是要理解,由于代码的设置方式,在调用ActionListener之前,数据是不相关的。大多数GUI都是事件驱动的,这意味着事情不会按顺序发生