gpt4 book ai didi

java - 如何访问事件监听器类中的变量?

转载 作者:行者123 更新时间:2023-12-02 11:06:31 26 4
gpt4 key购买 nike

我的代码是这样的:

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

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

最佳答案

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

关于java - 如何访问事件监听器类中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com