我制作了这个beanShell脚本,通过按下按钮增加截图,我现在正试图弄清楚如何在Jython中使用Java来拍摄实际截图(因为它是跨平台的)。
我的表现不是很好,并且想知道是否有人可以告诉我如何将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 :(得分: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中使用JButton
和JFrame
,在上面的代码段中?那是一回事。