【问题标题】:How to embed java code to a jython script.如何将 java 代码嵌入到 jython 脚本中。
【发布时间】:2012-03-03 02:57:36
【问题描述】:

我制作了这个 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

谢谢:)

【问题讨论】:

  • 如果@Leonel 的回答解决了您的问题,您应该接受他的回答。点击他答案旁边的绿色勾号:)

标签: java jython


【解决方案1】:

将 Java 代码的 sn-p 包装在公共 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')

您知道在上面的 sn-ps 中如何使用 JDK 中的 JButtonJFrame 吗?那是一回事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2011-07-01
    • 2013-07-02
    • 1970-01-01
    相关资源
    最近更新 更多