0

В разработке есть кривое приложение для захвата скриншота экрана. Функционал захвата всей области экрана работает безупречно (понятное дело). А вот с захватом прямоугольной области возник конфуз! Захват экрана осуществляется с помощью класса SnippingTool.java, захваченное изображение выводится на фрейм, представленный классом SnippingForm.java. Команду на начало захвата из SnippingForm.java слушает ActionListener заброшенный на некий JMenuItem. Беда в том, что в классе SnippingTool.java есть свой слушатель (объект класса Handlerclass, реализующий интерфейсы MouseListener и MouseMotionListener), который проделывает всю работу по захвату определенной области. В общем, слушатель Handlerclass заканчивает свою работу позже, чем упомянутый выше ActionListener. А задумывалось все наоборот. Понимаю, что дело в потоках, но не понимаю, что нужно сделать (пробовал - не получилось).

SnippingForm.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class SnippingForm {

    private JFrame mainFrame = new JFrame();

    // Menu Bar
    private JMenuBar menuBar;
    private JMenu menuFile;
    private JMenu menuEdit;
    private JMenu menuCapture;
    private JMenu menuHelp;
    // Menu File
    private JMenuItem saveItem;
    private JMenuItem saveAsItem;
    private JMenuItem openFolderItem;
    private JMenuItem exitItem;
    // Menu Edit
    private JMenuItem copyItem;
    private JMenuItem preferencesItem;
    // Menu Capture
    private JMenuItem captureFullScreenItem;
    private JMenuItem captureRectangleAreaItem;
    // Menu Help
    private JMenuItem helpItem;
    private JMenuItem aboutItem;

    // Image output components
    private BufferedImage screenCapture;
    private JPanel outImagePanel;
    private JLabel outImageLabel;


    public SnippingForm() {

        // Frame params
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setResizable(true);
        mainFrame.setSize(600, 400);

        // Menu objects
        menuBar = new JMenuBar();

        menuFile = new JMenu("File");
        saveItem = new JMenuItem("Save");
        saveAsItem = new JMenuItem("Save As");
        openFolderItem = new JMenuItem("Open Folder");
        exitItem = new JMenuItem("Exit");
        menuFile.add(saveItem);
        menuFile.add(saveAsItem);
        menuFile.add(openFolderItem);
        menuFile.add(exitItem);
        menuBar.add(menuFile);

        menuEdit = new JMenu("Edit");
        copyItem = new JMenuItem("Copy Image to Clipboard");
        preferencesItem = new JMenuItem ("Preferences");
        menuEdit.add(copyItem);
        menuEdit.add(preferencesItem);
        menuBar.add(menuEdit);

        menuCapture = new JMenu("Capture");
        captureFullScreenItem = new JMenuItem("Capture Full Screen");
        captureFullScreenItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    SnippingTool snippingTool = new SnippingTool(0);
                    ImageIcon outputImage = new ImageIcon(snippingTool.getCapture());
                    outImageLabel.setIcon(outputImage);
                } catch (AWTException | IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
        captureRectangleAreaItem = new JMenuItem("Capture Rectangle Area");
        captureRectangleAreaItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    SnippingTool snippingTool = new SnippingTool(1);
                    snippingTool.getCapture();
                    System.out.println(Thread.currentThread().getName() + " main");
                    //outImageLabel.setIcon(outputImage);
                } catch (AWTException | IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
        menuCapture.add(captureFullScreenItem);
        menuCapture.add(captureRectangleAreaItem);
        menuBar.add(menuCapture);

        menuHelp = new JMenu("Help");
        helpItem = new JMenuItem("Help");
        aboutItem = new JMenuItem("About");
        menuHelp.add(helpItem);
        menuHelp.add(aboutItem);
        menuBar.add(menuHelp);

        outImagePanel = new JPanel();
        outImagePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY, 10),
                BorderFactory.createEmptyBorder(50, 50, 50, 50)));
        outImageLabel = new JLabel();
        outImagePanel.add(outImageLabel);
        JScrollPane outScrollPane = new JScrollPane(outImagePanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        Container container = mainFrame.getContentPane();
        container.add(menuBar, BorderLayout.NORTH);
        container.add(outScrollPane, BorderLayout.CENTER);
        mainFrame.setVisible(true);
    }


}

SnippingTool.java:

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;

public class SnippingTool extends JFrame{

    private JLabel mousepanel ;
    private JLabel statusbar;
    private ImageIcon imageicon;
    private ImageIcon greyimageicon;
    private BufferedImage cap;
    private BufferedImage greyCap;
    private BufferedImage outputImage;
    private CoordinatesPair initial, start, end;
    private int start_x, start_y;
    GraphicsDevice device = GraphicsEnvironment
            .getLocalGraphicsEnvironment().getScreenDevices()[0];

    public SnippingTool(int optionSelected) throws AWTException, IOException
    {
        end = new CoordinatesPair();
        cap = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        imageicon = new ImageIcon(cap);
        if(optionSelected == 0){
            outputImage = cap;
            SnippingTool.this.setVisible(false);
            SnippingTool.this.dispose();
        }else{
            greyCap = new BufferedImage(cap.getWidth(), cap.getHeight(),
                    BufferedImage.TYPE_BYTE_GRAY);
            statusbar = new JLabel("Стандартный");
            Graphics gr = greyCap.getGraphics();
            gr.drawImage(cap, 0, 0, null);
            gr.dispose();
            greyimageicon = new ImageIcon(greyCap);
            mousepanel = new JLabel(greyimageicon);
            mousepanel.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
            Handlerclass handler = new Handlerclass();
            mousepanel.addMouseListener(handler);
            mousepanel.addMouseMotionListener(handler);
            add(statusbar, BorderLayout.SOUTH);
            add(mousepanel);
            setExtendedState(JFrame.MAXIMIZED_BOTH);
            setUndecorated(true);
            device.setFullScreenWindow(null);
            device.setFullScreenWindow(this);
            setVisible(true);
        }
    }

