/*** 

PicRenamer / ExtChange is a little application to change the extensions of files in a specific folder.
The source code is free to use and modify.

fabian taubald ( fabian - at - fabiantaubald.de )

***/

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

class PicRenamer extends JFrame implements ActionListener {

	JButton execute;
	JButton choose;
	JLabel desc_path, desc_ending;
	JTextField path, ending;

	public void rename(File file, String ending) {

		String filename = file.getAbsolutePath();
		int nameLength  = file.getAbsolutePath().length();

			for (int i = nameLength; i > 1; i--) {

				if (filename.substring(i - 1, i).equals(".")) {

					File newFile = new File(filename.substring(0, i - 1) + "." + ending);
					
						try {

							file.renameTo(newFile);
						}

						catch (Exception e) {

							System.out.println(e.getMessage());
						}

					break;					
				}
			}
	}

	public PicRenamer(String title) {

		super (title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(null);
		setSize(300, 200);
		setResizable(false);

		desc_path = new JLabel("Alle Dateiendungen des Ordners");
		desc_path.setSize(250, 20);
		desc_path.setLocation(5, 5);
		add(desc_path);

		path = new JTextField();
		path.setSize(290, 20);
		path.setLocation(5, 30);
		add(path);

		choose = new JButton("Durchsuchen");
		choose.setSize(130, 25);
		choose.setLocation(85, 55);
		choose.addActionListener(this);
		add(choose);
		
		execute = new JButton("Ausführen");
		execute.setSize(130, 25);
		execute.setLocation(85, 140);
		execute.setEnabled(false);
		execute.addActionListener(this);
		add(execute);

		desc_ending = new JLabel("ändern in *.");
		desc_ending.setSize(100, 20);
		desc_ending.setLocation(5, 100);
		add(desc_ending);

		ending = new JTextField();
		ending.setSize(50, 20);
		ending.setLocation(95, 100);
		add(ending);

		setVisible(true);
	} 

	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == choose) {

			execute.setText("Ausführen");
			JFileChooser fc = new JFileChooser();
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int r = fc.showOpenDialog(PicRenamer.this);
			
				if (r == 0) {

					path.setText(fc.getSelectedFile().getAbsolutePath());
					execute.setEnabled(true);
				}
		}

		if (e.getSource() == execute) {

			File folder = new File(path.getText());

			if (folder.exists() && folder.isDirectory()) {

				File[] picList = folder.listFiles();

					for (int i = 0; i < picList.length; i++) {

						rename(picList[i], ending.getText());
					}

				execute.setText("Fertig");
				execute.setEnabled(false);
			}

			else {

				System.out.println("Fehler bei Ordnerangabe");
			}
		}
	}

	public static void main(String[] args) {

		PicRenamer p = new PicRenamer("Dateiendungen ändern");
	}
}

