JFileChooser com erro!

3 respostas
ErielMiquilino

Olá

Então gente tenho um problema aqui...

Estou tentando pegar o diretório de um arquivo .txt e escrever em um JTextField.setEditable(false); apenas para mostrar onde esta o arquivo que ele selecionou...
o meu JFileChooser esta permitindo a seleção de vários arquivos de uma vez, e cada arquivo eu vou jogar em um JTextField diferente. (vou limitá-lo a até 6 arquivos mais ainda não fiz isso).

private JFileChooser chooser;
	private File files[] =  {null, null, null, null, null, null};
	
	
	private JButton getBtnSelect(){
		if(btnSelect == null){
			btnSelect = new JButton("Selecionar Arquivos");
			btnSelect.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnSelect.setFocusable(false);
					chooser = new JFileChooser();
					chooser.setMultiSelectionEnabled(true);
					chooser.setFileFilter(new FileNameExtensionFilter("*.txt", "txt")); 
					chooser.setAcceptAllFileFilterUsed(false);
					int returnValue = chooser.showOpenDialog(null);
					if(returnValue ==  JFileChooser.APPROVE_OPTION){
						files= chooser.getSelectedFiles();
						
						if(files[0].exists() ){
							getTxtFileOne().setText(files[0].getPath());
						}else{
							getTxtFileOne().setText(null);
						}
						
						if(files[1].exists() ){
							getTxtFileTwo().setText(files[1].getPath());
						}else{
							getTxtFileTwo().setText(null);
						}
						
						if(files[2].exists() ){
							getTxtFileThree().setText(files[2].getPath());
						}else{
							getTxtFileThree().setText(null);
						}
						
						if(files[3].exists() ){
							getTxtFileFour().setText(files[3].getPath());
						}else{
							getTxtFileFour().setText(null);
						}
						
						if(files[4].exists() ){
							getTxtFileFive().setText(files[4].getPath());
						}else{
							getTxtFileFive().setText(null);
						}
						
						if(files[5].exists() ){
							getTxtFileSix().setText(files[5].getPath());
						}else{
							getTxtFileSix().setText(null);
						}
					}else{
						JOptionPane.showMessageDialog(null, "Operação cancelada pelo usuário!");
					}
				}
			});
			
			
			btnSelect.setBounds(157,42,172,33);
		}
		
		return btnSelect;
	}

quando seleciono os 6 ele não da nenhum erro, o problema esta quando seleciono 1 só ou 2... (menos que 6)

ai ele me da esse erro aqui:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
	at br.com.thread.gui.MainFrame$1.actionPerformed(MainFrame.java:70)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$500(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

Oque estou fazendo de errado?
Desde já, agradeço a ajuda de todos!
Valeu!

3 Respostas

ViniGodoy

Se um arquivo só estiver selecionado, não haverá valores em files[1], files[2], files[3], etc... por isso, não tem como testar por exists(). O ideal é usar um for (até para corrigir essa repetição toda aí):

//Cria um array com todos os textFields
JTextField txtFields[] = {
     getTxtFileOne(), getTxtFileTwo(), getTxtFileThree(), 
     getTxtFileFour(), getTxtFileFive(), getTxtFileSix()
};

//Itera sobre os arquivos selecionados
for (int i = 0; i < files.length; i++) {
     if(files[i].exists() ){  
          txtFields[i].setText(files[i].getPath());  
     }else{  
          txtFields[i].setText(null);  
     }  
}
ErielMiquilino

Beleza! Entendi aqui… Muito Obrigado!

ErielMiquilino

Agora quando tento salvar a data de modificação que é do tipo Long do arquivo em um outro vetor (para que eu possa ordenar) da erro

public class ThreadDate implements Runnable {
	private File files[];
	private Long datas[];
	
	
	public File[] getFiles() {
		return files;
	}


	public void setFiles(File[] files) {
		this.files = files;
	}


	public void run() {		
		for(int i = 0; i< files.length; i++){
			datas[i] = files[i].lastModified(); 	//aqui esta o problema! linha 25	
		}

		for(int i = 0; i < files.length ; i++){
			DateFormat formatData = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss");
			System.out.println(formatData.format(datas[i]));
			
		}
	}
	public ThreadDate(){
	}
}

ele não funciona da este erro:

Exception in thread "Thread-3" java.lang.NullPointerException
	at br.com.thread.run.ThreadDate.run(ThreadDate.java:25)
	at java.lang.Thread.run(Unknown Source)

e esse é o meu Botão onde inicio o método:

private JButton getBtnStart(){
		if(btnStart == null){
			btnStart = new JButton("Iniciar Threads");
			btnStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					if(files.length < 2){
						JOptionPane.showInputDialog("Selecione pelo menos dois arquivos para fazer a comparação");
					}else{
					
					ThreadDate tDate = new ThreadDate();
					tDate.setFiles(files);
					Thread startThreadDate = new Thread(tDate);
					startThreadDate.start();
					}
					
				}
			});
			btnStart.setFocusable(false);
			btnStart.setBounds(157,316,172,33);
		}
		return btnStart;
	}

ahh antes que perguntem estou usando uma Thread por que tem outro método que ira ordenar por tamanho do arquivo e os dois devem rodar "simultaneamente"

Criado 30 de novembro de 2015
Ultima resposta 4 de dez. de 2015
Respostas 3
Participantes 2