如何访问eventlistener类中的变量?

时间:2018-06-19 04:00:21

标签: java scope

我的代码是这样的:

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 []数据”中的内容,以便我可以操作它。 现在,我一直在事件监听器中做所有事情,但我认为这不是很干净。

我希望能够在我的主程序中调用System.out.println(data [0])之类的内容。

1 个答案:

答案 0 :(得分:1)

byte[] data应该是一个实例变量,就像String[] hex一样。另外,不要在函数内定义类。创建类的十六进制和数据私有实例变量,并为它们提供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();
            }
        }
    }
}