Adicionar textos Jtextarea sem abrir nova instância

4 respostas
binhole

Alguém pode me ajudar, tenho um método em uma classe de interface gráfica “Prompt” com um Jtextarea e preciso acumular textos no mesmo de acordo com as informações que chegam do servidor, através de uma outra classe chamada “NewCliente” eu passo os textos chamando o método da classe “Prompt”, o problema é que toda vez que é chamado abre uma nova instância do Frame, eu apenas quero ir adicionado os textos conforme interação do usuário… segue as Classes.

Prompt

package IGrafica_Services;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JTextArea;
import java.awt.Rectangle;
import javax.swing.JTextField;
import java.awt.SystemColor;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JLabel;

import conexao.prototipo.NewCliente;

public class Prompt extends MonitorPress {

	private static final long serialVersionUID = 1L;
	NewCliente ObjCliente = new NewCliente();  //  @jve:decl-index=0:
	private JFrame jFrame = null;  
	private JPanel jContentPane = null;
	private JTextArea jTextArea = null;
	Dimension t = Toolkit.getDefaultToolkit().getScreenSize();  //  @jve:decl-index=0:
	private JTextField Comando = null;
	private JLabel jLabel = null;
	private JLabel conectado = null;
	private String line;  //  @jve:decl-index=0:
	private void JFrame() {
			jFrame = new JFrame();
			jFrame.setSize(new Dimension(415, 466));
			jFrame.setTitle("Prompt Remoto");
			jFrame.setResizable(false);
			jFrame.setContentPane(getJContentPane());
					
	}

	
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			conectado = new JLabel();
			conectado.setBounds(new Rectangle(1, 37, 409, 17));
			conectado.setText("");
			jLabel = new JLabel();
			jLabel.setBounds(new Rectangle(151, 4, 103, 22));
			jLabel.setText("Prompt Remoto");
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setBackground(new Color(147, 169, 189));
			jContentPane.add(getJTextArea(), null);
			jContentPane.add(getComando(), null);
			jContentPane.add(jLabel, null);
			jContentPane.add(conectado, null);
					
		}
		return jContentPane;
	}
	
	public Prompt(){
		JFrame();
		jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		jFrame.setVisible(true);
		jFrame.setLocation((t.width - 415)/2 , (t.height - 466)/2);
		conectado.setText("Conectado : " + super.Ip + " , " + super.porta );			
	}

	private JTextArea getJTextArea() {
		if (jTextArea == null) {
			jTextArea = new JTextArea();
			jTextArea.setBounds(new Rectangle(1, 59, 405, 342));
			jTextArea.setEnabled(false);
			jTextArea.setBackground(SystemColor.controlText);
			jTextArea.setForeground(SystemColor.window);
			jTextArea.setEditable(false);
		}
		return jTextArea;
	}
	

	private JTextField getComando() {
		if (Comando == null) {
			Comando = new JTextField();
			Comando.setBounds(new Rectangle(1, 401, 407, 30));
			Comando.setBackground(SystemColor.info);
			Comando.addKeyListener(new java.awt.event.KeyListener() {
				public void keyReleased(java.awt.event.KeyEvent e) {
					int code = e.getKeyCode();
					if(code == KeyEvent.VK_ENTER){
						
						ProcessoEnviar();	
						
					}
										
				}
				public void keyTyped(java.awt.event.KeyEvent e) {
				}
				public void keyPressed(java.awt.event.KeyEvent e) {
				}
			});
		}
		return Comando;
	}
	String g = "";  //  @jve:decl-index=0:
public void EditText(String line2){
	
	g = line2 + g;
	if(line2.length() > 69){
	  jTextArea.append(g + " \n" );	
	}
	else{
	  jTextArea.append(g);
		
	}
	
		
		line = null;
	}

	
	public void ProcessoEnviar(){
		new Thread(){
			public void run(){
			
				ObjCliente.ExecutarConexao(Comando.getText());	
				Comando.setText("");
								
			}
				}.start();
			}
	

}

New Cliente

package conexao.prototipo;

import java.net.*;  
import java.util.ArrayList;
import java.io.*;  

import javax.swing.JOptionPane;

import IGrafica_Services.Prompt;

 
public class NewCliente extends Thread {  
 

private static final long serialVersionUID = 1L;
public  int portaServer;
public  String ipServer;
public  String mensagem;
public  Socket socket=null;  
public static  PrintStream saida;  
public  BufferedReader entrada;
public String mens;
public String lord[] = new String[6];
public static boolean done = false;
private int statusping;
private String[] Dname;
private String[] Kname;
private int cont;
private String lin;



public NewCliente(Socket s){
	socket = s;
}

   public NewCliente() {
	// TODO Auto-generated constructor stub
}
         

 public void Client(String host,int port){  
	      
	    ipServer = host;  
	    portaServer = port;         
	  
	   }  
public void execClient() throws IOException{  
		conectarServer();  
		
	                             
	    }//fim execClient  

public void conectarServer() throws UnknownHostException, IOException {  
	    
	         		
       socket = new Socket(ipServer,portaServer);
	    
 try{
		
	    ObterFluxo();
	
   
	}
				
	 catch (Exception e) {
		JOptionPane.showMessageDialog(null,"Erro ao estabelecer fluxo de entrada de comunicação","erro de fluxo",JOptionPane.ERROR_MESSAGE);
		e.printStackTrace();
	}
		   	
		  
	Thread r = new NewCliente(socket);
	r.start();
}
 



public void run(){
	 
	 try{
		 entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		 
		 
		  while(true){
			  		 
			 //verifica se  linha de entrada é válida 
			 	  
	            String line = entrada.readLine();
	            if(line!= null){
 			 
	      			 Prompt o = new Prompt();
	      			   
	      			//System.out.println(line);
	      			o.EditText(line);
	      			  
	      			  line = null;
	      			  	      			   			    			 
	      		  }
	 }
		  }
	 
    catch(Exception e){  
     System.out.println("Algum problema ocorreu ao enviar dados pelo socket. " + e);
    }
	       
    done = true;
	 }


  public void ObterFluxo()  {  
      
	  try {			  
		  entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  		  saida   =  new PrintStream(socket.getOutputStream());	  
	  }          
             					
		 catch (IOException e1) {
			JOptionPane.showMessageDialog(null,"Não foi possível criar os fluxos de Entrada e  saida de dados","Erro ao estabelecer Fluxo",JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}
		 
	   
}
  public void ExecutarConexao(String n){
	  
	  this.mens = n;
	  Envia();
	 }   
 
		public void Envia(){
		 			
		try{
	 	                  	 
   		  saida.println(mens);
   		     		    		  
   		  mens = null;
   		    		
         }                 
         catch(Exception e){  
         System.out.println("Algum problema ocorreu ao enviar dados pelo socket. " + saida);
        
        
        try {
			conectarServer();
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(null,"Erro grave ocasionado ao se Conectar","Erro na Conexão",JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}
		
		
         }
         
		}
             
    public void fechaConexao(){  
              
           
           try {
			entrada.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}             
			saida.close();  
           try {
        	   socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
		try {
			socket.shutdownOutput();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*Janela muda = new Janela();     
              
		String texto = "A conexão foi cancelada pelo usuario"; 
								
		muda.getAtexto();
		
		muda.setAtexto(texto);*/
				
		JOptionPane.showMessageDialog(null,"Desconectado do ip "+socket.getInetAddress(),"Desconectado pelo Usuário",JOptionPane.INFORMATION_MESSAGE);
		
   }
    
    public void CapturaStatus() throws IOException{
    	    	   	   	
    	 try{
    		 
    		 entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		 		 
    		// pega a quantidade de serviços
    	    	
    		  String linha = entrada.readLine(); 
    	    	
    	    	cont = Integer.parseInt(linha);
    	    	
    	    	System.out.println(cont);
    	    	
    	    	linha = null;
    	    	
    	    	// Pega o Nome do Serviço (DisplayName)
    	   /*	
    	    	for(int i = 0; i<cont; i++){
    	    		   		
    	    		linha = entrada.readLine(); 
    	    		
    	    		if(linha!= null){
    	    					
    	    			//Dname[i] = linha; 			  
    	    			
    	    			System.out.println(linha);
    	    			
    	    	     }
    	    	}
    	    
    		  while(true){
    			  		 
    			 			 
    			 //verifica se  linha de entrada é válida 
    			 
    			 		            
    	            String line = entrada.readLine();
    	     		  
    	      		 if(line!= null){
    	      			  
    	      			  JOptionPane.showMessageDialog(null,line,"Processo de Execução",JOptionPane.INFORMATION_MESSAGE);
    	      			 
    	      			  line = null;
    	      			  	      			   			    			 
    	      		  }
    	 }}*/
    	 }catch(Exception e){  
    	            JOptionPane.showMessageDialog(null,"Algum problema ocorreu ao receber dados pelo socket. " + e);
    	 }
    	 
    }
    	       
   // Retorna Array de Display Nome
    
	public ArrayList<String> getdname() {
		
		ArrayList<String> displayname = new ArrayList<String>(); 
		
		for(int i = 0;i<=cont;i++){
		
	displayname.add(Dname[i]);
		
	}
		return displayname ;
	}
	
	// Retorna Array de KeyName Nome
	
public ArrayList<String> getkname() {
		
		ArrayList<String> Keyname = new ArrayList<String>(); 
		
		for(int i = 0;i<=cont;i++){
		
		Keyname.add(Kname[i]);
		
	}
		return Keyname ;
	}
    
	
	// testa se o ip infomado é Válido
	 
		public int pinga(String ip){
		
		Process p;
	    try {
			p = Runtime.getRuntime().exec("ping -n 1 "+ ip);
			statusping = p.waitFor(); 
				   
		}catch(Exception e){
		
		
		}
		return statusping;
		
	}
    	
		
		
		
public static void main(String[] args) throws IOException {
	
	NewCliente o = new NewCliente();
	
	o.Client("127.0.0.1",7000);
	o.execClient();
	o.ExecutarConexao("prompt");
	o.ExecutarConexao("dir c:\\teste2");
	o.ExecutarConexao("exit");
		
  }
}

4 Respostas

marcosharbs

passe seu frame como parametro para a outra classe
assim vc pode acessar os atributos do frame sem abrir uma nova instancia

binhole

Desculpe a minha ignorância cara, mas como assim? extendendo a classe prompt? e usar os atributos diretamente…? ou não? tem como me da um exemplo de como implemento neste codigo? obrigado

binhole

alguém pode me ajudar?

binhole

alguém pode me ajudar?

Criado 25 de fevereiro de 2009
Ultima resposta 25 de fev. de 2009
Respostas 4
Participantes 2