    static BufferedImage deepCopy(BufferedImage inp)
    {
        ColorModel cm = inp.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = inp.copyData(null);
        return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
    }
    public class Handlerclass implements MouseListener, MouseMotionListener
    {

        public void mouseClicked(MouseEvent event)
        {
            statusbar.setText("Щелкнута");
        }
        public void mousePressed(MouseEvent event)
        {
            initial = new CoordinatesPair(event.getX(), event.getY());
            start = new CoordinatesPair(event.getX(), event.getY());
            statusbar.setText("Нажата");
        }
        public void mouseReleased(MouseEvent event)
        {
            try{
                synchronized (outputImage) {
                    setCoordinates(event.getX(), event.getY());
                    BufferedImage copy = cap.getSubimage(start.x, start.y, end.x-start.x, end.y-start.y);
                    BufferedImage crop = new BufferedImage(copy.getWidth(), copy.getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics g = crop.createGraphics();
                    g.drawImage(copy,0,0,null);
                    device.setFullScreenWindow(null);
                    setVisible(false);
                    dispose();
                    outputImage = crop;
                    System.out.println(Thread.currentThread().getName() + "clicked");
                }
            }catch(Exception e){
                System.out.print("Системная ошибка");
            }
        }
        public void mouseEntered(MouseEvent event)
        {
            statusbar.setText("Область ввода");
        }
        public void mouseExited(MouseEvent event)
        {
            statusbar.setText("Выход");
        }
        public void mouseDragged(MouseEvent event)
        {
            statusbar.setText("Перемещина");
            BufferedImage temp = deepCopy(greyCap);
            Graphics2D g2d = temp.createGraphics();
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f));
            g2d.setColor(Color.RED);
            setCoordinates(event.getX(), event.getY());
            g2d.drawRect(start.x, start.y, end.x-start.x, end.y-start.y);
            imageicon.setImage(temp);
            mousepanel.setIcon(null);
            mousepanel.setIcon(imageicon);
        }
        public void mouseMoved(MouseEvent event)
        {
            ;
        }
    }
    public void setCoordinates(int event_x, int event_y)
    {
        int diff_x = event_x - initial.x;
        int diff_y = event_y - initial.y;
        if(diff_x>=0 && diff_y>=0)
            end.set(event_x,  event_y);
        else if(diff_x<=0 && diff_y>=0)
        {
            end.y = event_y;
            end.x = initial.x;
            start.x = event_x;
        }
        else if(diff_x>=0 && diff_y<=0)
        {
            end.x = event_x;
            end.y = initial.y;
            start.y = event_y;
        }
        else
        {
            end.x = initial.x;
            end.y = initial.y;
            start.x = event_x;
            start.y = event_y;
        }
    }

    public BufferedImage getCapture() {
        return outputImage;
    }
}

Далее классы, если будет желание скомпилировать на своей ЭВМ.

CoordinatesPair.java:

 public class CoordinatesPair {
    public int x, y;
    public CoordinatesPair(){
        x=0;
        y=0;
    }
    public CoordinatesPair(int a, int b)
    {
        x = a;
        y = b;
    }
    public void set(int a, int b)
    {
        x = a;
        y = b;
    }
    public CoordinatesPair deepCopy(CoordinatesPair p)
    {
        return new CoordinatesPair(p.x, p.y);
    }
    public void swap(CoordinatesPair p)
    {
        int tmp_x = p.x;
        int tmp_y = p.y;
        p.x = x;
        p.y = y;
        x = tmp_x;
        y = tmp_y;
    }
}

App.java:

import java.awt.*;

public class App {

    public static void main(String [] args) throws AWTException {
        SnippingForm appForm = new SnippingForm();
    }
}

2 ответа 2

1

Я думаю во втором случае (да и в первом можно, для схожести) тебе надо в SnipingTool передавать свой обработчик, который будет вызываться, когда изображение захвачено.

interface ScreenshotHandler {
  void onScreenshot(BufferedImage image);
}

...

public class SnippingTool extends JFrame{
  ...
  private ScreenshotHandler screenshotHandler;
  public SnippingTool(int optionSelected, screenshotHandler ScreenshotHandler) throws AWTException, IOException  {
        this.screenshotHandler = screenshotHandler;
        .... // остальное как есть за исключением, 
        // что во всех местах, где ты присваиваешь outputImage = ...
        // должно быть this.screenshotHandler.onScreenshot(image)
        // а поле outputImage тебе вообще не нужно
  }
  ...
}

....

в обоих местах, где ты создаёшь SnippingTool, д.б.

SnippingTool snippingTool = new SnippingTool(0 или 1, new ScreenshotHandler() {
  void onScreenshot(BufferedImage screenshot) {
     outImageLabel.setIcon(new ImageIcon(screenshot));
  }
});

1

Решил элементарно... передал в SnippingTool() объект, на который нужно выводить изображение - outImagePanel, т.е. обработчик mouseReleased() сразу закидывает результат работы в него.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.