Example usage for javax.swing JPanel paint

List of usage examples for javax.swing JPanel paint

Introduction

In this page you can find the example usage for javax.swing JPanel paint.

Prototype

public void paint(Graphics g) 

Source Link

Document

Invoked by Swing to draw components.

Usage

From source file:gui.images.CodebookVectorProfilePanel.java

/**
 * Generate a BufferedImage that would correspond to a JPanel. Images are
 * faster to show than interactive components if many components need to be
 * presented./*from w  ww  . j  a  v  a2  s  .  c om*/
 *
 * @param panel JPanel object.
 * @return BufferedImage of how the content in the provided panel would be
 * rendered.
 */
public BufferedImage createImage(JPanel panel) {
    int width = panel.getSize().width;
    int height = panel.getSize().height;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    panel.paint(g);
    return bi;
}

From source file:probe.com.model.util.vaadintoimageutil.HeatmapSwingComponent.java

public String generateHeatmap(String[] rows, String[] columns, String[][] data) {

    JPanel heatmapPanelLayout = new JPanel();
    heatmapPanelLayout.setLayout(null);/*from   w  w w . j  ava2 s . c  o m*/
    heatmapPanelLayout.setVisible(true);
    heatmapPanelLayout.setBorder(new LineBorder(Color.BLACK));
    int width = (columns.length + 1) * 50;
    int height = (rows.length + 1) * 50;
    heatmapPanelLayout.setSize(width, height);
    JPanel cornerCell = initCell("#ffffff", 0, 0);
    int x = 50;
    int y = 0;
    heatmapPanelLayout.add(cornerCell);

    for (String headerCell : columns) {
        JPanel cell = initCell(headerCell, x, y);
        x += 50;
        heatmapPanelLayout.add(cell);

    }
    y = 50;
    for (String headerCell : rows) {
        JPanel cell = initCell(headerCell, 0, y);
        y += 50;
        heatmapPanelLayout.add(cell);

    }
    x = 50;
    y = 50;
    for (String[] row : data) {
        for (String color : row) {
            JPanel cell = initCell(color, x, y);
            heatmapPanelLayout.add(cell);
            x += 50;
        }
        x = 50;
        y += 50;
    }

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    heatmapPanelLayout.paint(graphics);
    //        super.paint(graphics);
    byte[] imageData = null;

    try {

        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, new Float(0.084666f));
        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;
    //
    //        JFrame frame = new JFrame();
    //        frame.setSize(1000, 1000);
    //        frame.add(heatmapPanelLayout);
    //        frame.setVisible(true);

    //        return "";
}

From source file:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.heatmap.HeatMapImgGenerator.java

public String generateHeatmap(String[] rows, String[] columns, String[][] data) {

    JPanel heatmapPanelLayout = new JPanel();
    heatmapPanelLayout.setLayout(null);/*from   w  w  w  . j  av  a  2s . c  o m*/
    heatmapPanelLayout.setVisible(true);

    int width = (columns.length + 1) * 50;
    int height = (rows.length + 1) * 50;
    heatmapPanelLayout.setSize(width, height);
    JPanel cornerCell = initCell("#ffffff", 0, 0);
    int x = 50;
    int y = 0;
    heatmapPanelLayout.add(cornerCell);

    for (String headerCell : columns) {
        JPanel cell = initCell(headerCell, x, y);
        x += 50;
        heatmapPanelLayout.add(cell);

    }
    y = 50;
    for (String headerCell : rows) {
        JPanel cell = initCell(headerCell, 0, y);
        y += 50;
        heatmapPanelLayout.add(cell);

    }
    x = 50;
    y = 50;
    for (String[] row : data) {
        for (String color : row) {
            JPanel cell = initCell(color, x, y);
            heatmapPanelLayout.add(cell);
            x += 50;
        }
        x = 50;
        y += 50;
    }

    BufferedImage image = new BufferedImage(width + 10, height + 10, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    graphics.setBackground(Color.WHITE);
    heatmapPanelLayout.paint(graphics);
    byte[] imageData = null;

    try {

        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, new Float(0.084666f));
        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;

}

From source file:velocitekProStartAnalyzer.MainWindow.java

private void saveMapAsPng(JPanel panel) {

    btnSaveMapAsPng.addActionListener(new ActionListener() {

        @Override//from  ww  w .  ja  va  2  s  .c o  m
        public void actionPerformed(ActionEvent e) {
            fileChooser.setDialogTitle("Specify a file to save");
            int userSelection = fileChooser.showSaveDialog(frame);
            BufferedImage bufImage = new BufferedImage(panel.getSize().width, panel.getSize().height,
                    BufferedImage.TYPE_INT_RGB);
            panel.paint(bufImage.createGraphics());
            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File fileToSave = new File(fileChooser.getSelectedFile() + ".png");
                System.out.println("Save as file: " + fileToSave.getAbsolutePath());
                try {
                    fileToSave.createNewFile();
                    ImageIO.write(bufImage, "png", fileToSave);
                    statusLabel.setText("Map Screenshot Saved as: " + fileToSave.getName());
                } catch (Exception ex) {
                    statusLabel.setText("There was an error during save, aborted");
                }
            }
        }
    });

    btnSaveMapAsPngForChart.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            fileChooser.setDialogTitle("Specify a file to save");
            int userSelection = fileChooser.showSaveDialog(frame);
            BufferedImage bufImage = new BufferedImage(panel.getSize().width, panel.getSize().height,
                    BufferedImage.TYPE_INT_RGB);
            panel.paint(bufImage.createGraphics());
            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File fileToSave = new File(fileChooser.getSelectedFile() + ".png");
                System.out.println("Save as file: " + fileToSave.getAbsolutePath());
                try {
                    fileToSave.createNewFile();
                    ImageIO.write(bufImage, "png", fileToSave);
                    statusLabel.setText("Map Screenshot Saved as: " + fileToSave.getName());
                } catch (Exception ex) {
                    statusLabel.setText("There was an error during save, aborted");
                }
            }
        }
    });

    // File imageFile = new File("C:\\MJ_NETCLINIC\\asd.png");

}

