Example usage for java.awt Graphics drawString

List of usage examples for java.awt Graphics drawString

Introduction

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

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, int x, int y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the java.awt.font.TextAttribute TextAttribute class.

Usage

From source file:ubic.basecode.graphics.MatrixDisplay.java

/**
 * @param g//from w w w.ja  v a2  s .  com
 * @param d
 */
protected void drawScaleBar(Graphics g, Dimension d, double displayMin, double displayMax) {
    /*
     * FIXME this is all a bit of a hack
     */
    g.setColor(Color.white);
    int upperLeftScalebarGutter = 10;
    int scaleBarHeight = 10; // these and text height have to total < SCALE_BAR_ROOM
    int desiredScaleBarLength = (int) Math.min(DEFAULT_SCALE_BAR_WIDTH, d.getWidth());

    if (desiredScaleBarLength < 10) {
        return;
    }

    g.drawRect(upperLeftScalebarGutter, upperLeftScalebarGutter, desiredScaleBarLength,
            upperLeftScalebarGutter);
    JGradientLabel scalebar = new JGradientLabel(new ColorMap(this.getColorMap()).getPalette());
    scalebar.setBackground(Color.white);
    scalebar.setSize(new Dimension(desiredScaleBarLength, scaleBarHeight));
    int actualWidth = scalebar.drawAtLocation(g, upperLeftScalebarGutter, upperLeftScalebarGutter);
    g.setColor(Color.black);
    g.drawString(String.format("%.2g", displayMin), 0,
            upperLeftScalebarGutter + scaleBarHeight + m_fontGutter + g.getFontMetrics().getHeight());
    g.drawString(String.format("%.2g", displayMax), actualWidth,
            upperLeftScalebarGutter + scaleBarHeight + m_fontGutter + g.getFontMetrics().getHeight());
    g.drawRect(upperLeftScalebarGutter, upperLeftScalebarGutter, actualWidth, scaleBarHeight);
}

From source file:ubic.basecode.graphics.MatrixDisplay.java

/**
 * Draws row names (horizontally)//from   w ww. j a  v a2 s .  com
 * 
 * @param g Graphics
 * @param showScalebar
 */
protected void drawRowNames(Graphics g, boolean showScalebar) {

    if (colorMatrix == null)
        return;

    Color oldColor = g.getColor();

    g.setColor(Color.white);
    g.fillRect(colorMatrix.getColumnCount() * m_cellSize.width, 0,
            colorMatrix.getColumnCount() * m_cellSize.width, this.getHeight());

    int rowCount = colorMatrix.getRowCount();
    int xLabelStartPosition = colorMatrix.getColumnCount() * m_cellSize.width + m_labelGutter;
    g.setColor(Color.black);
    g.setFont(m_labelFont);

    for (int i = 0; i < rowCount; i++) {
        int y = i * m_cellSize.height + m_columnLabelHeight + m_labelGutter;
        int yLabelPosition = y + m_cellSize.height - m_fontGutter;
        if (showScalebar) {
            yLabelPosition += SCALE_BAR_ROOM;
        }

        Object rowName = colorMatrix.getRowName(i);
        if (null == rowName) {
            rowName = "Undefined";
        }

        g.drawString(rowName.toString(), xLabelStartPosition, yLabelPosition);

    } // end drawing row names
    g.setColor(oldColor);
}

From source file:tilt.image.page.Line.java

/**
 * Draw the line on the image for debugging
 * @param g the graphics environment to draw in
 * @param n the number of the line/*from   w ww .  j  av  a  2  s  . com*/
 */
public void draw(Graphics g, int n) {
    Point p1, p2 = null;
    for (int i = 0; i < points.size(); i++) {
        p1 = p2;
        p2 = points.get(i);
        if (p1 != null) {
            int x1 = Math.round(p1.x);
            int y1 = Math.round(p1.y);
            int x2 = Math.round(p2.x);
            int y2 = Math.round(p2.y);
            if (!rogue) {
                g.drawLine(x1, y1, x2, y2);
            } else {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(3));
                g2.draw(new Line2D.Float(x1, y1, x2, y2));
                g2.setStroke(new BasicStroke(1));
            }
        }
    }
    Rectangle bounds = getPointsBounds();
    String num = Integer.toString(n);
    g.drawString(num, bounds.x - 30, (bounds.y * 2 + bounds.height) / 2);
    //System.out.println("width of line"+n+": "+bounds.width);
}

