// ExecCon2
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.text.*;
public class ExecCon2 extends JFrame
{
private JTabbedPane base = new JTabbedPane();
private SwingWorker<String, String> worker;
JButton btnExec = new JButton(new actExec());
JTextPane Console = new JTextPane();
JScrollPane Scr = new JScrollPane(Console,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
StyleContext sc = new StyleContext();
StyledDocument doc = (StyledDocument)Console.getDocument();
protected void initDoc( JTextPane pan ) { pan.setText("Console:\\n"); }
public ExecCon2()
{
this.getContentPane().add(Scr);
Console.setDocument( doc );
initDoc( Console );
try {
initTab0();
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing( WindowEvent e ) { System.exit(0); }
});
} catch(Exception e) {
e.printStackTrace();
}
}
///////////////////////////////////////////////////////////
private void initTab0() throws Exception
{
this.getContentPane().setLayout(null);
this.setSize(new Dimension(400, 300));
this.setTitle( "Exec and Console sample");
Scr.setBounds(new Rectangle( 5, 40, 380, 200 ));
this.getContentPane().add(base, null);
btnExec.setBounds(new Rectangle(5, 10, 65, 20));
this.add(btnExec,null);
}
// srings add to console
public void appendDoc( String str )
{
try {
System.out.print("appendDoc:"+str);
doc.insertString( doc.getLength(), str,
sc.getStyle(StyleContext.DEFAULT_STYLE) );
Console.setCaretPosition(doc.getLength());
} catch (BadLocationException ble){
System.err.println("Document style initalize error.");
}
}
class actExec extends AbstractAction {
public actExec() { super("run"); }
public void actionPerformed(ActionEvent evt) {
btnExec.setEnabled(false);
worker = new SwingWorker<String, String>() {
@Override public String doInBackground() {
try {
Process proc
= Runtime.getRuntime().exec("perl test.pl", null,null);
InputStream is = proc.getInputStream();
InputStreamReader isrs = new InputStreamReader(is);
BufferedReader ib = new BufferedReader(isrs, 10);
byte[] ibuff = new byte[100];
int ilen;
while ( true ) {
ilen = is.read(ibuff);
if( ilen < 0 ) break;
appendDoc( new String( ibuff, 0, ilen ) );
}
proc.waitFor();
} catch(Exception ex ) {
ex.printStackTrace();
}
appendDoc("Done");
return "Done";
}
@Override public void done() {
btnExec.setEnabled(true);
}
}; // End of worker
worker.execute();
// btnExec.setEnabled(true); // for multiprocessing
}
}
public static void main(String args[]) {
ExecCon2 obj = new ExecCon2();
}
} // end of Class
|