From source file:org.broad.igv.hic.MainWindow.java

private JMenuBar createMenuBar(final JPanel hiCPanel) {

    JMenuBar menuBar = new JMenuBar();

    //======== fileMenu ========
    JMenu fileMenu = new JMenu("File");

    //---- loadMenuItem ----
    JMenuItem loadMenuItem = new JMenuItem();
    loadMenuItem.setText("Load...");
    loadMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadMenuItemActionPerformed(e);
        }/*from  w  w w .  ja  v a2  s.com*/
    });
    fileMenu.add(loadMenuItem);

    //---- loadFromURL ----
    JMenuItem loadFromURL = new JMenuItem();
    JMenuItem getEigenvector = new JMenuItem();
    final JCheckBoxMenuItem viewDNAseI;

    loadFromURL.setText("Load from URL ...");
    loadFromURL.setName("loadFromURL");
    loadFromURL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadFromURLActionPerformed(e);
        }
    });
    fileMenu.add(loadFromURL);
    fileMenu.addSeparator();

    // Pre-defined datasets.  TODO -- generate from a file
    addPredefinedLoadItems(fileMenu);

    JMenuItem saveToImage = new JMenuItem();
    saveToImage.setText("Save to image");
    saveToImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BufferedImage image = (BufferedImage) createImage(1000, 1000);
            Graphics g = image.createGraphics();
            hiCPanel.paint(g);

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File("image.png"));
            int actionDialog = fc.showSaveDialog(null);
            if (actionDialog == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists()) {
                    actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
                    if (actionDialog == JOptionPane.NO_OPTION || actionDialog == JOptionPane.CANCEL_OPTION)
                        return;
                }
                try {
                    // default if they give no format or invalid format
                    String fmt = "jpg";
                    int ind = file.getName().indexOf(".");
                    if (ind != -1) {
                        String ext = file.getName().substring(ind + 1);
                        String[] strs = ImageIO.getWriterFormatNames();
                        for (String aStr : strs)
                            if (ext.equals(aStr))
                                fmt = ext;
                    }
                    ImageIO.write(image.getSubimage(0, 0, 600, 600), fmt, file);
                } catch (IOException ie) {
                    System.err.println("Unable to write " + file + ": " + ie);
                }
            }
        }
    });
    fileMenu.add(saveToImage);
    getEigenvector = new JMenuItem("Get principal eigenvector");
    getEigenvector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getEigenvectorActionPerformed(e);
        }
    });
    fileMenu.add(getEigenvector);
    //---- exit ----
    JMenuItem exit = new JMenuItem();
    exit.setText("Exit");
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            exitActionPerformed(e);
        }
    });
    fileMenu.add(exit);

    menuBar.add(fileMenu);

    //======== Tracks menu ========

    JMenu tracksMenu = new JMenu("Tracks");

    viewEigenvector = new JCheckBoxMenuItem("View Eigenvector...");
    viewEigenvector.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewEigenvector.isSelected()) {
                if (eigenvectorTrack == null) {
                    eigenvectorTrack = new EigenvectorTrack("eigen", "Eigenvectors");
                }
                updateEigenvectorTrack();
            } else {
                trackPanel.setEigenvectorTrack(null);
                if (HiCTrackManager.getLoadedTracks().isEmpty()) {
                    trackPanel.setVisible(false);
                }
            }
        }
    });
    viewEigenvector.setEnabled(false);
    tracksMenu.add(viewEigenvector);

    JMenuItem loadItem = new JMenuItem("Load...");
    loadItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadHostedTrack(MainWindow.this);
        }

    });
    tracksMenu.add(loadItem);

    JMenuItem loadFromFileItem = new JMenuItem("Load from file...");
    loadFromFileItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadTrackFromFile(MainWindow.this);
        }

    });
    tracksMenu.add(loadFromFileItem);

    menuBar.add(tracksMenu);

    //======== Extras menu ========
    JMenu extrasMenu = new JMenu("Extras");

    JMenuItem dumpPearsons = new JMenuItem("Dump pearsons matrix ...");
    dumpPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            BasicMatrix pearsons = hic.zd.getPearsons();
            try {
                String chr1 = hic.getChromosomes()[hic.zd.getChr1()].getName();
                String chr2 = hic.getChromosomes()[hic.zd.getChr2()].getName();
                int binSize = hic.zd.getBinSize();
                File initFile = new File("pearsons_" + chr1 + "_" + "_" + chr2 + "_" + binSize + ".bin");
                File f = FileDialogUtils.chooseFile("Save pearsons", null, initFile, FileDialogUtils.SAVE);
                if (f != null) {
                    ScratchPad.dumpPearsonsBinary(pearsons, chr1, chr2, hic.zd.getBinSize(), f);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });

    JMenuItem dumpEigenvector = new JMenuItem("Dump eigenvector ...");
    dumpEigenvector.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                ScratchPad.dumpEigenvector(hic);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(dumpEigenvector);

    JMenuItem readPearsons = new JMenuItem("Read pearsons...");
    readPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                File f = FileDialogUtils.chooseFile("Pearsons file (Yunfan format)");
                if (f != null) {
                    BasicMatrix bm = ScratchPad.readPearsons(f.getAbsolutePath());

                    hic.zd.setPearsons(bm);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(readPearsons);

    extrasMenu.add(dumpPearsons);
    menuBar.add(extrasMenu);

    return menuBar;
}

