【问题标题】:How to show BufferedImages in SWT project?如何在 SWT 项目中显示 BufferedImages?
【发布时间】:2013-09-22 18:45:05
【问题描述】:

我正在处理一个 SWT 项目,但我将与 Awt.Robot.createScreenCapture() 广泛合作以生成 BufferedImages。我会以这种方式生成成百上千张图像。

问题是,SWT 似乎无法显示 BufferedImages ,并且有自己的 Image 类。我知道可以将 BufferedImages 转换为 SWT 的 Image,但 SWT 的图像似乎需要手动处理,并且没有像 Swing 的 BufferedImage 那样的自动垃圾收集。

另外,我认为计算机不断地从 BufferedImage 转换为 Image 需要时间/精力,这可能会减慢我的程序,因为它是一个时间要求严格的应用程序,这是不可接受的。

那么,有没有办法在 SWT Shell 上显示 BufferedImages? (我可能会有一个 Jpanel 显示每个图像的图像,所以我只需要一种方法将 JPanel 显示到 Shell 上。)

【问题讨论】:

  • 要么使用swt/awt bridge,要么在弹出的jframe中显示图像。

标签: java swing swt awt bufferedimage


【解决方案1】:

我按照对您问题的评论中的建议尝试了 SWT/AWT Bridge,它按预期工作:

    static BufferedImage bim;

static Frame frame;

public static void main(String[] args) {

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {

                try {
                    final java.awt.Rectangle screenRect = new java.awt.Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                    bim = new Robot().createScreenCapture(screenRect);
                    frame.repaint();
                    Thread.sleep(100);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }).start();

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    shell.setSize(200, 200);

    Composite composite = new Composite(shell, SWT.EMBEDDED | SWT.NO_BACKGROUND);
    frame = SWT_AWT.new_Frame(composite);
    frame.setLayout(new BorderLayout());
    frame.add(new JPanel() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(bim, 0, 0, this);
        }

    }, BorderLayout.CENTER);
    frame.setVisible(true);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

干杯

【讨论】:

  • 谢谢!一个问题,如果我想显示多个这些图像(例如 4-5),我会怎么做?我需要做些什么来制作可重复使用的BufferedImageContainer 或这样的类,我可以重复添加到我的shells(并调用setImage(myBufferedImage) 来设置图像?)
  • “多个图像”作为同一个面板上的图块?
  • 我认为每张图片都应该在自己的 Java 框架/合成中,这样我就可以将它们放在我需要的任何地方
猜你喜欢
  • 1970-01-01
  • 2012-06-21
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
相关资源
最近更新 更多