I'm trying to debug an issue with some code given to me by my professor. Ultimately I need to take the input from the text field in the LoginPanel
and reference this later on as the username
.
Here is my code:
import java.awt.*;
import java.awt.event.*;
public class MyCardFrame extends Frame{
LoginPanel lp;
ChatPanel cp;
public MyCardFrame(){
setLayout(new CardLayout());
setTitle("Chat");
setSize(500,500);
lp = new LoginPanel(this);
cp = new ChatPanel();
add(lp, "login");
add(cp, "chat");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setVisible(true);
}
public static void main(String[] args){
MyCardFrame mcf = new MyCardFrame();
}
}
class LoginPanel extends Panel implements ActionListener{
TextField tf;
MyCardFrame mcf;
public LoginPanel(MyCardFrame mcf){
this.mcf = mcf;
tf = new TextField(20);
tf.addActionListener(this);
add(tf);
}
public void actionPerformed(ActionEvent ae){
//using setName instead of setUserName *********
mcf.cp.setUserName(tf.getText()); //call setUserName of chatpanel which is a member of mycardframe
CardLayout cl = (CardLayout)(mcf.getLayout());
cl.next(mcf);
tf.setText("");
}
}
class ChatPanel extends Panel{
Label label1,label2;
String userName;
public ChatPanel(){
label1 = new Label("Chat Panel: ");
label2 = new Label("Name will go here");
add(label1);
add(label2);
}
public void setUserName(String userName){
this.userName = userName;
label2.setText(getUserName());
}
public String getUserName(){
return userName;
}
}
After this runs I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError:
finalproject.ChatPanel.setUserName(Ljava/lang/String;)V
This is coming from the line:
mcf.cp.setUserName(tf.getText());
From what I can tell I have correctly called setUserName
, and while the IDE provides no errors, on run it fails.
Also to clarify: Yes I know nobody uses AWT, but its required for this class and we are not permitted to use Swing.
答案 0 :(得分:1)
NoSuchMethodError
意味着非常具体的东西。它说当代码被编译时,类和方法被成功定位,但是当代码被执行时,即使加载了类,它也不包含所请求的方法。
这几乎总是意味着编译期间使用的jar文件的版本与运行时提供的版本不同。运行时版本缺少该方法,或签名不同,无法找到匹配方法。
来自NoSuchMethodError
的Javadoc:
如果应用程序试图调用类的指定方法(静态或实例),并且该类不再具有该方法的定义,则抛出该异能。
通常,编译器会捕获此错误;如果类的定义发生不兼容的更改,则此错误只能在运行时发生。
解决方案是仔细检查在编译和运行时都有相同的jar文件。