Example usage for java.awt Canvas Canvas

List of usage examples for java.awt Canvas Canvas

Introduction

In this page you can find the example usage for java.awt Canvas Canvas.

Prototype

public Canvas() 

Source Link

Document

Constructs a new Canvas.

Usage

From source file:PaintAWTInsideSWT.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    Composite composite = new Composite(shell, SWT.EMBEDDED);

    Frame frame = SWT_AWT.new_Frame(composite);
    Canvas canvas = new Canvas() {
        public void paint(Graphics g) {
            Dimension d = getSize();
            g.drawLine(0, 0, d.width, d.height);
        }//from w w  w.ja  v  a 2  s .c  om
    };
    frame.add(canvas);

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

From source file:org.eclipse.swt.snippets.Snippet155.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 155");
    shell.setLayout(new FillLayout());
    Composite composite = new Composite(shell, SWT.EMBEDDED);

    /* Draw an X using AWT */
    Frame frame = SWT_AWT.new_Frame(composite);
    Canvas canvas = new Canvas() {
        @Override//from  ww  w.j a  v  a 2s  .  c o m
        public void paint(Graphics g) {
            Dimension d = getSize();
            g.drawLine(0, 0, d.width, d.height);
            g.drawLine(d.width, 0, 0, d.height);
        }
    };
    frame.add(canvas);

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

From source file:org.eclipse.swt.snippets.Snippet337.java

public static void main(String args[]) {
    display = new Display();
    EventQueue.invokeLater(() -> {
        JFrame mainFrame = new JFrame("Main Window");
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.addWindowListener(new Snippet337.CloseListener());
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new FlowLayout());
        JButton launchBrowserButton = new JButton("Launch Browser");
        launchBrowserButton.addActionListener(e -> {
            JFrame childFrame = new JFrame();
            final Canvas canvas = new Canvas();
            childFrame.setSize(850, 650);
            childFrame.getContentPane().add(canvas);
            childFrame.setVisible(true);
            display.asyncExec(() -> {
                Shell shell = SWT_AWT.new_Shell(display, canvas);
                shell.setSize(800, 600);
                Browser browser = new Browser(shell, SWT.NONE);
                browser.setLayoutData(new GridData(GridData.FILL_BOTH));
                browser.setSize(800, 600);
                browser.setUrl("http://www.eclipse.org");
                shell.open();/*w ww .  j  a v a 2  s.  c o m*/
            });
        });

        mainPanel.add(new JTextField("a JTextField"));
        mainPanel.add(launchBrowserButton);
        mainFrame.getContentPane().add(mainPanel, BorderLayout.CENTER);
        mainFrame.pack();
        mainFrame.setVisible(true);
    });
    display.addListener(SWT.Close, event -> EventQueue.invokeLater(() -> {
        Frame[] frames = Frame.getFrames();
        for (int i = 0; i < frames.length; i++) {
            frames[i].dispose();
        }
    }));
    while (!display.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
}

