我有一个GUI程序,它通过TCPIP与设备通信。我开始创建一个应用程序,我后来想要创建一个JApplet。而且我认为我已经制作了一种混合类型,其中JApplet与appletviewer一起工作,但应用程序没有。我知道这是init()和静态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);
}
}