0

I have a GUI program which communicates with a device via TCPIP. I started out making an application, which I later on wanted to make to a JApplet. And I think I've made an type of hybrid where the JApplet works with appletviewer but the application doesn't. I know it's something with init() and the static void main() that is wrong.

But even though the applet works in appletviewer, it won't work when I test it as .html. The error "java.lang.reflect.InvocationTargetException" occurs. I've read about it and it's because it can't detect my JApplet as an actual applet (and that's probably because of my "hybrid"?)

Can you see what I need to add/remove from my init() and static void main()?

Thanks!

Edit: This is my SSCCE. I got two classes - MPT_ui and tcpip (the latter is handling the communcation). I've removed all GUI-buttons and textfields so it's pretty readible. Take a look:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JApplet;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Insets;
import java.net.InetAddress;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;


public class MPT_ui extends JApplet implements ActionListener, Runnable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;

private JProgressBar progressBar;


private String cmd = "";

String returnCmd="";
Thread timer;

String oldmessage = new String("");
private JTextArea idList= new JTextArea("");
private static JTextArea outputBox = new JTextArea(20, 100);

private JScrollPane scrollPane = new JScrollPane(idList); 
private JScrollPane scrollPaneLog = new JScrollPane(outputBox);

static private boolean isapplet = true;
static private InetAddress arg_ip = null;
static private int arg_port = 0;
tcpip gtp = null;;
InetAddress reader_ip = null;
int port = 10001;
String host="192.168.0.22";




/**
 * Launch the application.
 */

public void init() {

    gtp = null;
    reader_ip = null;
    port = 10001;
    returnCmd=null;

    //MPT_ui ui_frame = new MPT_ui();
    isapplet = true;

    setBounds(100, 100, 473, 750);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    createObjects(); 



}


public void start(){  //I've commented all this because the program wont start if ur not connected to my device, but good overview if u want to see what this is
/*  JLabel connection = new JLabel("TCP/IP connection status: ");
    connection.setFont(new Font("Volvo Sans Pro", Font.BOLD, 14));
    connection.setForeground(Color.BLACK);
    connection.setBounds(15, 710, 178, 16);
    contentPane.add(connection);

    JLabel connStatus = new JLabel("");
    connStatus.setFont(new Font("Volvo Sans Pro", Font.BOLD, 14));
    connStatus.setBounds(193, 710, 260, 16);
    contentPane.add(connStatus);
    String st = "";// new String("TCP/IP connection status: ");


    System.out.println("applet started\n");
    outputBox.append("applet started\n\n");
    outputBox.setCaretPosition(outputBox.getText().length() - 1);

    if (isapplet) {
        try{
            //reader_ip = InetAddress.getByName(getCodeBase().getHost());
            reader_ip = InetAddress.getByName(host);
        }
        catch (UnknownHostException e){}
    }
    else {
        reader_ip = arg_ip;
        if (arg_port != 0) {
            port = arg_port;
        }
    }
//   Open a socket to the Device Server's serial port 
    if (reader_ip != null) {
        if (gtp == null) {
            gtp = new tcpip(reader_ip, port);
            if (gtp.s == null) {
                st += "connection FAILED! not connected";
                connStatus.setForeground(Color.RED);
                connStatus.setText(st);
                System.out.println(st);
                outputBox.append(st+"\n\n");
                gtp = null;
            }
        }
    }
    if (gtp == null) {
        st = "not connected";
        //connStatus.setForeground(Color.yellow);
        //connStatus.setText(st);
        outputBox.append(st+"\n\n");
        System.out.println(st+"\n");
        //add((new Label(st)), c);
        return;
    }
    st += "connected";
    connStatus.setForeground(Color.GREEN.darker());
    connStatus.setText(st);
    System.out.println(st+"\n");
    outputBox.append(st+"\n\n");
    //add((new Label(st)), c);*/

    /* You may now perform IO with the Device Server via
    * gtp.send(byte[] data_out);
    * byte[] data_in = gtp.receive();
    * functions.
    * In our example we'll use two TextBoxes which have been extended
    * to handle IO to the Device Server. Data typed in the upper
    * text box will be sent to the Device Server, and data received
    * will be displayed in the lower text box.
    */
    //logThread.start();*/


}


public void run(){
    int i;
    byte[] in;
    Thread me = Thread.currentThread();


    while (timer == me) {
        try {
            Thread.currentThread().sleep(1000);
        }
        catch (InterruptedException e) { }
        if ( (gtp != null) && ((i = gtp.available()) > 0) ) {
            in = gtp.receive();
            /* remove non-printing bytes */
            for (i = 0; i < in.length; i++) {
                if (in[i] < 0x20)
                    in[i] = 0x20;
            }


            //returnCmd=returnCmd+"\n"+(new String(in));  //FNKAR SKITBRA!!  

            returnCmd="";


            if(cmd.equals("w"))
            {
                returnCmd=(new String (in));
                idList.append(returnCmd+"\n");
                outputBox.append(returnCmd+"\n");
                System.out.println(returnCmd);
                outputBox.setCaretPosition(outputBox.getText().length() - 1);
            }

            else returnCmd=(new String(in));
        }


        }


}



public void destroy()
{
    if (gtp != null)
    gtp.disconnect();
    gtp = null;
}

public void stop() {
}



public MPT_ui() { 

}



public static void main(String[] args){


/*  if (args.length > 0) {
        try{
            arg_ip = InetAddress.getByName(args[0]);
        }
        catch (UnknownHostException e){}
        if (args.length > 1) {
        try {
            arg_port = Integer.valueOf(args[1]).intValue();
        }
        catch (NumberFormatException e) {}
        }

    }*/

    //I've commented this because if you're not connected the applet wont start...


    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {

                MPT_ui ui_frame = new MPT_ui();
                isapplet = false; 
                ui_frame.init();
                ui_frame.start();
                ui_frame.setVisible(true);

            }
        });
    } catch (Exception e) { 
        System.out.println("mpt_ui didn't complete successfully");
        e.printStackTrace();
    }


}   


