我有这些类及其嵌套类(请转到相关行):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client {
private static final int FRAME_WIDTH = 500, FRAME_HEIGHT = 500;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ClientPanel());
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
}
@SuppressWarnings("serial")
private static class ClientPanel extends JPanel {
JTextArea textArea;
JTextField textField;
JButton goButton;
private ClientPanel() {
setLayout(new BorderLayout());
textArea = new JTextArea();
add(textArea, BorderLayout.NORTH);
textField = new JTextField();
add(textField, BorderLayout.CENTER);
goButton = new JButton("Go");
add(goButton, BorderLayout.PAGE_END);
goButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.append("Go button pressed. Text in field: "
+ textField.getText() + "\n ");
}
});
}
private static class GetBinaryThread extends Thread {
private String data;
public GetBinaryThread(String data) {
this.data = data;
}
public void run() {
try {
ClientPanel.this.textArea.append(", recieved" + data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
编译器在线上给我一个错误:
ClientPanel.this.textArea.append(", recieved" + data);
在范围
中无法访问类型为Client.ClientPanel
的封闭实例
我如何能够访问外部类的JTextArea?
答案 0 :(得分:4)
您的嵌套类是 static 嵌套类:
private static class GetBinaryThread extends Thread
因此它没有封闭的实例。
摆脱static
然后它将成为内部类,并引用ClientPanel
的实例。请注意,当您创建GetBinaryThread
的实例时(您已经显示的代码中没有),您需要ClientPanel
引用隐式传递给构造函数作为上下文。