[size=16]Olá pessoal, este é o meu 1º Post, desculpem se houver erro.[/size]
Estou criando uma aplicação e não sei escrever, nem alimentar um objeto em aberto por uma JFrame, não importa como seja o objeto(JTable,JLabel,…), preciso da ajuda de vocês, ja pesquisei e não encontrei nada que me faça entender, acho que herança ou coisas assim podem me ajudar a entender melhor.
A aplicação trabalha para monitorar um diretório.
Simplesmente ele carrega os arquivos existentes no diretório selecionado, tenho então a opção de clicar em um botão e o mesmo iniciar uma Thread para monitorar tudo oque é criado ou modificado, alimentando 2(JTables) na interface aberta, porem não sei fazer isso, enviar informações para uma janela já aberta.
Vou agradecer qualquer informação que ajude-me a compreender melhor como isso funciona e como fazer corretamente uso deste tipo de rotina.
Segue meus códigos da JFrame e da Thread.
Nas classes a seguir, não existe nenhuma ação para exibir na interface somente no System.out (assim eu sei que ta funcionando a thread, mas queria que o resultado fosse exibido na janela.
OBS: Uso do Eclipse, códigos todos digitados por mim, sem criação automática(talvez este seja o erro,rssss).
Abraço a todos e valew.
Class da Interface
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class JPMonitora extends JPanel{
private JFileChooser fc = null;
private Icon imgAbrir = new ImageIcon("imagens/dir.png");
private String sDirectory;
private boolean bIsFile = false;
private JButton btDiretorio,btMstartpause,btMstop;
private JLabel labelDiretorio;
private JLabel labelTopo;
private JTextField txDiretorio;
private JTable tbExiste,tbNovo,tbModificado;
private DefaultTableModel tbmExiste,tbmNovo,tbmModificado;
private HashSet<String> lista = new HashSet<String>();
private HashMap<String,String> pacote = new HashMap<String,String>();
private MonFiles moni ;
private Thread exec;
private int flag = 0;
public JPMonitora(){
/*
* Configuração da janela
*/
setLayout(null);
setBackground(new Color(222,222,222));
// Criando os componentes da janela
// Globais
btDiretorio = new JButton(imgAbrir);
btMstartpause = new JButton("Começar");
btMstop = new JButton("Finalizar");
tbmExiste = new DefaultTableModel();
tbmNovo = new DefaultTableModel();
tbmModificado = new DefaultTableModel();
tbExiste = new JTable(tbmExiste);
tbNovo = new JTable(tbmNovo);
tbModificado = new JTable(tbmModificado);
labelDiretorio = new JLabel("Selecione o diretório");
labelTopo = new JLabel("Monitoramento de Arquivos no Diretório");
txDiretorio = new JTextField(50);
moni = new rotinas.monitoramento.MonFiles();
exec = new Thread(moni);
//Locais
JScrollPane scExiste = new JScrollPane(tbExiste);
JScrollPane scNovo = new JScrollPane(tbNovo);
JScrollPane scModificado= new JScrollPane(tbModificado);
//Configuracao dos componentes
tbExiste .enable(false);
tbmExiste .addColumn("Arquivo Existente");
tbmExiste .addColumn("EXT");
tbmNovo .addColumn("Novo");
tbmNovo .addColumn("TP");
tbmModificado .addColumn("Midificado");
tbmModificado .addColumn("TP");
btDiretorio .setOpaque(true);
btDiretorio .setBackground(new Color(255,255,255));
btMstartpause .setOpaque(true);
btMstartpause .setBackground(new Color(255,255,255));
btMstartpause .setEnabled(false);
btMstop .setOpaque(true);
btMstop .setBackground(new Color(255,255,255));
btMstop .setEnabled(false);
txDiretorio .setEditable(false);
txDiretorio .setOpaque(true);
txDiretorio .setBackground(new Color(255,255,255));
txDiretorio .setFont(new Font(null,Font.ITALIC,10));
labelDiretorio .setForeground(Color.gray);
labelTopo .setForeground(Color.DARK_GRAY);
labelTopo .setFont(new Font(null,Font.BOLD+Font.ITALIC,18));
// redimencionando colunas
TableColumn colExist0 = tbExiste.getColumnModel().getColumn(0);
TableColumn colExist1 = tbExiste.getColumnModel().getColumn(1);
TableColumn colNovo0 = tbNovo.getColumnModel().getColumn(0);
TableColumn colNovo1 = tbNovo.getColumnModel().getColumn(1);
TableColumn colModif0 = tbModificado.getColumnModel().getColumn(0);
TableColumn colModif1 = tbModificado.getColumnModel().getColumn(1);
colExist0 .setPreferredWidth(280);
colExist1 .setPreferredWidth(10);
colNovo0 .setPreferredWidth(170);
colNovo1 .setPreferredWidth(10);
colModif0 .setPreferredWidth(170);
colModif1 .setPreferredWidth(10);
//Posicionando dos componentes
btDiretorio .setBounds(1, 60, 35, 30);
btMstartpause .setBounds(247, 60, 90, 30);
btMstop .setBounds(337, 60, 85, 30);
labelTopo .setBounds(40, 15, 423, 20);
labelDiretorio .setBounds(37, 60, 200, 15);
txDiretorio .setBounds(37, 75, 170, 15);
scExiste .setBounds(0, 90, 423, 165);
scNovo .setBounds(0, 255, 211, 242);
scModificado .setBounds(211, 255, 211, 242);
//Acao dos componentes
btDiretorio.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
carregaArquivoExiste();
}
});
btMstartpause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(flag==0){
btMstop .setEnabled(true);
flag = 1;
btMstartpause .setText("Pausar");
exec.start();
//valida();
//iniciar acao
}else if(flag==1){
btMstartpause .setText("Continuar");
exec.suspend();
flag=2;
//continuar acao
}else if(flag==2){
btMstartpause .setText("Pausar");
exec.resume();
flag=1;
//valida();
}else if(flag==3){
btMstop .setEnabled(true);
btMstartpause .setText("Pausar");
exec.suspend();
exec.resume();
flag=1;
}
}
});
btMstop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(flag==1 || flag == 2){
btMstartpause .setText("Começar");
btMstop .setEnabled(false);
exec.suspend();
moni.mata();
flag=3;
System.out.println("Finalizado");
//zerar monitoramento
}
}
});
//Adicionando ao painel
add(labelTopo);
add(labelDiretorio);
add(btDiretorio);
add(btMstartpause);
add(btMstop);
add(txDiretorio);
add(scExiste);
add(scNovo);
add(scModificado);
}
private void carregaArquivoExiste(){
if(fc == null)
{
fc = new JFileChooser();
//define o diretorio de abertura
File defaultstart = new File("C:\");
if(defaultstart.exists())
{fc.setCurrentDirectory(new File("C:\"));}
}
else
{
fc.setCurrentDirectory(new File(getFilePath()));
}
// define somente diretorio para ser selecionado
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int fileState = fc.showOpenDialog(null);
// -------------------------------
File dirSelecionado = fc.getSelectedFile();
if(dirSelecionado != null && fileState == JFileChooser.APPROVE_OPTION)
{setFilePath(dirSelecionado.getAbsolutePath());}
else if(fileState == JFileChooser.CANCEL_OPTION)
{bIsFile = false;}
if(bIsFile){
btMstartpause.setEnabled(true);
if(dirSelecionado.isDirectory()){
if(dirSelecionado.getParent() == null){
}else{
System.out.println(getFilePath()); }
loadLista();
};
txDiretorio.setText(getFilePath());
}}
private String getFilePath() {
//retorna os diretorio
return sDirectory;
}
private boolean isFilePath() {
//retorna se existir alguma selecao de diretorio
return bIsFile;
}
private void setFilePath(String fpath) {
//insere diretorio e valida a existencia
sDirectory = fpath;
bIsFile = true;
}
private void loadLista(){
int cls = 0;
File dir = new File(getFilePath());
File arquivos[] = dir.listFiles();
HashSet listArquivo = new HashSet<String>(arquivos.hashCode());
// remove todas as linhas da tbmExiste
while(tbmExiste.getRowCount()!=0){
tbmExiste.removeRow(cls);}
// adiciona as novas linhas da tbmExiste
JFileChooser choo = new JFileChooser();
for(int i = 0;i<arquivos.length;i++){
if(arquivos[i].isFile()){
tbmExiste.addRow(new Object[]{arquivos[i].getName(),choo.getTypeDescription(arquivos[i])});
pacote.put(arquivos[i].getName(),""+arquivos[i].length());
}
}
}
public boolean validaArquivo(String file){
if(pacote.containsKey(file)){
return true;
}else{
tbmNovo.addRow(new Object[]{file});
return false;
}
}
public boolean validaModificado(String file){
if( pacote.get(file) == file){
return true;
}else{
tbmModificado.addRow(new Object[]{file});
return false;
}
}
public void setNovoArquivo(String f){
tbmNovo.addRow(new Object[]{f});
}
public String getNovoArquivo(){
return getFilePath();
}
public static void main(String args[]){
JFrame tela = new JFrame();
tela.setSize(433, 600);
tela.add(new JPMonitora());
tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tela.setVisible(true);
}
}
Class Thread: Por enquanto só escrevendo no System.out
public class MonFiles extends Thread {
int contador = 0;
Thread rodando;
Temp vago = new Temp();
public void run() {
pegaDir();
while(true){
System.out.println("Contato : "+contador);
vago.setLabel("Contato : "+contador);
try{
contador+=1;
Thread.sleep(500);
}catch(Exception erro){
System.out.println("erro :"+erro.getMessage());
return;
}
}
}
public void mata(){
contador = 0;
}
public void pegaDir(){
}
}