私は正常に動作する次のコードを持っていますが、ユーザーがボタンをクリックしたときではなく、ロード時に人の名前を表示したいと考えています。これをどのように実装しますか?
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();
}
}