From source file:AccessibleScrollDemo.java

public void paintComponent(Graphics g) {
    Rectangle drawHere = g.getClipBounds();

    // Fill clipping area with dirty brown/orange.
    g.setColor(new Color(230, 163, 4));
    g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);

    // Do the ruler labels in a small font that's black.
    g.setFont(new Font("SansSerif", Font.PLAIN, 10));
    g.setColor(Color.black);//  w  w w  . j a v  a  2  s  .c  om

    // Some vars we need.
    int end = 0;
    int start = 0;
    int tickLength = 0;
    String text = null;

    // Use clipping bounds to calculate first tick
    // and last tick location.
    if (orientation == HORIZONTAL) {
        start = (drawHere.x / increment) * increment;
        end = (((drawHere.x + drawHere.width) / increment) + 1) * increment;
    } else {
        start = (drawHere.y / increment) * increment;
        end = (((drawHere.y + drawHere.height) / increment) + 1) * increment;
    }

    // Make a special case of 0 to display the number
    // within the rule and draw a units label.
    if (start == 0) {
        text = Integer.toString(0) + (isMetric ? " cm" : " in");
        tickLength = 10;
        if (orientation == HORIZONTAL) {
            g.drawLine(0, SIZE - 1, 0, SIZE - tickLength - 1);
            g.drawString(text, 2, 21);
        } else {
            g.drawLine(SIZE - 1, 0, SIZE - tickLength - 1, 0);
            g.drawString(text, 9, 10);
        }
        text = null;
        start = increment;
    }

    // ticks and labels
    for (int i = start; i < end; i += increment) {
        if (i % units == 0) {
            tickLength = 10;
            text = Integer.toString(i / units);
        } else {
            tickLength = 7;
            text = null;
        }

        if (tickLength != 0) {
            if (orientation == HORIZONTAL) {
                g.drawLine(i, SIZE - 1, i, SIZE - tickLength - 1);
                if (text != null)
                    g.drawString(text, i - 3, 21);
            } else {
                g.drawLine(SIZE - 1, i, SIZE - tickLength - 1, i);
                if (text != null)
                    g.drawString(text, 9, i + 3);
            }
        }
    }
}

From source file:Base64.java

/**
 * Draws a line on the screen at the specified index. Default is green.
 * <p/>//from   ww  w.  j  a  v  a 2 s.c  om
 * Available colours: red, green, cyan, purple, white.
 *
 * @param render The Graphics object to be used.
 * @param row    The index where you want the text.
 * @param text   The text you want to render. Colours can be set like [red].
 */
public static void drawLine(Graphics render, int row, String text) {
    FontMetrics metrics = render.getFontMetrics();
    int height = metrics.getHeight() + 4; // height + gap
    int y = row * height + 15 + 19;
    String[] texts = text.split("\\[");
    int xIdx = 7;
    Color cur = Color.GREEN;
    for (String t : texts) {
        for (@SuppressWarnings("unused")
        String element : COLOURS_STR) {
            // String element = COLOURS_STR[i];
            // Don't search for a starting '[' cause it they don't exists.
            // we split on that.
            int endIdx = t.indexOf(']');
            if (endIdx != -1) {
                String colorName = t.substring(0, endIdx);
                if (COLOR_MAP.containsKey(colorName)) {
                    cur = COLOR_MAP.get(colorName);
                } else {
                    try {
                        Field f = Color.class.getField(colorName);
                        int mods = f.getModifiers();
                        if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                            cur = (Color) f.get(null);
                            COLOR_MAP.put(colorName, cur);
                        }
                    } catch (Exception ignored) {
                    }
                }
                t = t.replace(colorName + "]", "");
            }
        }
        render.setColor(Color.BLACK);
        render.drawString(t, xIdx, y + 1);
        render.setColor(cur);
        render.drawString(t, xIdx, y);
        xIdx += metrics.stringWidth(t);
    }
}

From source file:edu.purdue.cc.bionet.ui.HeatMap.java

