Adaptar código[RESOLVIDO]

3 respostas
gabrielmelo

Salve rapaziada,

Estou com o minha classe pronto e rodando certinho. Que eu leio um arquivo txt com vários nomes delimitados por (";") e armazeno numa lista e a saída que eu mostro em outro arquivo txt. Esta tudo ok.
package br.com.teste;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SorteioTXT {

	public static void main(String []argv) {		
		try {
			//Le o arquivo
			BufferedReader reader = new BufferedReader(new FileReader(new File("/Gabriel/Projetos/sorteio/NOME.txt")));			
			String [] dados;  
			String linha = null;
			int cont = 0;
			int i = 1;
			List<String> lista = new ArrayList<String>();			
			
			//Percorre a o arquivo
			while((linha = reader.readLine()) != null){
				//Armazena cada linha do arquivo no array.
				dados = linha.split(";");			
				lista.add(dados[cont]);
			}
			
			reader.close();
			
			//Embaralha a lista
			Collections.shuffle(lista);
			for(int x = 0; x < lista.size(); x++){
				gravar(i++ + " - " + lista.get(x));
			}			
						
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("Arquivo não encontrado!");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			System.out.println();
			System.out.println("Fim do Arquivo");
		}
	}

	public static void gravar(String texto){
		String conteudo = texto;  
		try{  
			// o true significa q o arquivo será constante  			
			BufferedWriter bw = new BufferedWriter(new FileWriter("arquivoNomes.txt",true));
			
			bw.write(conteudo);
			bw.newLine();
			bw.flush();
			bw.close();
		}  
		// em caso de erro apresenta mensagem abaixo  
		catch(IOException e){  
			System.out.println("Erro na gravação do arquivo");  
		}  
	}
}
So que eu queria adaptar essa minha classe SorteioTXT em uma GUI Swing.
package br.com.teste;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ProgressBarDemo2 extends JPanel
                             implements ActionListener, 
                                        PropertyChangeListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task task;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            Random random = new Random();
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException ignore) {}
                //Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            taskOutput.append("Done!\n");
        }
    }

    public ProgressBarDemo2() {
        super(new BorderLayout());

        //Create the demo's UI.
        startButton = new JButton("Start");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Instances of javax.swing.SwingWorker are not reusuable, so
        //we create new instances as needed.
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
           
      
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName()) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            taskOutput.append(String.format(
                    "Completed %d%% of task.\n", task.getProgress()));
        } 
    }


    /**
     * Create the GUI and show it. As with all GUI code, this must run
     * on the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ProgressBarDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ProgressBarDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Estou com dificuldade de adaptar o meu código na GUI. Por exemplo, ao invés de mostrar o Completed 8% of task da GUI, mostrar cada nome lido no arquivo na saída da GUI e ao mesmo tempo continuar gerando o arquivo txt de saída.

Se alguém poder me ajudar nessa adaptação. Agradeço !!! Está f@#$ não estou conseguindo fazer a adaptação.

[]'s

3 Respostas

gabrielmelo
Está quase saindo. Mas não estou dando conta de imprimir nomes do arquivo txt no JTextArea.
package br.com.teste;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ProgressBarDemo2 extends JPanel
                             implements ActionListener, 
                                        PropertyChangeListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task nome;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            Random random = new Random();
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException ignore) {}
                //Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            taskOutput.append("Finalizado!\n");
        }
    }

    public ProgressBarDemo2() {
        super(new BorderLayout());

        //Create the demo's UI.
        startButton = new JButton("Sortear");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Instances of javax.swing.SwingWorker are not reusuable, so
        //we create new instances as needed.
        
        try {
            //Le o arquivo
            BufferedReader reader = new BufferedReader(new FileReader(new File("/Gabriel/Projetos/sorteio/NOME.txt")));
            String [] dados;
            String linha = null;
            int cont = 0;
            int i = 1;
            List<String> lista = new ArrayList<String>();
            nome = new Task();            

            //Percorre a o arquivo
            while((linha = reader.readLine()) != null){
                //Armazena cada linha do arquivo no array.
                dados = linha.split(";");
                lista.add(dados[cont]);                
            }

            reader.close();
            
			//Embaralha a lista
			Collections.shuffle(lista);
			for(int x = 0; x < lista.size(); x++){
				gravar(i++ + " - " + lista.get(x));
				nome.addPropertyChangeListener(this);
                nome.execute();
			}            

        } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("Arquivo não encontrado!");
        } catch (IOException e) {
                e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println();
            System.out.println("Fim do Arquivo");
        }
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName()) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            taskOutput.append(String.format(
                    "Completed %d%% of task.\n", nome.getProgress()));
        } 
    }


    /**
     * Create the GUI and show it. As with all GUI code, this must run
     * on the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("PGFN - Procuradoria Geral da Fazenda Nacional");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ProgressBarDemo2();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
	public static void gravar(String texto){
		String conteudo = texto;  
		try{  
			// o true significa q o arquivo será constante  			
			BufferedWriter bw = new BufferedWriter(new FileWriter("arquivoNomes.txt",true));
			
			bw.write(conteudo);
			bw.newLine();
			bw.flush();
			bw.close();
		}  
		// em caso de erro apresenta mensagem abaixo  
		catch(IOException e){  
			System.out.println("Erro na gravação do arquivo");  
		}  
	}    
}
gabrielmelo

Salve,

Estou tendo problema no preenchimento do JProgressBar de 0 a 100%. Alguem pode me ajudar ? Obrigado!!!!
package br.com.teste;

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

import br.com.teste.ProgressBarDemo.Task;

import java.beans.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ProgressBarDemo2 extends JPanel implements ActionListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task nome;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            Random random = new Random();
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException ignore) {}
                //Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            taskOutput.append("Finalizado!\n");
        }

		
    }

    public ProgressBarDemo2() {
        super(new BorderLayout());

        //Create the demo's UI.
        startButton = new JButton("Sortear");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Instances of javax.swing.SwingWorker are not reusuable, so
        //we create new instances as needed.
        nome = new Task();
        //nome.addPropertyChangeListener(this);
        nome.execute();
        
        try {
            //Le o arquivo
            BufferedReader reader = new BufferedReader(new FileReader(new File("/Gabriel/Projetos/sorteio/NOME20.txt")));
            String [] dados;
            String linha = null;
            int cont = 0;
            int i = 1;
            List<String> lista = new ArrayList<String>();
            //nome = new Task();
            
            //Percorre a o arquivo
            while((linha = reader.readLine()) != null){
                //Armazena cada linha do arquivo no array.
                dados = linha.split(";");
                lista.add(dados[cont]);                
            }

            reader.close();
            
			//Embaralha a lista
			Collections.shuffle(lista);
			for(int x = 0; x < lista.size(); x++){
				gravar(i++ + " - " + lista.get(x));
				progressBar.setValue(x);
				taskOutput.append(String.format(
						i++ + " - " + lista.get(x)+"\n", nome.getProgress()));

				 
			}            

        } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("Arquivo não encontrado!");
        } catch (IOException e) {
                e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println();
            System.out.println("Fim do Arquivo");
        }
    }

    /**
     * Create the GUI and show it. As with all GUI code, this must run
     * on the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("PGFN - Procuradoria Geral da Fazenda Nacional");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ProgressBarDemo2();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
	public static void gravar(String texto){
		String conteudo = texto;  
		try{  
			// o true significa q o arquivo será constante  			
			BufferedWriter bw = new BufferedWriter(new FileWriter("arquivoNomes.txt",true));
			
			bw.write(conteudo);
			bw.newLine();
			bw.flush();
			bw.close();
		}  
		// em caso de erro apresenta mensagem abaixo  
		catch(IOException e){  
			System.out.println("Erro na gravação do arquivo");  
		}  
	}    
}
gabrielmelo
Aí galera, consegui resolver, quebrei cabeça até consegui !
package br.com.teste;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ProgressBarDemo2 extends JPanel implements ActionListener, PropertyChangeListener {

    /**
	 * 
	 */
	private static final long serialVersionUID = -5034553172745647622L;
	private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task nome;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            Random random = new Random();
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1));
                } catch (InterruptedException ignore) {}
                //Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            taskOutput.append("Finalizado!\n");
        }		
    }

    public ProgressBarDemo2() {
        super(new BorderLayout());

        //Create the demo's UI.
        startButton = new JButton("Sortear");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Instances of javax.swing.SwingWorker are not reusuable, so
        //we create new instances as needed.
        nome = new Task();
        nome.addPropertyChangeListener(this);
        nome.execute();
        
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName()) {
        
	        try {
	            //Le o arquivo
	        	BufferedReader reader = new BufferedReader(new FileReader(new File("/NOME300.txt")));
	            String [] dados;
	            String linha = null;
	            int cont = 0;
	            int i = 1;
	            int y = 1;
	            List<String> lista = new ArrayList<String>();
	            String nomeConcat = "";
	            
	            //Percorre a o arquivo
	            while((linha = reader.readLine()) != null){
	                //Armazena cada linha do arquivo no array.
	                dados = linha.split(";");
	                lista.add(dados[cont]);                
	            }
	
	            reader.close();
	            
				//Embaralha a lista
				Collections.shuffle(lista);			
				for(int x = 0; x < lista.size(); x++){
					gravar(i++ + " - " + lista.get(x));
					nomeConcat += y++ + " - " + lista.get(x) + "\n";
				}
				
				int progress = (Integer) evt.getNewValue();
	            progressBar.setValue(progress);
	            taskOutput.append(String.format(nomeConcat, nome.getProgress()));			
	
	        } catch (FileNotFoundException e) {
	        	e.printStackTrace();
	            System.out.println("Arquivo não encontrado!");
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (NullPointerException e) {
	            System.out.println();
	            System.out.println("Fim do Arquivo");
	        }        
        }        
    }


    /**
     * Create the GUI and show it. As with all GUI code, this must run
     * on the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("PGFN - Procuradoria Geral da Fazenda Nacional");
        frame.setIconImage(new ImageIcon("/Gabriel/Projetos/sorteio/img/Logotipo_PGFN2.jpg").getImage());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ProgressBarDemo2();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
	public static void gravar(String texto){
		String conteudo = texto;  
		try{  
			// o true significa q o arquivo será constante  			
			BufferedWriter bw = new BufferedWriter(new FileWriter("/arquivo_Nomes_Sorteados.txt",true));
			
			bw.write(conteudo);
			bw.newLine();
			bw.flush();
			bw.close();
		}  
		// em caso de erro apresenta mensagem abaixo  
		catch(IOException e){  
			System.out.println("Erro na gravação do arquivo");  
		}  
	}    
}
Criado 3 de setembro de 2010
Ultima resposta 6 de set. de 2010
Respostas 3
Participantes 1