在JAVA中如何獲取文本框中輸入的值,并保存在一個文件之中。具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import java.io.*; import javax.swing.*; import java.awt.FlowLayout; import java.awt.event.*; public class WriterTo extends JFrame implements ActionListener{ JButton b;JTextField t; public WriterTo(){ super ( "文本框內容寫入文件" ); JLabel l= new JLabel( "請輸入內容:" ); t= new JTextField( 20 ); b= new JButton( "寫入" ); b.addActionListener( this ); this .add(l); this .add(t); this .add(b); this .setLayout( new FlowLayout()); this .pack(); this .setVisible( true ); } public void actionPerformed(ActionEvent e) { if (e.getSource()==b){ if (t.getText().equals( "" )){ JOptionPane.showMessageDialog( null , "請輸入內容~" , "錯誤" ,JOptionPane.ERROR_MESSAGE); t.grabFocus(); } else { write(t.getText()); JOptionPane.showMessageDialog( null , "寫入成功" , "提示" ,JOptionPane.INFORMATION_MESSAGE); } } } public void write(String line){ try { File f= new File( "C:\\Users\\Administrator\\Desktop\\java\\就是這里.txt" ); //向指定文本框內寫入 FileWriter fw= new FileWriter(f); fw.write(line); fw.close(); } catch (Exception e){ } } public static void main(String[] args) { new WriterTo(); } } |
關于向指定文本框內寫入,這一點需要注意一下。
總結
以上是本實例的全部代碼,希望對大家有所幫助。
原文鏈接:https://zhidao.baidu.com/question/197676958.html?qbl=relate_question_3&word=java%D6%D0%BB%F1%C8%A1%CE%C4%B1%BE%BF%F2%B5%C4%D6%B5