Example usage for java.awt Graphics fillRect

List of usage examples for java.awt Graphics fillRect

Introduction

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

Prototype

public abstract void fillRect(int x, int y, int width, int height);

Source Link

Document

Fills the specified rectangle.

Usage

From source file:ChartPanel.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (values == null || values.length == 0)
        return;//  w ww  . ja v  a  2  s.com
    double minValue = 0;
    double maxValue = 0;
    for (int i = 0; i < values.length; i++) {
        if (minValue > values[i])
            minValue = values[i];
        if (maxValue < values[i])
            maxValue = values[i];
    }

    Dimension d = getSize();
    int clientWidth = d.width;
    int clientHeight = d.height;
    int barWidth = clientWidth / values.length;

    Font titleFont = new Font("SansSerif", Font.BOLD, 20);
    FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
    Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
    FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);

    int titleWidth = titleFontMetrics.stringWidth(title);
    int y = titleFontMetrics.getAscent();
    int x = (clientWidth - titleWidth) / 2;
    g.setFont(titleFont);
    g.drawString(title, x, y);

    int top = titleFontMetrics.getHeight();
    int bottom = labelFontMetrics.getHeight();
    if (maxValue == minValue)
        return;
    double scale = (clientHeight - top - bottom) / (maxValue - minValue);
    y = clientHeight - labelFontMetrics.getDescent();
    g.setFont(labelFont);

    for (int i = 0; i < values.length; i++) {
        int valueX = i * barWidth + 1;
        int valueY = top;
        int height = (int) (values[i] * scale);
        if (values[i] >= 0)
            valueY += (int) ((maxValue - values[i]) * scale);
        else {
            valueY += (int) (maxValue * scale);
            height = -height;
        }

        g.setColor(Color.red);
        g.fillRect(valueX, valueY, barWidth - 2, height);
        g.setColor(Color.black);
        g.drawRect(valueX, valueY, barWidth - 2, height);
        int labelWidth = labelFontMetrics.stringWidth(names[i]);
        x = i * barWidth + (barWidth - labelWidth) / 2;
        g.drawString(names[i], x, y);
    }
}

From source file:org.processmining.analysis.performance.dottedchart.ui.DottedChartPanel.java

/**
 * paints this log item panel and all contained log items as specified.
 * //from w  w w.  j av  a 2 s.co  m
 * @param g
 *            the graphics object used for painting
 */
