package SwingPacket;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class FrameChoseFile extends JFrame {
//JFrame frame=new JFrame();
JPanel jpane=new JPanel();
JLabel label1=new JLabel();
JLabel label2=new JLabel();
JTextField text1=new JTextField();
JTextField text2=new JTextField();
JButton button1=new JButton();
JButton button2=new JButton();
BorderLayout layout=new BorderLayout();
FlowLayout flow1=new FlowLayout();
public FrameChoseFile(){
init();
}
public void init(){
//frame.getContentPane().add(jpane);
//this.setLayout(layout);
//frame.setLayout(layout);
label1.setText("打开文件");
label1.setToolTipText("");
label2.setText("保存文件");
text1.setPreferredSize(new Dimension(204,22));
text2.setPreferredSize(new Dimension(204,22));
button1.setText("...");
button1.setToolTipText("打开");
button2.setText("...");
jpane.setPreferredSize(new Dimension(339,138));
//this.getContentPane().add(jpane,BorderLayout.CENTER);
this.setLayout(layout);
this.getContentPane().add(jpane,BorderLayout.CENTER);
//this.setLayout(layout);
//getContentPane().setLayout(layout);
jpane.setLayout(flow1);
jpane.add(label1);
jpane.add(text1);
jpane.add(button1);
jpane.add(label2);
jpane.add(text2);
jpane.add(button2);
this.setTitle("文件选择器(JFileChooser)");
//jpane.setLayout(flow1);
button1.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
openFile();
}
});
button2.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
saveFile();
}
});
}
public void openFile(){
JFileChooser fc=new JFileChooser();
fc.setDialogTitle("选择文件演示");
fc.setDialogType(JFileChooser.CUSTOM_DIALOG);
if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
this.text1.setText(fc.getSelectedFile().toString());
this.text2.setText(fc.getSelectedFile().toString());
}
}
public void saveFile(){
JFileChooser fc=new JFileChooser();
fc.setDialogTitle("保存文件演示");
fc.setDialogType(JFileChooser.SAVE_DIALOG);
File f1=new File(text1.getText());
fc.setCurrentDirectory(f1);
fc.setSelectedFile(f1);
if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FrameChoseFile f=new FrameChoseFile();
f.pack();
f.setVisible(true);
}
}
JAVA Dialog 文件打开和保存程序
最新推荐文章于 2021-04-15 15:48:28 发布