解答例 - 実習課題3 - 17.選択コンポーネント
(実習課題3)
実習課題2のプログラムを改良しなさい。
- 拡張子が「java」のファイル以外は表示しないフィルタを追加する事。
解答例
/**
* ChooseOnlyJavaFileFrame.java
* TECHSCORE Javaユーザインタフェース17章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.ui.chapter17.exercise3;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class ChooseOnlyJavaFileFrame extends JFrame implements ActionListener {
private JButton openButton;
public ChooseOnlyJavaFileFrame() {
super("ChooseOnlyJavaFileFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(300, 200));
openButton = new JButton("choose");
openButton.addActionListener(this);
getContentPane().add(openButton);
}
private class OnlyJavaFilter extends FileFilter {
public boolean accept(java.io.File f) {
// ディレクトリなら表示
if (f.isDirectory()) {
return true;
}
// ファイルなら拡張子がjavaのものだけを表示
String fileName = f.getName();
int extIndex = fileName.lastIndexOf(".");
if (extIndex >= 0) {
if (fileName.substring(extIndex).equals(".java")) {
return true;
}
}
return false;
}
public String getDescription() {
return "Java File(*.java)";
}
}
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new OnlyJavaFilter());
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(
this,
fileChooser.getSelectedFile().getPath(),
"FILE PATH",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "You don't choose a file.", "WARNING", JOptionPane.WARNING_MESSAGE);
}
}
public static void main(String[] args) {
new ChooseOnlyJavaFileFrame().setVisible(true);
}
}