public void paintComponent(Graphics grx) {
    selectedIDIndices.clear(); // for exporting
    bDrawLine = dca.getSettingPanel().isDrawLine();
    // todo
    bBottleneck = dca.getSettingPanel().isBottleneck();
    bBottleneckforInstances = dca.getSettingPanel().isBottleneckforInstance();
    double percentileL = dcModel.getOverallStatistics().getPercentile(dca.getSettingPanel().getPercentileL());
    double percentileU = dcModel.getOverallStatistics().getPercentile(dca.getSettingPanel().getPercentileU());

    Graphics gr = grx.create();

    if (this.isOpaque()) {
        gr.setColor(colorBg);
        gr.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint the time indicator equipped component lane
    paintComponentLane(gr);

    // calculate are to be painted
    int height = (int) ((double) (getHeight() - (2 * border)));
    int unitHeight = height / getHashMapSize();
    int currentTop = 0;

    // paint items
    if (dcModel.getItemMap().size() > 0) {
        String key = null;
        AbstractLogUnit item = null;
        // iterate through sets
        int index = 0;
        for (Iterator itSets = dcModel.getSortedKeySetList().iterator(); itSets.hasNext();) {
            key = (String) itSets.next();
            // if key is not in instanceIDs, skip..
            if (dcModel.getTypeHashMap().equals(ST_INST) && !dcModel.getInstanceTypeToKeep().contains(key))
                continue;

            currentTop = unit2Cord(index) + unitHeight / 2;

            LogUnitList tempUnitList = new LogUnitList();
            AbstractLogUnit olditem = null;

            // for bottleneck
            boolean bInstances = false;
            boolean flag = true;
            if (dcOptionPanel.getComponentType().equals(DottedChartPanel.ST_INST) && bBottleneckforInstances) {
                LogUnitList tempUnitList2;
                tempUnitList2 = ((LogUnitList) dcModel.getItemMap().get(key));
                double percentile2L = dcModel.getTimeStatistics().get(0)
                        .getPercentile(dca.getSettingPanel().getPercentileforInstanceL());
                double percentile2U = dcModel.getTimeStatistics().get(0)
                        .getPercentile(dca.getSettingPanel().getPercentileforInstanceU());
                long tempDuration = (tempUnitList2
                        .getRightBoundaryTimestamp(dcModel.getEventTypeToKeep(),
                                dcModel.getInstanceTypeToKeep())
                        .getTime()
                        - tempUnitList2.getLeftBoundaryTimestamp(dcModel.getEventTypeToKeep(),
                                dcModel.getInstanceTypeToKeep()).getTime());
                if (dcOptionPanel.getComponentType().equals(DottedChartPanel.ST_INST) && bBottleneckforInstances
                        && tempDuration >= percentile2L && tempDuration <= percentile2U)
                    bInstances = true;
            }
            // end for bottleneck ////////

            // iterate through items
            for (Iterator itItm = ((LogUnitList) dcModel.getItemMap().get(key)).iterator(); itItm.hasNext();) {
                item = (AbstractLogUnit) itItm.next();
                if (dcModel.getEventTypeToKeep() != null
                        && (!dcModel.getEventTypeToKeep().contains(item.getType()) || !dcModel
                                .getInstanceTypeToKeep().contains(item.getProcessInstance().getName())))
                    continue;
                if (bDrawLine && item.getType().equals(dca.getSettingPanel().getStartEvent()))
                    tempUnitList.addEvent(item);
                assignColorByItem(item, gr);
                clipL = (int) gr.getClipBounds().getMinX() - 1;
                clipR = (int) gr.getClipBounds().getMaxX() + 1;
                long clipLeftTs2 = coord2timeMillis(clipL);
                long clipRightTs2 = coord2timeMillis(clipR);
                // if line is added
                if (bDrawLine && item.getType().equals(dca.getSettingPanel().getEndEvent())) {
                    for (Iterator itr = tempUnitList.iterator(); itr.hasNext();) {
                        AbstractLogUnit item2 = (AbstractLogUnit) itr.next();
                        if (item2.getElement().equals(item.getElement())
                                && item2.getProcessInstance().equals(item.getProcessInstance())) {
                            paintItemLine(time2coord(item2.getCurrentTimeStamp()) + border, currentTop,
                                    time2coord(item.getCurrentTimeStamp()) + border, gr);
                            tempUnitList.removeEvent(item2);
                            break;
                        }
                    }
                }

                // if item is not shown on the screen, ship drawing
                if (item.getCurrentTimeStamp() == null || item.getCurrentTimeStamp().getTime() < clipLeftTs2
                        || item.getCurrentTimeStamp().getTime() > clipRightTs2)
                    continue;

                // for botteleneck
                if (dcOptionPanel.getComponentType().equals(DottedChartPanel.ST_INST) && bBottleneck
                        && olditem != null
                        && (item.getCurrentTimeStamp().getTime()
                                - olditem.getCurrentTimeStamp().getTime()) >= percentileL
                        && (item.getCurrentTimeStamp().getTime()
                                - olditem.getCurrentTimeStamp().getTime()) <= percentileU) {
                    paintItemLineBottleneck(time2coord(olditem.getCurrentTimeStamp()) + border, currentTop,
                            time2coord(item.getCurrentTimeStamp()) + border, gr);
                    this.paintHighligtedItem(time2coord(olditem.getCurrentTimeStamp()) + border, currentTop, gr,
                            assignShapeByItem(olditem));
                    this.paintHighligtedItem(time2coord(item.getCurrentTimeStamp()) + border, currentTop, gr,
                            assignShapeByItem(item));
                    this.addExportingList(item);
                    olditem = item;
                    continue;
                }
                // paint an item
                if (bInstances) {
                    this.paintHighligtedItem(time2coord(item.getCurrentTimeStamp()) + border, currentTop, gr,
                            assignShapeByItem(item));
                    if (flag) {
                        this.addExportingList(item);
                        flag = false;
                    }
                } else {
                    this.paintItem(time2coord(item.getCurrentTimeStamp()) + border, currentTop, gr,
                            assignShapeByItem(item));
                }
                olditem = item;
            }
            // move y point
            index++;
        }
    }
    // to do box for zoom
    if (p1 != null && p2 != null) {
        int x1 = Math.min(p1.x, p2.x);
        int y1 = Math.min(p1.y, p2.y);
        int width = Math.abs(p1.x - p2.x);
        height = Math.abs(p1.y - p2.y);
        grx.drawRect(x1, y1, width, height);
    }
    // for exporting
    if (selectedIDIndices.size() > 0) {
        int tempArray[] = new int[selectedIDIndices.size()];
        int i = 0;
        for (Iterator itr = selectedIDIndices.iterator(); itr.hasNext();) {
            tempArray[i++] = (int) ((Integer) itr.next());
        }
        dca.setSelectedInstanceIndicesfromScreen(tempArray);
    }
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

protected void drawPageError(Graphics grx) {
    grx.setColor(Color.white);/* ww w.  j  av  a  2 s  .c o  m*/
    grx.fillRect(0, 0, jasperPrint.getPageWidth() + 1, jasperPrint.getPageHeight() + 1);
}

From source file:com.openbravo.pos.util.JRViewer400.java

protected void drawPageError(Graphics grx) {
    PrintPageFormat pageFormat = getPageFormat();
    grx.setColor(Color.white);//from   w  w w  .  ja v a2  s.  co m
    grx.fillRect(0, 0, pageFormat.getPageWidth() + 1, pageFormat.getPageHeight() + 1);
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Generate an image replicating the users map in the browser.
 * //from  ww w. j  a  v a 2  s. c  o  m
 * @outFileFormat - Allowed types (png, gif, jpg, bmp)
 * @mapBounds - JSON constructed as {"bottom":"VALUE", "top":"VALUE", "left":"VALUE", "right":"VALUE"}
 * @mapSize - JSON constructed as {"width":"VALUE", "height":"VALUE"}
 * @activeBaseMap = JSON constructed as {"LAYER_SOURCE_TYPE":"VALUE"}
 */
@Override
public InputStream generateMapImageExport(String outFileFormat, String mapBounds, String mapSize,
        String activeBaseMap) {
    InputStream inStream = null;
    int width;
    int height;

    // Get dimensions of the map window (<div>)
    try {
        JSONObject mapSizeObj = new JSONObject(mapSize);
        width = mapSizeObj.getInt("width");
        height = mapSizeObj.getInt("height");
    } catch (JSONException e) {
        String error = "Could not parse map size.";
        throw new ProgrammingErrorException(error, e);
    }

    // Setup the base canvas to which we will add layers and map elements
    BufferedImage base = null;
    Graphics mapBaseGraphic = null;
    try {
        if (outFileFormat.toLowerCase().equals("png") || outFileFormat.toLowerCase().equals("gif")) {
            base = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        } else if (outFileFormat.equals("jpg") || outFileFormat.toLowerCase().equals("bmp")) {
            base = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        }

        // Create the base canvas that all other map elements will be draped on top of
        mapBaseGraphic = base.getGraphics();
        mapBaseGraphic.setColor(Color.white);
        mapBaseGraphic.fillRect(0, 0, width, height);
        mapBaseGraphic.drawImage(base, 0, 0, null);

        // Ordering the layers from the default map
        DashboardLayer[] orderedLayers = this.getOrderedLayers();

        // Add layers to the base canvas
        BufferedImage layerCanvas = getLayersExportCanvas(width, height, orderedLayers, mapBounds);

        // Get base map
        String baseType = null;
        try {
            JSONObject activeBaseObj = new JSONObject(activeBaseMap);
            baseType = activeBaseObj.getString("LAYER_SOURCE_TYPE");
        } catch (JSONException e) {
            String error = "Could not active base map JSON.";
            throw new ProgrammingErrorException(error, e);
        }

        // Get bounds of the map
        if (baseType.length() > 0) {
            String bottom;
            String top;
            String right;
            String left;
            try {
                JSONObject mapBoundsObj = new JSONObject(mapBounds);
                bottom = mapBoundsObj.getString("bottom");
                top = mapBoundsObj.getString("top");
                right = mapBoundsObj.getString("right");
                left = mapBoundsObj.getString("left");
            } catch (JSONException e) {
                String error = "Could not parse map bounds.";
                throw new ProgrammingErrorException(error, e);
            }

            BufferedImage baseMapImage = this.getBaseMapCanvas(width, height, left, bottom, right, top,
                    baseType);

            if (baseMapImage != null) {
                mapBaseGraphic.drawImage(baseMapImage, 0, 0, null);
            }
        }

        // Offset the layerCanvas so that it is center
        int widthOffset = (int) ((width - layerCanvas.getWidth()) / 2);
        int heightOffset = (int) ((height - layerCanvas.getHeight()) / 2);

        mapBaseGraphic.drawImage(layerCanvas, widthOffset, heightOffset, null);

        // Add legends to the base canvas
        BufferedImage legendCanvas = getLegendExportCanvas(width, height);
        mapBaseGraphic.drawImage(legendCanvas, 0, 0, null);
    } finally {
        ByteArrayOutputStream outStream = null;
        try {
            outStream = new ByteArrayOutputStream();
            ImageIO.write(base, outFileFormat, outStream);
            inStream = new ByteArrayInputStream(outStream.toByteArray());
        } catch (IOException e) {
            String error = "Could not write map image to the output stream.";
            throw new ProgrammingErrorException(error, e);
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    String error = "Could not close stream.";
                    throw new ProgrammingErrorException(error, e);
                }
            }
        }

        if (mapBaseGraphic != null) {
            mapBaseGraphic.dispose();
        }
    }

    return inStream;
}

From source file:es.emergya.ui.plugins.AdminPanel.java

/**
 * /*ww  w . j ava2s  . c o m*/
 * @param columnNames
 *            nombres de las columnas de la tabla
 * @param filterOptions
 *            lista de opciones de un combobox. Si esta vacio entonces es un
 *            textfield
 * @param noFiltrarAction
 * @param filtrarAction
 */
public void generateTable(String[] columnNames, Object[][] filterOptions,
        AdminPanel.NoFiltrarAction noFiltrarAction, AdminPanel.FiltrarAction filtrarAction) {

    if (columnNames == null) {
        columnNames = new String[] {};
    }
    if (filterOptions == null) {
        filterOptions = new Object[][] {};
    }

    String filterString = "[";
    for (Object[] o : filterOptions) {
        filterString += Arrays.toString(o) + " ";
    }
    filterString += "]";

    log.debug("generateTable( columnNames = " + Arrays.toString(columnNames) + ", filterOptions = "
            + filterString + ")");

    tablePanel.removeAll();
    int columnNamesLength = columnNames.length;
    if (!getCanDelete())
        columnNamesLength++;
    MyTableModel dataModel = new MyTableModel(1, columnNamesLength + 2) {

        private static final long serialVersionUID = 1348355328684460769L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column != 0 && !invisibleFilterCols.contains(column);
        }
    };
    filters = new JTable(dataModel) {

        private static final long serialVersionUID = -8266991359840905405L;

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);

            if (isCellEditable(row, column) && column != getColumnCount() - 1) {
                if (c instanceof JTextField) {
                    ((JTextField) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JComboBox) {
                    ((JComboBox) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JLabel) {
                    ((JLabel) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                }
            }
            return c;
        }
    };
    filters.setSurrendersFocusOnKeystroke(true);
    filters.setShowGrid(false);
    filters.setRowHeight(22);
    filters.setOpaque(false);

    for (Integer i = 0; i < filterOptions.length; i++) {
        final Object[] items = filterOptions[i];
        if (items != null && items.length > 1) {
            setComboBoxEditor(i, items);
        } else {
            final DefaultCellEditor defaultCellEditor = new DefaultCellEditor(new JTextField());
            defaultCellEditor.setClickCountToStart(1);
            filters.getColumnModel().getColumn(i + 1).setCellEditor(defaultCellEditor);
        }
    }

    filters.setRowSelectionAllowed(false);
    filters.setDragEnabled(false);
    filters.setColumnSelectionAllowed(false);
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());

    filters.setDefaultRenderer(Object.class, new DefaultTableRenderer() {
        private static final long serialVersionUID = -4811729559786534118L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (invisibleFilterCols.contains(column))
                c = new JLabel("");
            return c;
        }

    });

    filters.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            b.setBorderPainted(false);
            b.setContentAreaFilled(false);
            return b;
        }
    });
    filters.setDefaultRenderer(JLabel.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            return (JLabel) value;
        }
    });
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());
    filters.getModel().setValueAt(new JLabel(""), 0, 0);
    JButton jButton2 = new JButton(noFiltrarAction);
    JButton jButton = new JButton(filtrarAction);
    jButton.setBorderPainted(false);
    jButton2.setBorderPainted(false);
    jButton.setContentAreaFilled(false);
    jButton2.setContentAreaFilled(false);
    if (jButton.getIcon() != null)
        jButton.setPreferredSize(
                new Dimension(jButton.getIcon().getIconWidth(), jButton.getIcon().getIconHeight()));
    if (jButton2.getIcon() != null)
        jButton2.setPreferredSize(
                new Dimension(jButton2.getIcon().getIconWidth(), jButton2.getIcon().getIconHeight()));

    filters.getModel().setValueAt(jButton, 0, columnNamesLength - 1);
    filters.getColumnModel().getColumn(columnNamesLength - 1).setMinWidth(jButton.getWidth() + 24);
    filters.getModel().setValueAt(jButton2, 0, columnNamesLength);
    filters.getColumnModel().getColumn(columnNamesLength).setMinWidth(jButton2.getWidth() + 14);
    cuenta.setHorizontalAlignment(JLabel.CENTER);
    cuenta.setText("?/?");
    filters.getModel().setValueAt(cuenta, 0, columnNamesLength + 1);

    tablePanel.add(filters, BorderLayout.NORTH);

    Vector<String> headers = new Vector<String>();
    headers.add("");
    headers.addAll(Arrays.asList(columnNames));
    MyTableModel model = new MyTableModel(headers, 0);
    table = new JTable(model) {

        private static final long serialVersionUID = 949284378605881770L;
        private int highLightedRow = -1;
        private Rectangle dirtyRegion = null;

        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            try {
                if (AdminPanel.this.myRendererColoring != null)
                    c.setBackground(AdminPanel.this.myRendererColoring
                            .getColor(AdminPanel.this.table.getValueAt(row, 1)));
            } catch (Throwable t) {
                log.error("Error al colorear la celda: " + t);
            }
            return c;
        }

        @Override
        protected void processMouseMotionEvent(MouseEvent e) {
            try {
                int row = rowAtPoint(e.getPoint());
                Graphics g = getGraphics();
                if (row == -1) {
                    highLightedRow = -1;
                }

                // row changed
                if (highLightedRow != row) {
                    if (null != dirtyRegion) {
                        paintImmediately(dirtyRegion);
                    }
                    for (int j = 0; j < getRowCount(); j++) {
                        if (row == j) {
                            // highlight
                            Rectangle firstRowRect = getCellRect(row, 0, false);
                            Rectangle lastRowRect = getCellRect(row, getColumnCount() - 1, false);
                            dirtyRegion = firstRowRect.union(lastRowRect);
                            g.setColor(new Color(0xff, 0xff, 0, 100));
                            g.fillRect((int) dirtyRegion.getX(), (int) dirtyRegion.getY(),
                                    (int) dirtyRegion.getWidth(), (int) dirtyRegion.getHeight());
                            highLightedRow = row;
                        }

                    }
                }
            } catch (Exception ex) {
            }
            super.processMouseMotionEvent(e);
        }
    };

    table.setRowHeight(22);

    table.setOpaque(false);
    // table.setAutoCreateRowSorter(true);

    table.setDragEnabled(false);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);

    table.setDefaultEditor(JButton.class, new JButtonCellEditor());
    table.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            if (b != null) {
                b.setBorderPainted(false);
                b.setContentAreaFilled(false);
            }
            return b;
        }
    });

    JScrollPane jScrollPane = new JScrollPane(table);
    jScrollPane.setOpaque(false);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.getViewport().setOpaque(false);
    tablePanel.add(jScrollPane, BorderLayout.CENTER);
}

