Java 应用/JApplet混合问题

Java 应用/JApplet混合问题,java,jframe,japplet,tcp-ip,hybrid,Java,Jframe,Japplet,Tcp Ip,Hybrid,我有一个GUI程序,它通过TCPIP与设备通信。我开始做一个申请,后来我想做一个日本人。我想我已经做了一种混合,JApplet与appletviewer一起工作,但应用程序没有。我知道init()和static void main()有问题 但即使applet在appletviewer中工作,当我将其测试为.html时,它也不会工作。出现错误“java.lang.reflect.InvocationTargetException”。我读过关于它的文章,这是因为它无法将我的JApplet检测为实际

我有一个GUI程序,它通过TCPIP与设备通信。我开始做一个申请,后来我想做一个日本人。我想我已经做了一种混合,JApplet与appletviewer一起工作,但应用程序没有。我知道init()和static void main()有问题

但即使applet在appletviewer中工作,当我将其测试为.html时,它也不会工作。出现错误“java.lang.reflect.InvocationTargetException”。我读过关于它的文章,这是因为它无法将我的JApplet检测为实际的applet(这可能是因为我的“混合”?)

你能看到我需要从init()和static void main()中添加/删除什么吗

谢谢

编辑:这是我的SSCCE。我有两个类-MPT_ui和tcpip(后者处理通信)。我已经删除了所有GUI按钮和文本字段,所以它非常可读。看一看:

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);
}
}
import javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.JButton;
导入javax.swing.JApplet;
导入javax.swing.JProgressBar;
导入javax.swing.JScrollPane;
导入javax.swing.JTextArea;
导入javax.swing.SwingUtilities;
导入javax.swing.border.EmptyBorder;
导入javax.swing.JLabel;
导入java.awt.Font;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.Insets;
导入java.net.InetAddress;
导入java.io.BufferedInputStream;
导入java.io.BufferedOutputStream;
导入java.io.DataInputStream;
导入java.io.DataOutputStream;
导入java.io.IOException;
导入java.net.InetAddress;
导入java.net.Socket;
公共类MPT_ui扩展JApplet实现ActionListener,Runnable{
/**
* 
*/
私有静态最终长serialVersionUID=1L;
私有JPanel内容窗格;
私人JProgressBar progressBar;
私有字符串cmd=“”;
字符串returnCmd=“”;
线程定时器;
字符串oldmessage=新字符串(“”);
私有JTextArea idList=新JTextArea(“”);
专用静态JTextArea输出框=新的JTextArea(20100);
私有JScrollPane scrollPane=新JScrollPane(idList);
私有JScrollPane ScrollPanel OG=新JScrollPane(输出框);
静态私有布尔值isapplet=true;
静态私有地址arg_ip=null;
静态专用int arg_端口=0;
tcpip gtp=null;;
InetAddress读取器_ip=null;
int端口=10001;
字符串host=“192.168.0.22”;
/**
*启动应用程序。
*/
公共void init(){
gtp=null;
读卡器ip=null;
端口=10001;
returnCmd=null;
//MPT_ui_frame=新的MPT_ui();
isapplet=true;
立根(100100473750);
contentPane=newjpanel();
setboorder(新的EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(null);
createObjects();
}
public void start(){//我已经对所有这些进行了注释,因为如果您未连接到我的设备,程序将不会启动,但是如果您想查看这是什么,请提供良好的概述
/*JLabel连接=新的JLabel(“TCP/IP连接状态:”);
connection.setFont(新字体(“Volvo Sans Pro”,Font.BOLD,14));
连接。设置前景(颜色。黑色);
连接.立根(1571017816);
contentPane.add(连接);
JLabel connStatus=新JLabel(“”);
connStatus.setFont(新字体(“Volvo Sans Pro”,Font.BOLD,14));
康涅狄格州(193710260,16);
contentPane.add(connStatus);
String st=“”;//新字符串(“TCP/IP连接状态:”);
System.out.println(“小程序启动\n”);
append(“小程序已启动\n\n”);
setCaretPosition(outputBox.getText().length()-1);
if(isapplet){
试一试{
//reader_ip=InetAddress.getByName(getCodeBase().getHost());
reader_ip=InetAddress.getByName(主机);
}
捕获(未知后异常e){}
}
否则{
读卡器ip=arg\u ip;
如果(arg_端口!=0){
端口=arg_端口;
}
}
//打开设备服务器串行端口的套接字
如果(读卡器ip!=null){
如果(gtp==null){
gtp=新的tcpip(读卡器ip,端口);
如果(gtp.s==null){
st+=“连接失败!未连接”;
connStatus.setForeground(颜色:红色);
connStatus.setText(st);
系统输出打印LN(st);
追加(st+“\n\n”);
gtp=null;
}
}
}
如果(gtp==null){
st=“未连接”;
//connStatus.setForeground(颜色:黄色);
//connStatus.setText(st);
追加(st+“\n\n”);
System.out.println(st+“\n”);
//添加((新标签(st)),c);
回来
}
st+=“已连接”;
设置前景(Color.GREEN.darker());
connStatus.setText(st);
System.out.println(st+“\n”);
追加(st+“\n\n”);
//添加((新标签(st)),c)*/
/*现在,您可以通过使用设备服务器执行IO
*gtp.send(字节[]数据输出);
*字节[]数据_in=gtp.receive();
*功能。
*在我们的示例中,我们将使用两个已扩展的文本框
*处理设备服务器的IO。在上表中键入的数据
*文本框将被发送到设备服务器,并接收数据
*将显示在下方的文本框中。
*/
//logThread.start()*/
}
公开募捐{
int i;
中的字节[];
线程me=Thread.currentThread();
while(timer==me){
试一试{
Thread.currentThread().sleep(1000);
}
捕获(中断异常e){}
如果((gtp!=null)和((i=gtp.available())>0)){
in=gtp.receive();
/*删除非打印字节*/
对于(i=0;i