/**
 * This method retrieves a heatmap image from jfreechart and places it on the panel
 * along with black divider lines and labels to create a heat map graph.
 * /*from w  ww .j a  va2s.c  o m*/
 * @param g The Graphics for the jpanel.
 */
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (moleculeList.size() > 0) {
        float tickStep;
        BufferedImage drawing = HeatMapUtilities.createHeatMapImage(this.getDataset(), this.spectrum);
        int leftEdge = this.getWidth() / 8;
        int topEdge = this.getHeight() / 32;
        int bottomEdge = this.getHeight() * 7 / 8;
        int rightEdge = this.getWidth() * 31 / 32;
        mapPosition = new Rectangle(leftEdge, topEdge, rightEdge - leftEdge, bottomEdge - topEdge);
        g.drawImage(drawing, leftEdge, topEdge, rightEdge - leftEdge, bottomEdge - topEdge,
                this.getBackground(), this);
        // y-axis
        int yAxisPos = leftEdge - 1;
        //      g.drawLine( yAxisPos, topEdge, yAxisPos, bottomEdge );
        tickStep = (bottomEdge - topEdge) / (float) moleculeList.size();
        for (int i = 0; i <= moleculeList.size(); i++) {
            int tickY = Math.round(topEdge + i * tickStep);
            g.drawLine(rightEdge, tickY, yAxisPos - tickSize, tickY);
            if (i < moleculeList.size()) {
                String name = this.moleculeList.get(this.moleculeList.size() - 1 - i).toString();
                g.drawString(name, yAxisPos - 4 - g.getFontMetrics().stringWidth(name),
                        (int) (tickY + tickStep));
            }
        }

        // x-axis
        int xAxisPos = bottomEdge;
        tickStep = (rightEdge - leftEdge) / (float) moleculeList.size();
        //      g.drawLine( leftEdge, xAxisPos, rightEdge, xAxisPos );
        for (int i = 0; i <= moleculeList.size(); i++) {
            int tickX = (int) (leftEdge + i * tickStep);
            g.drawLine(tickX, topEdge, tickX, xAxisPos + tickSize);
        }
        // transform clockwise 90 degrees for the vertical text
        AffineTransform at = new AffineTransform();
        at.quadrantRotate(3);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.transform(at);
        for (int i = 0; i < moleculeList.size(); i++) {
            int tickX = Math.round(leftEdge + i * tickStep);
            String name = this.moleculeList.get(i).toString();
            g2d.drawString(name, -(int) (xAxisPos + 4 + g.getFontMetrics().stringWidth(name)),
                    (int) (tickX + tickStep));
        }
    }
}

From source file:WeatherWizard.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension size = getSize();//from ww  w  . j a  va2  s.c  o m
    Composite origComposite;

    setupWeatherReport();

    origComposite = g2.getComposite();
    if (alpha0 != null)
        g2.setComposite(alpha0);
    g2.drawImage(img0, 0, 0, size.width, size.height, 0, 0, img0.getWidth(null), img0.getHeight(null), null);
    if (img1 != null) {
        if (alpha1 != null)
            g2.setComposite(alpha1);
        g2.drawImage(img1, 0, 0, size.width, size.height, 0, 0, img1.getWidth(null), img1.getHeight(null),
                null);
    }
    g2.setComposite(origComposite);

    // Freezing, Cold, Cool, Warm, Hot,
    // Blue, Green, Yellow, Orange, Red
    Font font = new Font("Serif", Font.PLAIN, 36);
    g.setFont(font);

    String tempString = feels + " " + temperature + "F";
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    Rectangle2D boundsTemp = font.getStringBounds(tempString, frc);
    Rectangle2D boundsCond = font.getStringBounds(condStr, frc);
    int wText = Math.max((int) boundsTemp.getWidth(), (int) boundsCond.getWidth());
    int hText = (int) boundsTemp.getHeight() + (int) boundsCond.getHeight();
    int rX = (size.width - wText) / 2;
    int rY = (size.height - hText) / 2;

    g.setColor(Color.LIGHT_GRAY);
    g2.fillRect(rX, rY, wText, hText);

    g.setColor(textColor);
    int xTextTemp = rX - (int) boundsTemp.getX();
    int yTextTemp = rY - (int) boundsTemp.getY();
    g.drawString(tempString, xTextTemp, yTextTemp);

    int xTextCond = rX - (int) boundsCond.getX();
    int yTextCond = rY - (int) boundsCond.getY() + (int) boundsTemp.getHeight();
    g.drawString(condStr, xTextCond, yTextCond);

}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * Write a blank thumbnail image so user doesn't see the broken icon.
 *///from w w w.ja v a  2 s. c om