//***************************************************************************************************


public void createObjects()  //I've removed all of my buttons, textfields and so on
{

    progressBar = new JProgressBar(0, 100);
    progressBar.setStringPainted(true);
    progressBar.setBounds(50, 464, 350, 25);


    outputBox.setLineWrap(true);   
    outputBox.setWrapStyleWord(true); 
    scrollPaneLog.setBounds(50, 500, 350, 200);

    outputBox.setMargin(new Insets(5,5,5,5));


    JLabel consoleLbl = new JLabel("Console");
    consoleLbl.setFont(new Font("Volvo Broad", Font.PLAIN, 24));
    consoleLbl.setBounds(190, 464, 70, 25);

    outputBox.setLineWrap(true);   
    outputBox.setWrapStyleWord(true); 


    outputBox.setEditable(false);

    contentPane.add(scrollPaneLog);
    contentPane.add(progressBar);

    JButton btnExit = new JButton("Exit");  //430
    btnExit.setBounds(385, 430, 56, 25);
    contentPane.add(btnExit);
    btnExit.addActionListener(this);

} 

    //***************************************************************************************************

    public void sendTCPIP(String message)    //my method which sends strings to my device server (handled by my class tcpip)
    {

        String str = new String("");

        int len = message.length();
        str=message;

        if ( (len != 0) && (gtp != null) )
            gtp.send(str);


    }




                //***************************************************************************************************


public void exitProgram()
{
    //JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");



    Object[] exitOptions = {"Yes, please", "No, thanks"};
    int ans = JOptionPane.showOptionDialog(null ,"Are you sure you want to exit?",
            "Exit Program",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            exitOptions,
            exitOptions[1]);

if(ans==0)
{
    System.out.println("killing applet\n");
    outputBox.append("killing applet\n\n");
    outputBox.setCaretPosition(outputBox.getText().length() - 1);
    System.exit(0);
}
else ;

}

//***************************************************************************************************

@Override
public void actionPerformed(ActionEvent aEvent) 
{

        if("Exit".equals(aEvent.getActionCommand())) exitProgram();


}


}   