From source file:test.uk.co.modularaudio.rackgeneration.GenerateReleaseComponentImages.java

private void generateImageForDefinition(final MadDefinition<?, ?> def)
        throws DatastoreException, RecordNotFoundException, MadProcessingException, IOException {
    final Map<MadParameterDefinition, String> emptyParams = new HashMap<MadParameterDefinition, String>();
    final MadInstance<?, ?> aui = componentService.createInstanceFromDefinition(def, emptyParams,
            def.getName());/*from  w  w w .  j a v a  2 s.  c  o  m*/

    final IMadUiInstance<?, ?> auui = componentUiService.createUiInstanceForMad(aui);

    final RackComponent rackComponent = new RackComponent(def.getName(), aui, auui);
    final AbstractGuiAudioComponent frontComponent = guiComponentFactoryService
            .createFrontGuiComponent(rackComponent);

    final JFrame testFrame = new JFrame();
    final JPanel testPanel = new JPanel();
    final MigLayout layout = new MigLayout("insets 0, gap 0, fill");
    testPanel.setLayout(layout);
    testPanel.setOpaque(false);

    final Span cellSpan = auui.getCellSpan();
    final Dimension gridSize = GuiRackPanel.FRONT_GRID_SIZE;
    final int width = cellSpan.x * gridSize.width;
    final int height = cellSpan.y * gridSize.height;
    final Dimension componentSize = new Dimension(width, height);

    final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2d = bi.createGraphics();

    frontComponent.setBounds(new Rectangle(0, 0, width, height));
    frontComponent.setSize(componentSize);
    frontComponent.setMinimumSize(componentSize);

    testPanel.add(frontComponent);
    testFrame.add(testPanel);

    testPanel.validate();
    testFrame.pack();

    testFrame.setVisible(true);
    try {
        Thread.sleep(100);
    } catch (final InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    testPanel.paint(g2d);
    testFrame.setVisible(false);
    testFrame.dispose();

    final File defOutputFile = new File("tmpoutput/" + def.getId() + ".png");
    ImageIO.write(bi, "png", defOutputFile);

    componentUiService.destroyUiInstance(auui);
    componentService.destroyInstance(aui);
}