PapaiLu
Janeiro 17, 2019, 12:29am
#1
Olá. Estou trabalhando num Jogo da Forca e me deparei com algo BASTANTE complexo pra mim. Carregar um JCombobox com os NOMES DOS ARQUIVOS que estão em uma pasta.
P.Ex.: c:\Livros
Informatica.txt
Animais Domésticos.txt
Utilidades do Lar.txt
Times de Futebol.txt
Ferramentas.txt
O meu JCombobox: jComboCategorias
Infelizmente não tenho qualquer código ou sequer idéias para esta Função.
Obrigado por qualquer ajuda.
File f = new File("C:\\Livros");
//-- Lista de arquivos .java...
File[] files = f.listFiles (new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
});
for (int i = 0; i < files.length; ++i) {
System.out.println (files[i]);
}
Você já sabe adicionar itens no comboBox, agora no for vc coloca, suaCombo.addItem(files[i]);
1 curtida
PapaiLu
Janeiro 17, 2019, 11:49am
#3
Hei Abner.
Super obrigado pela resposta tão breve.
Ocorre um erro na hora de adicionar no combo.
Diz que File não pode ser convertido para String.
Não to conseguindo converter para por no combo.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.FileFilter;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Exemplo extends JFrame {
public static void main(String[] args) throws Exception {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Exemplo programinha = new Exemplo();
programinha.setDefaultCloseOperation(EXIT_ON_CLOSE);
programinha.setLocationRelativeTo(null);
programinha.setVisible(true);
} catch (Throwable t) {
t.printStackTrace();
}
}
private final File pasta;
private final FileFilter filtro;
Exemplo() {
super("Meu Programinha");
pasta = new File("C:\\Livros");
filtro = arquivo -> aceitarArquivo(arquivo, ".txt");
String tipo = ".txt";
ComboBoxModel<String> comboBoxModel = new ComboBoxModelArquivos();
JComboBox<String> comboBox = new JComboBox<>(comboBoxModel);
comboBox.addItemListener(event -> selecionouArquivo(event));
comboBox.setPreferredSize(new Dimension(100, 30));
JPanel container = new JPanel(new BorderLayout());
container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setContentPane(container);
container.add(comboBox, BorderLayout.NORTH);
setMinimumSize(new Dimension(640, 480));
}
private class ComboBoxModelArquivos extends DefaultComboBoxModel<String> {
@Override
public int getSize() {
File[] arquivos = getArquivos();
return arquivos.length;
}
@Override
public String getElementAt(int posicao) {
File[] arquivos = getArquivos();
return nomeSemExtensao(arquivos[posicao]);
}
}
private boolean aceitarArquivo(File arquivo, String tipo) {
if (arquivo.getName().toLowerCase().endsWith(tipo)) {
return true;
}
return false;
}
private File[] getArquivos() {
return pasta.listFiles(filtro);
}
private void selecionouArquivo(ItemEvent event) {
if (event.getStateChange() == ItemEvent.DESELECTED) {
return;
}
JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
int posicao = comboBox.getSelectedIndex();
File[] arquivos = getArquivos();
File arquivo = arquivos[posicao];
JOptionPane.showMessageDialog(null, "Arquivo selecionado:\n" + arquivo.getAbsolutePath(), "Mensagem", JOptionPane.INFORMATION_MESSAGE);
}
private String nomeSemExtensao(File arquivo) {
String nome = arquivo.getName();
int extensao = nome.lastIndexOf('.');
if (extensao > 0) {
return nome.substring(0, extensao);
}
return nome;
}
}
1 curtida
PapaiLu
Janeiro 17, 2019, 1:25pm
#5
Hei staroski,
Me perdoe. Não consegui entender…
PapaiLu:
Não consegui entender
Estude como utilizar ComboBoxModel.
PapaiLu
Janeiro 18, 2019, 3:15pm
#7
Alguém pode dar ajuda?
Ainda não consegui fazer.
Boa tarde amigo. Se for isso que precisa, segue:
public static void main(String[] args) {
Test t = new Test();
t.getFilesName("C:/Users/usuario/Desktop/pastaArquivos", new JComboBox());
}
public void getFilesName(String path, JComboBox combo) {
try {
combo.removeAllItems();
File file = new File(path);
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("txt");
}
});
for (File f : files){
String name = f.getName();
int end = name.lastIndexOf(".") != -1 ? name.lastIndexOf(".") : name.length();
combo.addItem(name.substring(0, end));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Boa sorte a todos.
1 curtida
PapaiLu
Janeiro 18, 2019, 5:43pm
#9
Resolvi.
Achei onde faz a inclusão dos itens no combo e removi a parte não necessária.
Te amo Villa. kkkkkkkkkkk
Muito obrigado viu. Deus abençoe vcs.