2

I have an Applet code like below. I have a String called String randomNumberStr in this Applet to display a random number, which has retrieved from a socket server. After Applet window is displayed, I have a button called "Connect". Clicking on this button will connect with Socket program and gets a Random Number string.

My issue is, I am running socket connection code in a separate thread SocketConnectionThread in this Applet, But, String randomNumberStr and repaint function are there in main thread.

How can i access and pass the random number value from this thread SocketConnectionThread to main and repaint the Applet window?

public class CobrowseApplet extends Applet implements ActionListener
{
    private static final long serialVersionUID = 1L;
    String titleStr ;
    String randomNumberStr;
    Image sharedImage;
    BufferedImage image;
    private Button connectBtn;
    Socket localSocket;
    PrintWriter out;
    BufferedReader in;
    static Timer timer;
    int delay = 1000;
    int period = 1000;
    DataInputStream inStream;
    PrintStream outStream;
    InputStream input;

    public void init(){
        titleStr = "Welcome";
        randomNumberStr = "";

        connectBtn = new Button("Connect");

        connectBtn.addActionListener(this);
        add(connectBtn);
        connectBtn.setBounds(200, 50, 90, 20);
        connectBtn.setEnabled(true);
        setLayout( null );

        setSize(550, 650);
    }
    public void paint (final Graphics g)
    {
        //super.paint(g);
        int x = getSize().width;
        int c1 = x/2;
        g.drawString(titleStr, c1-100, 20);
        g.drawString(randomNumberStr, c1-100, 80);
        System.out.println("sharedImage" + sharedImage);
        //g.drawImage(sharedImage, 100, 100, this);
        System.out.println("drawImage");
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        Thread thr = new Thread(new SocketConnectionThread(randomNumberStr));
        thr.start();


        if ( connectBtn.getLabel()=="Connect" )
        {
            connectBtn.setLabel("");
            connectBtn.setLabel("Disconnect");
        }
        else
        {
            connectBtn.setLabel("");
            connectBtn.setLabel("Connect");
        }
        System.out.println("randomNumberStr: " + randomNumberStr);

        repaint();
    }

}

class SocketConnectionThread implements Runnable {

    String randomStr;

    public SocketConnectionThread(String randomNumberStr) {
        this.randomStr = randomNumberStr;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println("Before Applet socket connection");

            Socket localSocket = new Socket(getLocalIP(), 8080);

            BufferedReader socketReader = new BufferedReader(new InputStreamReader(localSocket.getInputStream()));
            String msgStr = socketReader.readLine();
            System.out.println("Server Message on Client: " + msgStr);

            // IT GETS THE NEW STRING HERE FROM SOCKET. HOW CAN I PUSH TO MAIN?
            randomStr = msgStr;

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    String getLocalIP () {
        InetAddress inetAddress = null;
        String ipAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
            ipAddress = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("ipAddress : " + ipAddress);

        return ipAddress;
    }

}
Stella
  • 1,728
  • 5
  • 41
  • 95
  • You can try it with the [Observer-pattern](http://en.wikipedia.org/wiki/Observer_pattern). – Alexander_Winter Feb 17 '14 at 13:11
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Feb 18 '14 at 22:19

3 Answers3

0

To compare objects in java use .equals() method instead of "==" operator

Replace the following code

 if ( connectBtn.getLabel()=="Connect" )

to

  if ( "Connect".equals.(connectBtn.getLabel()))
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

Strings are immutable in java. And if you change the string in SocketConnectionThread the update won't be visibly in main thread. You can try to wrap your string with AtomicReference. This way you can change the value in your SocketConnectionThread and the main thread will always see the correct value.

A better solution is to move your SocketConnectionThread code into SwingWorker. You'll read the socket in the doInBackground() method and update the GUI in done() method.

Kojotak
  • 2,020
  • 2
  • 16
  • 29
  • I also need to get image data from socket and update in Main thread drawImage. So, please advise, what should be the easy and best approach to access both, "String" as well "Byte data" in Main thread (repainting windows) from Socket thread. I don't know how to use AtomicReference in my case. – Stella Feb 17 '14 at 14:01
  • I would use the SwingWorker. Check out this older tutorial: http://www.oracle.com/technetwork/articles/javase/swingworker-137249.html#ImageRetriever – Kojotak Feb 17 '14 at 15:55
  • Oh, I need an Applet to be extended, i have to use an Applet. – Stella Feb 17 '14 at 16:33
  • I don't know, how to achieve this whether SwingWorker or AtomicReference. Please help – Stella Feb 17 '14 at 16:57
0

You can try it with the Observer-Pattern:

public class CobrowseApplet extends Applet implements ActionListener, Observer {

    @Override
    public void update(Observable obs, Object obj) {
        String randomNumberStr = String.valueOf(obj);
        System.out.println("randomNumberStr: " + randomNumberStr);
        repaint();  
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        SocketConnectionThread sct = new SocketConnectionThread(randomNumberStr);
        Thread thr = new Thread(sct);
        sct.addObserver(this);
        thr.start();
        // ...
    }

    // your code here

}

class SocketConnectionThread extends Observable implements Runnable {

    List<Observer> observer;

    public SocketConnectionThread(String randomNumberStr) {
        this.randomStr = randomNumberStr;
        observer = new LinkedList<Observer>();
    }

    public void addObserver(Observer obs) {
        observer.add(obs);
    }

    @Override
    public void run() {
        // ...   
        randomStr = msgStr;
        notifyObservers(randomStr);   
        // ...
    }

    //  your code here

}
Alexander_Winter
  • 314
  • 1
  • 3
  • 9