[英]How to embed java code to a jython script.
我制作了這個beanShell腳本,該腳本通過按按鈕來增加屏幕截圖,現在試圖弄清楚如何在Jython中使用Java來獲取實際的屏幕截圖(因為它是跨平台的)。
我的表現不是很好,並且想知道是否有人可以向我展示如何將Java部分插入Jython部分(我已經安裝了gui和event -見下文)?
這是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
謝謝 :)
將這段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中的JButton
和JFrame
嗎? 那是同一回事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.