21.文件打开、关闭对话框
效果:

点击“打开文件...”:

选择一个文件打开:

点“取消”:

点击“保存文件...”:

选择一个文件保存:

选择“取消”:
package com.lvshitech.gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JFileChooserDemo extends JFrame {
public JFileChooserDemo() {
super("使用JFileChooser");
// 操作结果展示文本框
final JTextArea ta = new JTextArea(5, 20);
ta.setMargin(new Insets(5, 5, 5, 5));
ta.setEditable(false);
JScrollPane sp = new JScrollPane(ta); // 带滚动条
final JFileChooser fc = new JFileChooser(); // 文件选择器
// 打开按钮
JButton openButton = new JButton("打开文件...");
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(JFileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) { // JFileChooser.APPROVE_OPTION = 0
File file = fc.getSelectedFile();
ta.append("打开:" + file.getName() + "\n");
} else {
ta.append("取消打开命令。\n");
}
}
});
// 保存按钮
JButton saveButton = new JButton("保存文件...");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showSaveDialog(JFileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
ta.append("保存:" + file.getName() + "\n");
} else {
ta.append("取消保存命令。\n");
}
}
});
// 按钮标签
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
// 点击Tab键的时候在这两个按钮之间切换选中
openButton.setNextFocusableComponent(saveButton);
saveButton.setNextFocusableComponent(openButton);
// 添加到容器
Container container = getContentPane();
container.add(buttonPanel, BorderLayout.NORTH);
container.add(sp, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new JFileChooserDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

浙公网安备 33010602011771号