我想找到答案,但我不能。在java中,当我创建一个子类时,我如何才能获得第一级类?使用"这个"访问子类,所以我不能。另一个选择是将参数传递给子类,但我很好奇是否有最简单的方法。
//here there is my other 1st level class implementation, this is a JFrame
btnNewProject.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
VehicleScreen pp=new VehicleScreen(**here should go the top class reference**);
//v is a JPanel that I pass to allJframes
v.setContentPane(pp);
v.setVisible(true);
}
});
答案 0 :(得分:2)
class Foo {
int x;
Foo() {
new Runnable() {
public void run() {
Foo.this.x = 1;
}
}
}
}
答案 1 :(得分:2)
您有几个选择:
使匿名类之外的变量成为实例变量:
public class AnonymousClass extends JFrame {
private JLabel label;
...
public AnonymousClass() {
...
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(textField.getText());
}
});
...
}
您还可以按如下方式访问实例变量:
AnonymousClass.this.label.setText(textField.getText());
在局部变量上使用final
修饰符:
public class AnonymousClass extends JFrame {
...
public AnonymousClass() {
final JLabel label = new JLabel("Enter a new message!");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(textField.getText());
}
});
...
}
请注意使用final
modifier will mean you cannot re-assign the variable at a later point in your program.