2011-07-29 39 views
1

我做了這個beanShell腳本,它通過按下按鈕增加屏幕截圖,現在我正在試圖找出如何在Jython中使用Java來實現截圖(因爲它是跨平臺的)。如何將java代碼嵌入到jython腳本中。

雖然我並沒有做得很好,但想知道是否有人能告訴我如何將Java部分插入到Jython部分(我有gui和事件到位 - 請參見下文)?

這是Java部分...

Dimension scr = Toolkit.getDefaultToolkit().getScreenSize(); 
Robot robot = new Robot(); 
Rectangle rect = new Rectangle(0, 0, scr.width, scr.height); 
BufferedImage image = robot.createScreenCapture(rect); 
ImageIO.write(image, "jpeg", new File("Captured" + c + ".jpg")); 

這是整個的BeanShell腳本

import java.awt.Toolkit; 
import java.awt.event.KeyEvent; 
import java.awt.image.BufferedImage; 
import javax.imageio.ImageIO; 
import java.io.File; 
import java.io.IOException; 

int c = 0; // image counter 

buttonHandler = new ActionListener() { 
    actionPerformed(this) { 

    Dimension scr = Toolkit.getDefaultToolkit().getScreenSize(); 

    // Allocate a Robot instance, and do a screen capture 
    Robot robot = new Robot(); 
    Rectangle rect = new Rectangle(0, 0, scr.width, scr.height); 
    BufferedImage image = robot.createScreenCapture(rect); 

    // Save the captured image to file with ImageIO (JDK 1.4) 
    ImageIO.write(image, "jpeg", new File("Captured" + c + ".jpg")); 
    c++; 
    } 
}; 

button = new JButton("Click to save incrementing screenshots to this app's location"); 
button.addActionListener(buttonHandler); 
// JLabel label1 = new JLabel("hello"); 
frame(button); 

這是Jython腳本我到目前爲止...

from javax.swing import JButton, JFrame 
from java.awt import Toolkit 
from java.awt.event import KeyEvent; 
from java.awt.image import BufferedImage; 
from javax.imageio import ImageIO;  
from java.io import File, IOException 

c = 0 

frame = JFrame(
    'App Title', 
    defaultCloseOperation = JFrame.EXIT_ON_CLOSE, 
    size = (450, 60) 
) 


def change_text(event): 
    global c 
    ... 
    // Java part 
    ... 
    c = c + 1 


button = JButton(
    "Click to save incrementing screenshots to this app's location", 
    actionPerformed=change_text 
) 

frame.add(button) 
frame.visible = True 

謝謝:)

+0

如果@ Leonel的答案解決了您的問題,您應該接受他的答案。點擊他答案旁邊的綠色勾號:) –

回答

1

裹在一個公共Java類的Java代碼片段:

package com.mycompany; 
public class ScreenshotEngine { 
    public void takeScreenshot(String filename) { 
    // Code that actually takes the screenshot and saves it to a file 
    } 
} 

請記住,編譯它,並使其可應用程序的類路徑上。

然後,從jython腳本中,您可以像使用任何其他Java類一樣使用它。

# Using the fully qualified name of the class 
engine = com.mycompany.ScreenshotEngine() 
engine.takeScreenshot('/tmp/sc1.png') 

# You can also use import to shorten class names 
from com.mycompany import ScreenshotEngine 
engine = ScreenshotEngine() 
engine.takeScreenshot('/tmp/sc2.png') 

你知道如何從JDK上面使用JButtonJFrame,在片段?這是一回事。

相關問題