From source file:org.tinymediamanager.ui.components.ImageLabel.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (scaledImage != null) {
        int originalWidth = scaledImage.getWidth(null);
        int originalHeight = scaledImage.getHeight(null);

        // calculate new height/width
        int newWidth = 0;
        int newHeight = 0;

        int offsetX = 0;
        int offsetY = 0;

        if (drawBorder && !drawFullWidth) {
            Point size = ImageCache.calculateSize(this.getWidth() - 8, this.getHeight() - 8, originalWidth,
                    originalHeight, true);

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x - 8;
            }/*from   w  ww. j  av a  2s  . c  o  m*/

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y - 8;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x - 8) / 2;
                offsetY = (this.getHeight() - size.y - 8) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            g.setColor(Color.BLACK);
            g.drawRect(offsetX, offsetY, size.x + 7, size.y + 7);
            g.setColor(Color.WHITE);
            g.fillRect(offsetX + 1, offsetY + 1, size.x + 6, size.y + 6);
            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX + 4, offsetY + 4, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX + 4, offsetY + 4, newWidth, newHeight, this);
        } else {
            Point size = null;
            if (drawFullWidth) {
                size = new Point(this.getWidth(), this.getWidth() * originalHeight / originalWidth);
            } else {
                size = ImageCache.calculateSize(this.getWidth(), this.getHeight(), originalWidth,
                        originalHeight, true);
            }

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x;
            }

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x) / 2;
                offsetY = (this.getHeight() - size.y) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX, offsetY, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX, offsetY, newWidth, newHeight, this);
        }
    } else {
        // draw border and background
        if (drawBorder) {
            g.setColor(Color.BLACK);
            g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
            if (getParent().isOpaque()) {
                g.setColor(getParent().getBackground());
                g.fillRect(1, 1, this.getWidth() - 2, this.getHeight() - 2);
            }
        }

        // calculate diagonal
        int diagonalSize = (int) Math
                .sqrt(this.getWidth() * this.getWidth() + this.getHeight() * this.getHeight());

        // draw text
        String text = "";
        if (alternativeText != null) {
            text = alternativeText;
        } else {
            text = BUNDLE.getString("image.nonefound"); //$NON-NLS-1$
        }
        if (!getParent().isOpaque()) {
            text = "";
        }
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        AffineTransform orig = g2.getTransform();
        AffineTransform at = new AffineTransform(orig);
        at.translate(0, this.getHeight());
        at.rotate(this.getWidth(), -this.getHeight());
        g2.setTransform(at);
        g2.setColor(Color.BLACK);
        g2.setFont(FONT);

        FontMetrics fm = g2.getFontMetrics();
        int x = (diagonalSize - fm.stringWidth(text)) / 2;
        int y = (fm.getAscent() - fm.getDescent()) / 2;

        g2.drawString(text, x, y);
        // g2.drawLine(0, 0, diagonalSize, 0);
        at.translate(0, -this.getHeight());
        g2.setTransform(orig);
    }
}

