我有以下代码可以正常工作,但我希望在加载时显示人名,而不是在用户单击按钮时显示。我将如何实现这一点?
public class NameSwing implements ActionListener {
private JTextArea tf = new JTextArea(20, 20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
static String fullName;
public NameSwing() {
f.add(new JLabel("Name"));
tf.setEditable(true);
f.add(tf);
b.addActionListener(this);
f.add(b);
f.setLayout(new FlowLayout());
f.setSize(600, 600);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
tf.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
Names t = new Names();
t.OpenFile();
t.ReadFile();
t.CloseFile();
fullName = Names.fullName;
}
}
Names
班级:
package names;
public class Names {
Scanner scan;
static String Firstname = null;
static String Surname;
static String Fullname;
static String fullName;
String myArray[];
public void OpenFile() {
try {
scan = new Scanner(new File("/Users/nikhilpatel/NetBeansProjects/Names/src/names/test.txt"));
System.out.println("File found!");
} catch (Exception e) {
System.out.println("File not found");
}
}
public void ReadFile() {
while (scan.hasNext()) {
Firstname = scan.next();
Surname = scan.next();
Fullname += Firstname + " " + Surname + "\n";
fullName = Fullname.replace("null", "");
System.out.println(fullName);
}
}
public void CloseFile() {
scan.close();
}
}