From source file:org.eclipse.swt.snippets.Snippet361.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 361");
    shell.setText("Translate and Rotate an AWT Image in an SWT GUI");
    shell.setLayout(new GridLayout(8, false));

    Button fileButton = new Button(shell, SWT.PUSH);
    fileButton.setText("&Open Image File");
    fileButton.addSelectionListener(widgetSelectedAdapter(e -> {
        String filename = new FileDialog(shell).open();
        if (filename != null) {
            image = Toolkit.getDefaultToolkit().getImage(filename);
            canvas.repaint();//from  w w  w  . j a  v a  2 s  .co m
        }
    }));

    new Label(shell, SWT.NONE).setText("Translate &X by:");
    final Combo translateXCombo = new Combo(shell, SWT.NONE);
    translateXCombo.setItems("0", "image width", "image height", "100", "200");
    translateXCombo.select(0);
    translateXCombo.addModifyListener(e -> {
        translateX = numericValue(translateXCombo);
        canvas.repaint();
    });

    new Label(shell, SWT.NONE).setText("Translate &Y by:");
    final Combo translateYCombo = new Combo(shell, SWT.NONE);
    translateYCombo.setItems("0", "image width", "image height", "100", "200");
    translateYCombo.select(0);
    translateYCombo.addModifyListener(e -> {
        translateY = numericValue(translateYCombo);
        canvas.repaint();
    });

    new Label(shell, SWT.NONE).setText("&Rotate by:");
    final Combo rotateCombo = new Combo(shell, SWT.NONE);
    rotateCombo.setItems("0", "Pi", "Pi/2", "Pi/4", "Pi/8");
    rotateCombo.select(0);
    rotateCombo.addModifyListener(e -> {
        rotate = numericValue(rotateCombo);
        canvas.repaint();
    });

    Button printButton = new Button(shell, SWT.PUSH);
    printButton.setText("&Print Image");
    printButton.addSelectionListener(widgetSelectedAdapter(e -> {
        performPrintAction(display, shell);
    }));

    composite = new Composite(shell, SWT.EMBEDDED | SWT.BORDER);
    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 8, 1);
    data.widthHint = 640;
    data.heightHint = 480;
    composite.setLayoutData(data);
    Frame frame = SWT_AWT.new_Frame(composite);
    canvas = new Canvas() {
        @Override
        public void paint(Graphics g) {
            if (image != null) {
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());

                /* Use Java2D here to modify the image as desired. */
                Graphics2D g2d = (Graphics2D) g;
                AffineTransform t = new AffineTransform();
                t.translate(translateX, translateY);
                t.rotate(rotate);
                g2d.setTransform(t);
                /*------------*/

                g.drawImage(image, 0, 0, this);
            }
        }
    };
    frame.add(canvas);
    composite.getAccessible().addAccessibleListener(new AccessibleAdapter() {
        @Override
        public void getName(AccessibleEvent e) {
            e.result = "Image drawn in AWT Canvas";
        }
    });

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

From source file:SampleAWTRenderer.java

/**
 * Returns an AWT component that it will render to. Returns null
 * if it is not rendering to an AWT component.
 *///w w w.  ja  va  2 s  .  co m
public java.awt.Component getComponent() {
    if (component == null) {
        component = new Canvas() {
            public Dimension getPreferredSize() {
                return new Dimension(getInWidth(), getInHeight());
            }

            public void update(Graphics g) {
            }

            public void paint(Graphics g) {
                // TODO: Need to repaint image if the movie is in paused state
            }

        };
    }

    return component;
}

From source file:biometricgui.MainWindow.java

void runMedia(String filePath) {
    NativeDiscovery nd = new NativeDiscovery();
    if (!nd.discover()) {
        System.out.println("VLC not found");
        System.exit(-1);//w w  w  . ja v  a  2 s  .  c  om
    }
    Canvas canvas = new Canvas();
    jPanel1.add(canvas);
    canvas.setSize(jPanel1.getSize());
    jPanel1.revalidate();
    jPanel1.repaint();

    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
    EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
    CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas);
    mediaPlayer.setVideoSurface(videoSurface);
    jLabel2.setVisible(false);
    mediaPlayer.playMedia(filePath);
}

From source file:net.wurstclient.hooks.FrameHook.java

public static void createFrame(DefaultResourcePack mcDefaultResourcePack, Logger logger) throws LWJGLException {
    // check if frame should be created
    if (!isAutoMaximize() && !WurstBot.isEnabled())
        return;/*from   www .  ja  v a2s.  c  o  m*/

    // create frame
    frame = new JFrame("Minecraft 1.8");

    // add LWJGL
    Canvas canvas = new Canvas();
    canvas.setBackground(new Color(16, 16, 16));
    Display.setParent(canvas);
    Minecraft mc = Minecraft.getMinecraft();
    canvas.setSize(mc.displayWidth, mc.displayHeight);
    frame.add(canvas);

    // configure frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);

    // add icons
    InputStream icon16 = null;
    InputStream icon32 = null;
    try {
        icon16 = mcDefaultResourcePack.func_152780_c(new ResourceLocation("icons/icon_16x16.png"));
        icon32 = mcDefaultResourcePack.func_152780_c(new ResourceLocation("icons/icon_32x32.png"));
        ArrayList<BufferedImage> icons = new ArrayList<>();
        icons.add(ImageIO.read(icon16));
        icons.add(ImageIO.read(icon32));
        frame.setIconImages(icons);
    } catch (Exception e) {
        logger.error("Couldn't set icon", e);
    } finally {
        IOUtils.closeQuietly(icon16);
        IOUtils.closeQuietly(icon32);
    }

    // show frame
    if (!WurstBot.isEnabled())
        frame.setVisible(true);
}