From source file:replicatorg.app.ui.panels.ControlPanel.java

public ControlPanel() {
    super(Base.getMainWindow(), Dialog.ModalityType.MODELESS);
    initComponents();/*from  w  w  w .j a v a 2 s  .c om*/
    Base.writeLog("Control panel opened...", this.getClass());
    setTextLanguage();
    super.centerOnScreen();
    super.enableDrag();
    evaluateInitialConditions();

    this.tempPanel.setLayout(new GridBagLayout());
    this.tempPanel.add(this.makeChart());

    //Sets legend colors
    BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(t0MeasuredColor);
    g.fillRect(0, 0, 10, 10);
    Icon icon1 = new ImageIcon(image);

    this.colorCurrentTemp.setIcon(icon1);
    this.colorCurrentTemp.setText("");

    BufferedImage image2 = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    Graphics g2 = image2.getGraphics();
    g2.setColor(t0TargetColor);
    g2.fillRect(0, 0, 10, 10);
    Icon icon2 = new ImageIcon(image2);

    this.colorTargetTemp.setIcon(icon2);
    this.colorTargetTemp.setText("");

    if (connectedPrinter == PrinterInfo.BEETHEFIRST) {
        jSliderBlowerSpeed.setMaximum(1);
        jSliderBlowerSpeed.setMinorTickSpacing(0);
        jSliderBlowerSpeed.setMajorTickSpacing(1);

        jSliderExtruderSpeed.setEnabled(false);
    }

    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowOpened(WindowEvent e) {
            consoleInput.requestFocus();
        }

        @Override
        public void windowClosed(WindowEvent e) {
            if (movButtonHoldDown != null && movButtonHoldDown.isRunning()) {
                movButtonHoldDown.stop();
            }
            driver.dispatchCommand("M1110 S0", COM.NO_RESPONSE);

            if (loggingTemperature == false) {
                disposeThread.cancel();
            }
            inputValidationThread.cancel();
            getInitialValuesThread.cancel();
        }
    });
}

