您好我无法将JTextField的值写入另一个类中的ArrayList,错误是“...字符串无法转换为Object”我该如何解决? 这是arraylist类
public class MemberList
{
private ArrayList < Member> members;
/**
* Create a Member.
*/
public MemberList()
{
members = new ArrayList < Member>();
}
/**
* Add a member to this member list.
* @param member the member to be added
*/
public void addMember(Member member)
{
members.add(member);
}
}
和GUI
public class Test extends JFrame implements ActionListener {
private JTextField jtFName, jtLName, jtMemberNo;
private int nextMemNo;
private MemberList members;
private JFrame frame;
@Override
public void actionPerformed(ActionEvent evt) {
members = new MemberList();
if (evt.getActionCommand().equals("Add Member")) {
if (jtLName.getText().equals("") && (jtFName.getText().equals(""))) {
jtMember.setText("No names");
} else if (jtFName.getText().equals("")) {
jtMember.setText("No first name");
} else if (jtLName.getText().equals("")) {
jtMember.setText("No last name");
} else if (!jtLName.getText().equals("") && (!jtFName.getText().equals(""))) {
btnOne.setText("Confirm");
String fName = jtFName.getText();
String memNo = "1";
String lName = jtLName.getText();
members.addMember(member);
}
} else if (evt.getActionCommand().equals("No. of Members")) {
btnTwo.setText("Clear Number");
jlbMember.setVisible(true);
} else if (evt.getActionCommand().equals("Clear Number")) {
jtFName.setText("");
jtLName.setText("");
} else if (evt.getActionCommand().equals("Quit")) {
System.exit(0);
}
}
}
在ArrayList中添加jtFName需要做什么? 抱歉编辑错误,谢谢
答案 0 :(得分:0)
您必须创建Member类的新实例并将其传递给addMember方法。例如
Member member = new Member(fName, lName); //replace with your actual constructor logic
members.addMember(member);
答案 1 :(得分:0)
您的列表members
包含Member
类型的对象,而不是String
类型
要么你的List包含String,就像:
members = new ArrayList<String>();
或者为Member
类创建一个构造函数,在该类中将String传递给对象,并将新的Object添加到List中:
public class Member{
private String name;
public Member(String name){ //create constructor with String argument
this.name = name;
}
}
members.addMember(new Member(name)) //add new Member to list
我看不到你的会员类,但是当我查看你的代码时,我认为它有一个fName,lName和memNo。所以在你的程序中构造函数看起来像:
public class Member{
private String fName;
private String lName;
private String memNo;
public Member(String fNamen, String lName, String memNo){ //create constructor with String arguments
this.fName= fName;
this.lName= lName;
this.memNo= memNo;
}
}
并将其添加到列表中,如:
members.addMember(new Member(fName, lName, memNo));