📄 filechooserdemo.java
字号:
package chapter14;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Filechooserdemo implements ActionListener{
JFrame f=null;
JLabel label=null;
JTextArea textarea=null;
JFileChooser filechooser=null;
public Filechooserdemo(){
f=new JFrame("filechooser example");
textarea=new JTextArea();
JScrollPane scrollpane=new JScrollPane(textarea);
JPanel panel=new JPanel();
JButton button1=new JButton("new");
button1.addActionListener(this);
JButton button2=new JButton("save");
button2.addActionListener(this);
panel.add(button1);
panel.add(button2);
label=new JLabel();
filechooser=new JFileChooser("E://");
Container contentpane=f.getContentPane();
contentpane.add(label,BorderLayout.NORTH);
contentpane.add(scrollpane,BorderLayout.CENTER);
contentpane.add(panel,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args) {
new Filechooserdemo();
}
public void actionPerformed(ActionEvent e){
File file=null;
int result;
if(e.getActionCommand().equals("new")){
filechooser.setApproveButtonText("ok");
filechooser.setDialogTitle("open new file");
result=filechooser.showOpenDialog(f);
textarea.setText("");
if(result==filechooser.APPROVE_OPTION){
file=filechooser.getSelectedFile();
label.setText("the file you chooser is:"+file.getName());
}
else if(result==filechooser.CANCEL_OPTION){
label.setText("you don not chooser file");
}
FileInputStream fileinput=null;
if(file!=null){
try {
fileinput=new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
int readbyte;
try {
while((readbyte=fileinput.read())!=-1){
textarea.append(String.valueOf((char)readbyte));
}
} catch (IOException e1) {
e1.printStackTrace();
} finally{
try {
fileinput.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
if(e.getActionCommand().equals("save")){
result=filechooser.showSaveDialog(f);
file=null;
String filenane;
if(result==filechooser.APPROVE_OPTION){
file=filechooser.getSelectedFile();
label.setText("the file name you save is"+file.getName());
}
else if(result==filechooser.CANCEL_OPTION){
label.setText("yon don not have saved any file");
}
OutputStreamWriter fileoutput=null;
try {
fileoutput=new OutputStreamWriter(new FileOutputStream(file));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String content=textarea.getText();//这个与textpane中得document.gettext()中得参数不一样得。
try {
fileoutput.write(String.valueOf(content.getBytes()));
} catch (IOException e1) {
e1.printStackTrace();
}
finally{
try {
fileoutput.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -