Duvida em como chamar classe atraves de um botao

2 respostas
L

Caros colegas…sou novo no Forum e no Java e necessito a ajuda de voces…
estou desenvolvendo um programinha que tem 4 classes socket do tipo cliente/servidor.
é uma classe servidor que fica escutando e quando executo a classe cliente abre uma janela de bate papo, tipo messenger…a outra classe servidor tambem fica escutando e quando executo o cliente ele copia um arquivo do caminha que indiquei pra onde indiquei no servidor…quando executo estas classes individualmente no netbeans funcionan perfeitamente…acontece que criei um NewJApplet com botoes para chamar as referidas classes, mas nao consigo que funcione, ja olhei varios exemplos e forums mas nao acerto…vcs podem me ajudar?

ja tentei com todas estas opcoes abaixo e nao consigo fazer com que a janela da classe cliente se abra.

Runtime.getRuntime().exec(“java clienteCall.java”);

Runtime.getRuntime().exec(“java Cliente”);


ClienteCAll();

new ClienteCall().show();


ClienteCall C = new ClienteCall();
C.start();

ClienteCall Cliente = new ClienteCall();
Cliente.setVisible(true);

ClienteCall C = new ClienteCall();
C.show();

ClienteCall C = new  ClienteCall();

C.setVisible(true);

C.start();

C.show();

2 Respostas

samuray13

Já tentou criar os objetos na inicialização do aplicativo ?

Pelo que entendi você quer fazer alguma coisa do tipo :
Dois clientes se comunicarem um envia uma mensagem e outro recebe , seria isso ?

L

Ola…obrigado por responder…Sim e isso mesmo, mas a troca de mensagem ja funciona…o que nao consigo é fazer com que um botao de NewjApplet chame a clase ClienteCall, a classe serverChat consigo ativarla com:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

new chatserver();

}

coloco abaixo as classes para possa me entender:

SERVERCHAT.JAVA

import java.awt.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import <a href="http://java.io">java.io</a>.<em>;

import java.util.</em>;
public class chatserver extends Thread

{

int DEFAULT_PORT=4321;

protected int port;

protected ServerSocket server_port;

protected ThreadGroup CurrentConnections;

protected Vector connections;

protected ServerWriter writer;

private Calendar datatual;
//Crear un ServerSocket

public chatserver()

{

super(Server);

this.port=DEFAULT_PORT;

try

{

server_port=new ServerSocket(port);

}

catch (IOException e)

{

System.err.println(e+Exception);

}

//Crea un threadgroup para las conexiones

CurrentConnections=new ThreadGroup(Server Connections);
//Mensaje inicial en la ventana del servidor
System.out.println("=== &#65533;&#65533;&#65533; Conexiones Realizadas &#65533;&#65533;&#65533; ===");

//Un vetor para almacenar las conexiones
connections=new Vector();
writer=new ServerWriter(this);

//Inicia el servidor para oir las conexiones
this.start();

}

public void run()

{

try

{

while(true)

{

datatual = Calendar.getInstance();

Socket cliente_socket=server_port.accept();

//Exibe en la ventana del servidor los clientes que se conectan (mostra

//el host del cliente, el puerto y la fecha y hora de la conexion

System.out.println(Host:+cliente_socket.getInetAddress()+“� Porta:+

cliente_socket.getPort()+"� "+datatual.getTime());

Connection c=new Connection(cliente_socket,CurrentConnections,3,writer);

//evita el acceso simultaneo

synchronized(connections)

{

//adiciona esta nueva conexion a la lista

connections.addElement©;

}

}

}

catch(IOException e)

{

System.err.println(e+Exception);

}

}
//Inicia el servidor

public static void main(String[] args)

{

new chatserver();

}

}

//----------------------------------------------------------------------------

class Connection extends Thread

{

static int numberOfConnections=0;

protected Socket client;

protected DataInputStream in;

protected PrintStream out;

protected ServerWriter writer;
public Connection(Socket cliente_socket, ThreadGroup CurrentConnections,

int priority, ServerWriter writer)

{

super(CurrentConnections,Connection number+numberOfConnections++);

//define la prioridad

this.setPriority(priority);

client=cliente_socket;

this.writer=writer;

try

{

//Atarraxa los streams a los streams de entrada y salida del socket del

//cliente y adiciona este outputstream al vetor que contiene todos

//los streams de salida, usados por el escritor writer

in=new DataInputStream(client.getInputStream());

out=new PrintStream(client.getOutputStream());

writer.OutputStreams.addElement(out);

}

catch(IOException e)

{

try

{

client.close();

}

catch (IOException e2)

{

System.err.println(Exception while getting socket streams:+e);

return;

}

}

//dispara Thread

this.start();

}
//El metodo run hace un lazo leyendo los mensajes recebidos

public void run()

{

String inline;

//Envia un mensaje de bienvenidao al cliente

out.println(Bienvenido al MiniChat…”);

try

{

while(true)

{

//le una linea del mensaje

inline=in.readLine();

//La conexion es interrumpida si null

if (inline==null)

break;

//Pone la linea en el escritor writer

writer.setOutdata(inline);

synchronized(writer)

{

//llama el escritor synchronized() para evitar que dos lineas

//Connection o llamen a la vez. Esta es una forma de “bloqueo”.

writer.notify();

}

}

}

catch(IOException e)

{}

finally

{

try

{

client.close();

}

catch(IOException e2)

{}

}

}

}

//----------------------------------------------------------------------------

class ServerWriter extends Thread

{

protected chatserver server;

public Vector OutputStreams;

public String outdata;

private String outputline;
public ServerWriter(chatserver s)

{

super(s.CurrentConnections,“Server Writer”);

server=s;

OutputStreams=new Vector();

this.start();

}
public void setOutdata(String mensagem)

{

outdata=mensagem;

}

public synchronized void run()
{
while(true)
{
//La linea hace un lazo para siempre, pero la vedad solo es ejecutada
//cuando la condicion wait for reinicializada por un notify. Eso en un
//bloque sincronizado para bloquear la linea y evitar el acceso multiplo.
try
{
this.wait();
}
catch (InterruptedException e)
{
System.out.println(“Caught an Interrupted Exception”);
}
outputline=outdata;
synchronized(server.connections)
{
for (int i=0 ; i<OutputStreams.size() ; i++)
{
//Es impreso el mensaje en cada OutputStreams.
PrintStream out;
out=(PrintStream)OutputStreams.elementAt(i);
out.println(outputline);
}
}
}
}
}

CLIENTECALL.JAVA

import <a href="http://java.io">java.io</a>.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import java.awt.<em>;

import java.applet.</em>;
public class ClienteCall extends Applet

{

public static final int DEFAULT_PORT=4321;

public Socket clisoc;

private Thread reader;

public TextArea OutputArea;

public TextField InputArea, nomefield;

public PrintStream out;

public String Name;
//Crea las lineas de lectura y escritura y las inicia.

public void init()

{

OutputArea=new TextArea(20,45);

InputArea=new TextField(45);

nomefield=new TextField(10);
//Tela da Applet
add(new Label("                  Chat usando conexion (Socket TCP)" ));
add(new Label("Nombre del usuario"));
add(nomefield);
add(OutputArea);
add(new Label("Teclee el Mensaje y presione ENTER"));
add(InputArea);
resize(350,490);
try
{
  //Crea un socket cliente pasando la direccion y el puerto del servidor
  clisoc=new Socket("127.0.0.1",DEFAULT_PORT);
  reader=new Reader(this, OutputArea);
  out=new PrintStream(clisoc.getOutputStream());
  //Define prioridades desiguales para que la consola sea compartida
  //de forma efectiva.
  reader.setPriority(3);
  reader.start();
}
catch(IOException e)
{
  System.err.println(e);
}

}

public boolean handleEvent(Event evt)

{

if (evt.target==InputArea)

{

char c=(char)evt.key;

if (c==\n)

//Vigila si el usuario presiona la tecla ENTER.

//Eso permite saber si el mensaje esta listo para ser enviado!

{

String InLine=InputArea.getText();

Name=nomefield.getText();

out.println(Name+">"+InLine);

InputArea.setText("");

//Envia el mensaje, pero añade el nombre del usuario al mensaje para que

//los otros clientes sepan quien a envio.

return true;

}

}

return false;

}

}

//----------------------------------------------------------------------------

//La clase Reader le la entrada del socket y actualiza la OutputArea con los

//nuevos mensajes.

class Reader extends Thread

{

protected ClienteCall cliente;

private TextArea OutputArea;

public Reader(ClienteCall c, TextArea OutputArea)

{

super(chatclient Reader);

this.cliente=c;

this.OutputArea=OutputArea;

}

public void run()
{
DataInputStream in=null;
String line;
try
{
in=new DataInputStream(cliente.clisoc.getInputStream());
while(true)
{
line=in.readLine();
//Añade un nuevo mensaje a la OutputArea
OutputArea.appendText(line+"\r\n");
}
}
catch(IOException e)
{
System.out.println(“Reader:”+e);
}
}
}

NEWAPPLET.JAVA

public class NewJApplet extends javax.swing.JApplet {

/** Initializes the applet NewJApplet */
public void init() {
    resize(455,380);
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                initComponents();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/** This method is called from within the init() method to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JSeparator();
    jSeparator2 = new javax.swing.JSeparator();
    jSeparator3 = new javax.swing.JSeparator();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jButton5 = new javax.swing.JButton();

    setBackground(new java.awt.Color(204, 204, 204));

    jButton1.setText("Activar Server Chat");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Activar Cliente Chat");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jButton3.setText("Activar Cliente Transfer");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.setText("Activar Server TransferChat");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jLabel1.setFont(new java.awt.Font("Bookman Old Style", 3, 14));
    jLabel1.setText("Mensajería");

    jLabel2.setFont(new java.awt.Font("Bookman Old Style", 3, 14));
    jLabel2.setText("Transferencia Ficheros");

    jLabel3.setFont(new java.awt.Font("Serif", 3, 18));
    jLabel3.setText("Práctica de Ingeníeria de Protocolos de Comunicación");

    jLabel4.setFont(new java.awt.Font("Serif", 3, 18));
    jLabel4.setText("2007/2008");

    jLabel5.setFont(new java.awt.Font("Arial", 0, 14));
    jLabel5.setText("Leandro C. Fumega");

    jLabel6.setFont(new java.awt.Font("Serif", 3, 18));
    jLabel6.setText("Facultad de Informática - UPM");

    jButton5.setText("Finalizar Aplicación");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addGap(181, 181, 181)
            .addComponent(jLabel1)
            .addContainerGap(177, Short.MAX_VALUE))
        .addGroup(layout.createSequentialGroup()
            .addGap(36, 36, 36)
            .addComponent(jButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 110, Short.MAX_VALUE)
            .addComponent(jButton2)
            .addGap(38, 38, 38))
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(131, Short.MAX_VALUE)
            .addComponent(jLabel2)
            .addGap(134, 134, 134))
        .addGroup(layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addComponent(jButton4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 81, Short.MAX_VALUE)
            .addComponent(jButton3)
            .addGap(24, 24, 24))
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addGap(98, 98, 98)
            .addComponent(jLabel6)
            .addContainerGap(102, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel3)
            .addGap(20, 20, 20))
        .addGroup(layout.createSequentialGroup()
            .addGap(177, 177, 177)
            .addComponent(jLabel4)
            .addContainerGap(186, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(313, Short.MAX_VALUE)
            .addComponent(jLabel5))
        .addGroup(layout.createSequentialGroup()
            .addGap(183, 183, 183)
            .addComponent(jButton5)
            .addContainerGap(136, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel6)
            .addGap(8, 8, 8)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGap(18, 18, 18)
            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jLabel2)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton4)
                .addComponent(jButton3))
            .addGap(18, 18, 18)
            .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton5)
            .addGap(11, 11, 11)
            .addComponent(jLabel5))
    );
}// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {

System.exit(0);

// TODO add your handling code here:

}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

new chatserver();

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

AQUI QUERO CHAMARA CLASSE CLIENTE E QUE SE ABRA O SEU APPLET
AQUI QUERO CHAMARA CLASSE CLIENTE E QUE SE ABRA O SEU APPLET
AQUI QUERO CHAMARA CLASSE CLIENTE E QUE SE ABRA O SEU APPLET
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
// End of variables declaration

}

Criado 20 de junho de 2008
Ultima resposta 21 de jun. de 2008
Respostas 2
Participantes 2