/*
* This class opens a TCP connection, and allows reading and writing of byte arrays.
*/
class tcpip
{
protected Socket s = null;
public DataInputStream dis = null;
protected DataOutputStream dos = null;

public tcpip(InetAddress ipa, int port)
{
    Socket s1 = null;
    try { // Open the socket
        s1 = new Socket(ipa.getHostAddress(), port);
    }
    catch (IOException e) {
        System.out.println("Error opening socket");
        return;
    }
    s = s1;
    try { // Create an input stream
        dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
    }
    catch(Exception ex) {
        System.out.println("Error creating input stream");
    }
    try { // Create an output stream
        dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
    }
    catch(Exception ex) {
        System.out.println("Error creating output stream");
    }
}

public synchronized void disconnect()
{
    if (s != null) {
    try {
        s.close();
    }
    catch (IOException e){}
    }
}

public synchronized void send(byte[] temp)
{
    try {
        dos.write(temp, 0, temp.length);
        dos.flush();
        dos.flush();
    }
    catch(Exception ex) {
        System.out.println("Error sending data : " + ex.toString());
        //JOptionPane.showMessageDialog(null,"Error sending data : " + ex.toString());
    }
}

public synchronized void send(byte[] temp, int len)
{
    try {
        dos.write(temp, 0, len);
        dos.flush();
        dos.flush();
    }
    catch(Exception ex) {
        System.out.println("Error sending data : " + ex.toString());

    }
}

public synchronized void send(String given)
{
    // WARNING: this routine may not properly convert Strings to bytes
    int length = given.length();
    byte[] retvalue = new byte[length];
    char[] c = new char[length];
    given.getChars(0, length, c, 0);
    for (int i = 0; i < length; i++) {
        retvalue[i] = (byte)c[i];
    }
    try {
        dos.flush();
    }
    catch (IOException e){}
    send(retvalue);
}

public synchronized byte[] receive()
{
    byte[] retval = new byte[0];

    try {
        while(dis.available() == 0); /* Wait for data */
    }
    catch (IOException e){}
    try {

        retval = new byte[dis.available()];
    }
    catch (IOException e){}
    try {
        dis.read(retval);
        dos.flush();

    }
    catch (IOException e){}
    System.out.println("retval: "+retval);
    return(retval);
}

public int available()
{
    int avail;
    avail = 0;
    try {
        avail = dis.available();
        dos.flush();  
    }
    catch (IOException e) {}
    return(avail);
}
}
Kalekulan
  • 13
  • 5
  • *"..I started out making an application, which I later on wanted to make to a JApplet."* Tat is a bad idea, for starters. If you can make it work in a `JFrame`, it will be easier to launch the frame using [Java Web Start](http://stackoverflow.com/tags/java-web-start/info) than to deploy an applet. – Andrew Thompson Dec 13 '13 at 22:40
  • 1) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Dec 13 '13 at 22:40
  • Hi, thank you for you answer, Andrew! The device I'm using is a Device Server (ethernet) which can read via RS232. This device server has a possibility to add an JApplet on the its webpage. So I don't think web start will work? – Kalekulan Dec 14 '13 at 14:09
  • Applets can be deployed free floating since the start of JWS around the end of Java 1.2. Since the 'Plug-In 2 architecture JREs' were introduced in 1.6.0_10+, an applet deployed by JWS can remain 'embedded' in the web page. -- Where is that SSCCE? – Andrew Thompson Dec 14 '13 at 14:16
  • @AndrewThompson Alright! Well then maybe I should reconstruct it to an application again? I've added my SSCCE now. – Kalekulan Dec 14 '13 at 19:19
  • *"This is my SSCCE. I got two classes"* They must both be in the **same source file** to be an SSCCE. Demote one class from `public` & paste it in the end of the other. (Try again!) – Andrew Thompson Dec 14 '13 at 19:22
  • OK ..finally I've ..seen the applet on-screen, with no `IvocationTargetException` ... ``. We seem to be taking one step forward, and two steps back! But while I'm here: `catch (IOException e) {}` Never do that. Change code of the form `catch (Exception e) { ..` to `catch (Exception e) { e.printStackTrace(); // very informative! ..` – Andrew Thompson Dec 14 '13 at 21:09
  • 1
    @AndrewThompson Now when I tried the SSCCE it worked for me too. But as soon as I run the whole program I get the same error as before. Does it have something to do with the init()? Because if I don't have a connection the program can sometimes struggle. Maybe it has problems running the program on html? – Kalekulan Dec 16 '13 at 08:33
  • *"Does it have something to do with.."* It has everything to do with the difference between the short and the log version. Keep trimming one, or adding to the other, until you find the code line that triggers it. – Andrew Thompson Dec 16 '13 at 08:42
  • @AndrewThompson Hi again. The problem was the images the program was trying to find (something is wrong the path). My files is placed like this: C:/.../src - all my .java, .class and my .html Here's my resources (images): C:.../src/resources And here's my path in the program: ImageIcon icon = new ImageIcon("resources\\smallicon_transp.png"); It works perfect in appletviewer but not in .html. Where should I put it? P.S. I've tried ClassLoader with same results. D.S. – Kalekulan Dec 19 '13 at 09:10
  • Did it occur to you that instead of 487 LOC that I am not going to search for the image loading, it might be better to post a 20 LOC SSCCE of loading an image? And as an aside, IMO 487 LOC is *not* short. – Andrew Thompson Dec 19 '13 at 15:42

0 Answers0