/***************************************** 示範呼叫外部程式 *************************************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ui43 extends JFrame implements ActionListener { Container c; JLabel lab1,ans; JTextField txt1; JButton bot0,bot2; public ui43() //建構元 { super("呼叫demo4計算圓形面積"); c=getContentPane(); setSize(640,480); lab1=new JLabel("請輸入半徑:"); txt1=new JTextField(10); bot2=new JButton("算面積"); bot0=new JButton("結束程式"); ans=new JLabel("沒有任何答案!"); c.setLayout(new FlowLayout(FlowLayout.CENTER));//設定為流水版面設定 //注意加入元件的順序 c.add(lab1); c.add(txt1); c.add(bot2); c.add(ans); c.add(bot0); bot0.addActionListener(this);//設定自己為bot0按鈕的傾聽者 bot2.addActionListener(this);//設定自己為bot1按鈕的傾聽者 setVisible(true); } public void paint(Graphics g) //真正的畫圖設定 { super.paint(g);//畫出元件 } public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { if (e.getSource()==bot0) System.exit(0); if (e.getSource()==bot2) { java.io.BufferedInputStream inp; java.io.BufferedOutputStream out; java.io.BufferedInputStream err; byte tmp[]=new byte[1000]; int pt,num; String ins; try { Process prc=Runtime.getRuntime().exec("java demo4 "); inp= new java.io.BufferedInputStream(prc.getInputStream()); out=new java.io.BufferedOutputStream(prc.getOutputStream()); err=new java.io.BufferedInputStream(prc.getErrorStream()); ins=txt1.getText()+"\n"; out.write(ins.getBytes()); out.flush();//一定要flush喔! out.close(); pt=0; while ( inp.available()>0 || pt==0) { num=inp.read(tmp, pt, inp.available()); pt=pt+num; } ans.setText(new String(tmp,0,pt)); repaint(); inp.close(); err.close(); } catch (Exception ee) { System.out.println(ee.toString()); } } } /***主程式***/ public static void main(String args[]) //程式起點 { ui43 app=new ui43(); //畫圖 app.addWindowListener(new WindowAdapter(){ //匿名內部類別 public void windowClosing(WindowEvent e) { System.exit(0); } }); //處理視窗關閉要求 } }