From source file:tv.dyndns.kishibe.qmaclone.server.IconUploadServletStub.java

private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    logger.log(Level.INFO, request.toString());

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(64L * 1024L);/*from   w  w  w.j  a v a  2 s.c o m*/
    List<FileItem> items = null;

    try {
        List<FileItem> temp = upload.parseRequest(request);
        items = temp;
    } catch (FileUploadException e) {
        writeResponse(response, Constant.ICON_UPLOAD_RESPONSE_FAILED_TO_PARSE_REQUEST);
        return;
    }

    String userCode = null;
    BufferedImage inputImage = null;
    long originalFileSize = 0;

    for (FileItem item : items) {
        if (item.isFormField()) {
            String key = item.getFieldName();
            String value = item.getString();

            if (key.equals(Constant.FORM_NAME_USER_CODE)) {
                userCode = value;
            }

            continue;
        }

        // ??
        originalFileSize = item.getSize();
        try (InputStream inputStream = item.getInputStream()) {
            inputImage = ImageIO.read(inputStream);
        } catch (IOException e) {
            writeResponse(response, Constant.ICON_UPLOAD_RESPONSE_FAILED_TO_DETECT_IMAGE_FILE_TYPE);
            return;
        }

        if (inputImage == null) {
            writeResponse(response, Constant.ICON_UPLOAD_RESPONSE_FAILED_TO_DETECT_IMAGE_FILE_TYPE);
            return;
        }
    }

    if (userCode == null || inputImage == null) {
        writeResponse(response, Constant.ICON_UPLOAD_RESPONSE_REQUEST_FORMAT_ERROR);
        return;
    }

    String extension = "jpg";
    String fileTitle = Utility.createFileName();
    String fileName = fileTitle + "." + extension;

    // 
    // TODO(nodchip): ?
    int size = Constant.ICON_SIZE * 2;
    ImageFilter imageFilter = new AreaAveragingScaleFilter(size, size);
    Image middleImage = new Canvas().createImage(new FilteredImageSource(inputImage.getSource(), imageFilter));
    BufferedImage outputImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    outputImage.createGraphics().drawImage(middleImage, 0, 0, size, size, null);

    // ???
    new File(Constant.ICON_FOLDER_PATH).mkdirs();
    File outputFile = new File(Constant.ICON_FOLDER_PATH, fileName);
    ImageIO.write(outputImage, "jpg", outputFile);

    logger.log(Level.INFO, String.format("%d bytes -> %d bytes (%s)", originalFileSize, outputFile.length(),
            outputFile.getPath()));

    // ???
    int userId = Integer.parseInt(userCode);
    PacketUserData userData;
    try {
        userData = database.getUserData(userId);
    } catch (DatabaseException e) {
        logger.log(Level.WARNING, "????????", e);
        throw new ServletException(e);
    }
    File oldFile = new File(Constant.ICON_FOLDER_PATH, userData.imageFileName);
    if (oldFile.isFile() && !oldFile.getName().equals(Constant.ICON_NO_IMAGE)) {
        oldFile.delete();
    }
    userData.imageFileName = fileName;
    try {
        database.setUserData(userData);
    } catch (DatabaseException e) {
        logger.log(Level.WARNING, "???????", e);
        throw new ServletException(e);
    }

    // ????
    writeResponse(response, Constant.ICON_UPLOAD_RESPONSE_OK);
}