How to embed java code to a jython script.
I made this beanShell script that takes incrementing screenshots by button press, and am now trying to figure out how to do this in Jython using Java to take the actual screenshot (because it's cross platform).
I'm not doing very well though and was wondering if someone could show me how to insert the Java part in to the Jython part (I have the gui and event in place -- see below)?
This is the Java Part...
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"));
This is the whole beanShell script
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);
This is the Jython script开发者_运维知识库 I have so far...
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
Thanks :)
Wrap that snippet of Java code in a public Java class:
package com.mycompany;
public class ScreenshotEngine {
public void takeScreenshot(String filename) {
// Code that actually takes the screenshot and saves it to a file
}
}
Remember to compile it and make it available on the class path of your application.
Then, from the jython script, you can use it just like any other Java class.
# 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')
You know how you used JButton
and JFrame
from the JDK, in the snippets above ? That's the same thing.
精彩评论