private void writePlaceholderThumbnailImage(OutputStream os, int placeholderSize) throws IOException {
    // Make the image a bit bigger to account for the empty space around the generated image.
    // If we can find a way to remove this empty space, we don't need to make the chart bigger.
    BufferedImage buffer = new BufferedImage(placeholderSize + 16, placeholderSize + 9,
            BufferedImage.TYPE_INT_RGB);
    Graphics g = buffer.createGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, placeholderSize + 16, placeholderSize + 9);
    g.setColor(Color.gray);
    g.drawLine(8, placeholderSize + 5, placeholderSize + 8, placeholderSize + 5); // x-axis
    g.drawLine(8, 5, 8, placeholderSize + 5); // y-axis
    g.setColor(Color.black);
    Font font = g.getFont();
    g.setFont(new Font(font.getName(), font.getStyle(), 8));
    g.drawString("N/A", 9, placeholderSize);
    ImageIO.write(buffer, "png", os);
}

From source file:ala.soils2sat.DrawingUtils.java

public static Rectangle drawString(Graphics g, Font font, String text, int x, int y, int width, int height,
        int align, boolean wrap) {
    g.setFont(font);//from w  ww.java 2  s .co  m
    FontMetrics fm = g.getFontMetrics(font);

    setPreferredAliasingMode(g);

    Rectangle ret = new Rectangle(0, 0, 0, 0);

    if (text == null) {
        return ret;
    }
    String[] alines = text.split("\\n");
    ArrayList<String> lines = new ArrayList<String>();
    for (String s : alines) {
        if (wrap && fm.stringWidth(s) > width) {
            // need to split this up into multiple lines...
            List<String> splitLines = wrapString(s, fm, width);
            lines.addAll(splitLines);
        } else {
            lines.add(s);
        }
    }
    int numlines = lines.size();
    while (fm.getHeight() * numlines > height) {
        numlines--;
    }
    if (numlines > 0) {
        int maxwidth = 0;
        int minxoffset = y + width;
        int totalheight = (numlines * fm.getHeight());

        int linestart = ((height / 2) - (totalheight / 2));

        if (!wrap) {
            ret.y = y + linestart;
        } else {
            ret.y = y;
            linestart = 0;
        }
        for (int idx = 0; idx < numlines; ++idx) {
            String line = lines.get(idx);
            int stringWidth = fm.stringWidth(line);
            // the width of the label depends on the font :
            // if the width of the label is larger than the item
            if (stringWidth > 0 && width < stringWidth) {
                // We have to truncate the label
                line = clipString(null, fm, line, width);
                stringWidth = fm.stringWidth(line);
            }

            int xoffset = 0;
            int yoffset = linestart + fm.getHeight() - fm.getDescent();
            if (align == TEXT_ALIGN_RIGHT) {
                xoffset = (width - stringWidth);
            } else if (align == TEXT_ALIGN_CENTER) {
                xoffset = (int) Math.round((double) (width - stringWidth) / (double) 2);
            }

            if (xoffset < minxoffset) {
                minxoffset = xoffset;
            }
            g.drawString(line, x + xoffset, y + yoffset);
            if (stringWidth > maxwidth) {
                maxwidth = stringWidth;
            }
            linestart += fm.getHeight();
        }

        ret.width = maxwidth;
        ret.height = totalheight;
        ret.x = x + minxoffset;

        // Debug only...
        if (DEBUG) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(new BasicStroke(1));
            g.setColor(Color.blue);
            g.drawRect(ret.x, ret.y, ret.width, ret.height);
            g.setColor(Color.green);
            g.drawRect(x, y, width, height);
        }

        return ret;
    }
    return ret;
}

From source file:org.cloudml.ui.graph.Visu.java

