gpt4 book ai didi

java - 奇怪的 Swing 编译时可访问性错误

转载 作者:行者123 更新时间:2023-12-03 21:27:09 26 4
gpt4 key购买 nike

这是代码-

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public final class SetLabelForDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JLabeledButton("foo:")); // new JLabeledButton("foo:") is the problem
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

private final class JLabeledButton extends JButton{
public JLabeledButton(final String s){
super();
JLabel label = new JLabel(s);
label.setLabelFor(this);
}
}
}

这是错误信息-

No enclosing instance of type SetLabelForDemo is accessible. Must qualify the allocation with an enclosing instance of type SetLabelForDemo (e.g. x.new A() where x is an instance of SetLabelForDemo).

我完全不明白这个错误。对我来说,一切似乎都是完全正确的。我错过了什么吗?

最佳答案

您必须将您的类 JLabeledButton 声明为静态的,因为您是在静态上下文中实例化它的:

private static final class JLabeledButton extends JButton {
...
}

因为您的方法 createAndShowGUI 是静态的,所以编译器不知道您正在为哪个 SetLabelForDemo 实例创建封闭类。

关于java - 奇怪的 Swing 编译时可访问性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600455/

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