我试图从文本字段中读取一个名称,然后将其传递给将其归入数组的类。我试图将这个类传递给电话簿,但我正在尝试添加GUI。但是,当我尝试将变量从jframe传递给原始类时,程序崩溃了。这是原始的相关部分和我试图传递的框架 的 MainPhonebook
import java.io.*;
import java.util.*;
public class Phonebook {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception {
int i;
char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
readPhoneBook("PhoneBook1.txt");
System.out.println("Codes are entered as 1 to 8 characters.\nUse"
+ " \"e\" for enter," + " \"f\" for find,"
+ " \"l\" for listing all the entries," + " \"q\" to quit.");
Command = null;
C = ' ';
while (C != 'q') {
System.out.print("Command: ");
Command = stdin.next();
C = Command.charAt(0);
switch (C) {
case 'e':
addContact();
break;
case 'f':
code = stdin.next();
stdin.nextLine();
i = index(code);
if (i >= 0)
displayContact(contactList[i]);
else
System.out.println("**No entry with code " + code);
break;
case 'l':
sortList();
listAllContacts();
break;
case 's':
sortList();
break;
case 'q':
CopyPhoneBookToFile("PhoneBook1.txt");
System.out
.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt");
break;
default:
System.out
.println("Invalid command Please enter the command again!!!");
}
}
}
public static void addContact() {
String name = stdin.next();
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].name = name;
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number;
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine();
num_entries++;
}
public static void name(String name){
contactList[num_entries] = new Entry();
contactList[num_entries].name = name;
}
帧
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Name extends JFrame implements ActionListener
{
private JButton Next;
static TextField Name = new TextField(10);
public Name()
{
super("Add New Contact");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
add(new JLabel("Add Contacts Name"));
Next = new JButton("Next");
add(Name);
add(Next);
Next.addActionListener(this);
Next.setActionCommand("Open");
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
String name =Name.getText();
Phonebook.name(name);
String cmd = e.getActionCommand();
if(cmd.equals("Open"))
{
dispose();
new Number();
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run()
{
new Name().setVisible(true);
}
});
}
}
感谢您的帮助!