public void createFrame() {
    final VisualizationViewer<Vertex, Edge> vv = v.getVisualisationViewer();

    vv.getRenderContext().setVertexIconTransformer(new Transformer<Vertex, Icon>() {
        public Icon transform(final Vertex v) {
            return new Icon() {

                public int getIconHeight() {
                    return 40;
                }//from ww  w . ja va2 s.c om

                public int getIconWidth() {
                    return 40;
                }

                public void paintIcon(java.awt.Component c, Graphics g, int x, int y) {
                    ImageIcon img;
                    if (v.getType() == "node") {
                        img = new ImageIcon(this.getClass().getResource("/server.png"));
                    } else if (v.getType() == "platform") {
                        img = new ImageIcon(this.getClass().getResource("/dbms.png"));
                    } else {
                        img = new ImageIcon(this.getClass().getResource("/soft.png"));
                    }
                    ImageObserver io = new ImageObserver() {

                        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width,
                                int height) {
                            // TODO Auto-generated method stub
                            return false;
                        }
                    };
                    g.drawImage(img.getImage(), x, y, getIconHeight(), getIconWidth(), io);

                    if (!vv.getPickedVertexState().isPicked(v)) {
                        g.setColor(Color.black);
                    } else {
                        g.setColor(Color.red);

                        properties.setModel(new CPIMTable(v));
                        runtimeProperties.setModel(new CPSMTable(v));
                    }
                    g.drawString(v.getName(), x - 10, y + 50);
                }
            };
        }
    });

    // create a frame to hold the graph
    final JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final ModalGraphMouse gm = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(gm);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton save = new JButton("save");
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "save");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            OutputStream streamResult;
            try {
                streamResult = new FileOutputStream(result);
                codec.save(dmodel, streamResult);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });
    JButton saveImage = new JButton("save as image");
    saveImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "save");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            v.writeJPEGImage(result);
        }
    });
    //WE NEED TO UPDATE THE FACADE AND THE GUI
    JButton load = new JButton("load");
    load.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "load");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            try {
                InputStream stream = new FileInputStream(result);
                Deployment model = (Deployment) codec.load(stream);
                dmodel = model;
                v.setDeploymentModel(dmodel);
                ArrayList<Vertex> V = v.drawFromDeploymentModel();
                nodeTypes.removeAll();
                nodeTypes.setModel(fillList());

                properties.setModel(new CPIMTable(V.get(0)));
                runtimeProperties.setModel(new CPSMTable(V.get(0)));

                CommandFactory fcommand = new CommandFactory();
                CloudMlCommand load = fcommand.loadDeployment(result.getPath());
                cml.fireAndWait(load);

            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });
    JButton deploy = new JButton("Deploy!");
    deploy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //cad.deploy(dmodel);
            System.out.println("deploy");
            CommandFactory fcommand = new CommandFactory();
            CloudMlCommand deploy = fcommand.deploy();
            cml.fireAndWait(deploy);
        }
    });

    //right panel
    JPanel intermediary = new JPanel();
    intermediary.setLayout(new BoxLayout(intermediary, BoxLayout.PAGE_AXIS));
    intermediary.setBorder(BorderFactory.createLineBorder(Color.black));

    JLabel jlCPIM = new JLabel();
    jlCPIM.setText("CPIM");

    JLabel jlCPSM = new JLabel();
    jlCPSM.setText("CPSM");

    properties = new JTable(null);
    //properties.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    JTableHeader h = properties.getTableHeader();
    JPanel props = new JPanel();
    props.setLayout(new BorderLayout());
    props.add(new JScrollPane(properties), BorderLayout.CENTER);
    props.add(h, BorderLayout.NORTH);

    runtimeProperties = new JTable(null);
    //runtimeProperties.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    JTableHeader h2 = runtimeProperties.getTableHeader();
    JPanel runProps = new JPanel();
    runProps.setLayout(new BorderLayout());
    runProps.add(h2, BorderLayout.NORTH);
    runProps.add(new JScrollPane(runtimeProperties), BorderLayout.CENTER);

    intermediary.add(jlCPIM);
    intermediary.add(props);
    intermediary.add(jlCPSM);
    intermediary.add(runProps);

    content.add(intermediary, BorderLayout.EAST);

    //Left panel
    JPanel selection = new JPanel();
    JLabel nodes = new JLabel();
    nodes.setText("Types");
    selection.setLayout(new BoxLayout(selection, BoxLayout.PAGE_AXIS));
    nodeTypes = new JList(fillList());
    nodeTypes.setLayoutOrientation(JList.VERTICAL);
    nodeTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    nodeTypes.setVisibleRowCount(10);
    JScrollPane types = new JScrollPane(nodeTypes);
    types.setPreferredSize(new Dimension(150, 80));
    selection.add(nodes);
    selection.add(types);

    content.add(selection, BorderLayout.WEST);

    ((DefaultModalGraphMouse<Integer, Number>) gm)
            .add(new MyEditingGraphMousePlugin(0, vv, v.getGraph(), nodeTypes, dmodel));
    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(save);
    controls.add(saveImage);
    controls.add(load);
    controls.add(deploy);
    controls.add(((DefaultModalGraphMouse<Integer, Number>) gm).getModeComboBox());
    content.add(controls, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}