2013-06-20 20 views
3

我正在嘗試製作屏幕捕獲程序。不能使用按鈕實例化一個類

我所擁有的是一個透明的窗口,這將給該地區被抓獲,上面有一個按鈕capture,我試圖在captureScreen單獨使用命令提示符

執行實例化一個類 captureScreen的作品好

我試圖實例化這個captureScreen類,當按鈕capture被擊中。

我已經試過保留這個class在我的screenrecord.java,把代碼也在event listener也。在這兩種情況下,我在

Robot robot = new Robot(); 

得到這些錯誤

AWTException,must be caught or declared 

和IOException異常在BufferedImage image線。

並保持captureScreen.java單獨不做任何事。 System.out.println("Start");甚至不會打印任何東西。

這裏是我screenrecord.java代碼

public class screenrecord extends JFrame implements ActionListener{ 
    public screenrecord() {... 
    } 
    public void actionPerformed(ActionEvent e){ 
     if ("record".equals(e.getActionCommand())) { 
      captureScreen a = new captureScreen(); 
      } 
    } 
} 

而且captureScreen.java,個別工作正常。

public class captureScreen extends Object{ 

    public static void main(String args[]){ 
     ... 
     Robot robot = new Robot(); 
     BufferedImage image = robot.createScreenCapture(screenRectangle); 
     ImageIO.write(image, "png", new File(filename)); 
     System.out.println("Done"); 
    } 

} 

所有的建議,意見,建議,歡迎和讚賞。 請幫我分類這個問題。謝謝。

回答

0

文選編輯captureScreen.java爲,

public class captureScreen extends Object{ 

    public captureScreen() { 
     .... 
     filename = ".\\out.png"; 
     try{Robot robot = new Robot(); 
      ............ } 
     catch(Exception e) /* Catch Exceptions too */ 
     { 
      System.out.println("Error"+e); 
     } 
    } 

    public static void main(String args[]){ 
     new captureScreen(); 
    } 
} 

主要使用實例的另一個功能。

4

您需要使用try/catches。這些並不像警告那樣錯誤。例如,插入此周圍具有的AWTException代碼:

try 
{ 
    //code causing AWTException 
    Robot robot = new Robot(); 
} 
catch(AWTException e) 
{ 
    System.out.println("Error"+e); 
} 

和:

try 
{ 
    //code causing IOException 
    BufferedImage image = robot.createScreenCapture(screenRectangle); 
} 
catch(IOException e) 
{ 
    System.out.println("Error"+e); 
} 

或者結合兩種:

try 
{ 
    //code causing AWTException or IOException 
    Robot robot = new Robot(); 
    BufferedImage image = robot.createScreenCapture(screenRectangle); 
} 
catch(IOException e) 
{ 
    System.out.println("Error"+e); 
} 
catch(AWTException e) 
{ 
    System.out.println("Error"+e); 
} 

對於進一步的閱讀,這可能有助於澄清例外:

http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html

+0

我已經使用了Google,並使用了try-catch。但是我的問題沒有解決。我無法讓我的類實例化。即使'captureScreen.java'中的「Start」和「Done」也不會被打印出來。屏幕也沒有被捕獲。 'Donesss'通過'screenrecord.java'打印出來但 –

+0

並且在捕捉異常時,try部分根本不起作用。這並不意味着這部分是最重要的。 –

+0

然後我不能告訴你發生了什麼問題。但是你描述的錯誤顯然是因爲你沒有try/catch語句。如果還有其他錯誤,它們不符合那些錯誤,並且您沒有給我們任何幫助。 – eatonphil