From source file:CopyAreaPerformance.java

protected void paintComponent(Graphics g) {
    long startTime = System.nanoTime();
    // prevVX is set to -10000 when first enabled
    if (useCopyArea && prevVX > -9999) {
        // Most of this code determines the proper areas to copy and clip
        int scrollX = viewX - prevVX;
        int scrollY = viewY - prevVY;
        int copyFromY, copyFromX;
        int clipFromY, clipFromX;
        if (scrollX == 0) {
            // vertical scroll
            if (scrollY < 0) {
                copyFromY = 0;/*from  www.ja  va2  s.c o m*/
                clipFromY = 0;
            } else {
                copyFromY = scrollY;
                clipFromY = getHeight() - scrollY;
            }
            // copy the old content, set the clip to the new area
            g.copyArea(0, copyFromY, getWidth(), getHeight() - Math.abs(scrollY), 0, -scrollY);
            g.setClip(0, clipFromY, getWidth(), Math.abs(scrollY));
        } else {
            // horizontal scroll
            if (scrollX < 0) {
                copyFromX = 0;
                clipFromX = 0;
            } else {
                copyFromX = scrollX;
                clipFromX = getWidth() - scrollX;
            }
            // copy the old content, set the clip to the new area
            g.copyArea(copyFromX, 0, getWidth() - Math.abs(scrollX), getHeight(), -scrollX, 0);
            g.setClip(clipFromX, 0, Math.abs(scrollX), getHeight());
        }
    }
    // Track previous view position for next scrolling operation
    prevVX = viewX;
    prevVY = viewY;
    // Get the clip in case we need it later
    Rectangle clipRect = g.getClip().getBounds();
    int clipL = (int) (clipRect.getX());
    int clipT = (int) (clipRect.getY());
    int clipR = (int) (clipRect.getMaxX());
    int clipB = (int) (clipRect.getMaxY());
    g.setColor(Color.WHITE);
    g.fillRect(clipL, clipT, (int) clipRect.getWidth(), (int) clipRect.getHeight());
    for (int column = 0; column < 256; ++column) {
        int x = column * (SMILEY_SIZE + PADDING) - viewX;
        if (useClip) {
            if (x > clipR || (x + (SMILEY_SIZE + PADDING)) < clipL) {
                // trivial reject; outside to the left or right
                continue;
            }
        }
        for (int row = 0; row < 256; ++row) {
            int y = row * (SMILEY_SIZE + PADDING) - viewY;
            if (useClip) {
                if (y > clipB || (y + (SMILEY_SIZE + PADDING)) < clipT) {
                    // trivial reject; outside to the top or bottom
                    continue;
                }
            }
            Color faceColor = new Color(column, row, 0);
            drawSmiley(g, faceColor, x, y);
        }
    }
    long stopTime = System.nanoTime();
    System.out.println("Painted in " + ((stopTime - startTime) / 1000000) + " ms");
}

From source file:com.projity.contrib.calendar.JXXMonthView.java

private void drawDay(boolean colored, boolean flagged, boolean today, Graphics g, String text, int x, int y) {
    Color defaultColor = g.getColor();
    Font oldFont = getFont();//from ww  w.ja va  2s .  c  o m
    if (colored) {
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(_bounds.x, _bounds.y, _bounds.width, _bounds.height);
        g.setColor(defaultColor);
    }
    if (today)
        g.setColor(Color.BLUE);
    if (flagged) {
        g.setColor(Color.RED);
        g.setFont(_derivedFont);
    }
    g.drawString(text, x, y);
    g.setColor(defaultColor);
    g.setFont(oldFont);
}