How to draw string vertically?

Hi,
The java drawString() method draws string horizontally by default, but I want to draw the string vertically, see an example below: I want to draw the string "abcdef" as below format:
a
b
c
d
e
f
so, I thought of the AffineTransform, but I can not work it out.
Who can help me? If you have other ways, they are welcome too.
Thanks. Robin

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class VText {
    public static void main(String[] args) {
        int w = 200, h = 300;
        BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(UIManager.getColor("OptionPane.background"));
        g2.clearRect(0,0,w,h);
        g2.setPaint(Color.black);
        Font font = g2.getFont().deriveFont(18f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        String text = "Hello World";
        g2.drawString(text, 50, h - 25);
        String[] s = text.split("(?<=[\\w\\s])");
        float y = 25f;
        for(int j = 0; j < s.length; j++) {
            float width = (float)font.getStringBounds(s[j], frc).getWidth();
            LineMetrics lm = font.getLineMetrics(s[j], frc);
            float x = (w - width)/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            g2.setFont(font.deriveFont(at));
            g2.drawString(s[j], 0, 0);
            y += lm.getAscent();// - lm.getDescent();
        g2.dispose();
        JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
                                      JOptionPane.PLAIN_MESSAGE);
}

Similar Messages

  • How to draw text vertically, or in an angle

    please help me how to draw text vertically, or in an angle

    I robbed the framework from Dr Las or 74phillip (don't remember which) ...
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class AngleText extends JPanel {
      private int      degrees = 16;
      private JSpinner degreesSpinner;
      public AngleText () {
        setBackground ( Color.WHITE );
      }  // AngleText constructor
      protected void paintComponent ( Graphics _g ) {
        super.paintComponent ( _g );
        Graphics2D g = (Graphics2D)_g;
        g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        AffineTransform at = AffineTransform.getRotateInstance ( Math.toRadians ( degrees ) );
        Font f =  g.getFont();
        g.setFont ( f.deriveFont ( at ) );
        g.drawString ( "Rotating Text!", getWidth()/2, getHeight()/2 );
        g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
      }  // paintComponent
      public JPanel getUIPanel () {
        SpinnerModel degreesModel = new SpinnerNumberModel (
                                      degrees  // initial
                                     ,0        // min
                                     ,360      // max
                                     ,2        // step
        degreesSpinner = new JSpinner ( degreesModel );
        degreesSpinner.addChangeListener ( new DegreesTracker() );
        JPanel panel = new JPanel();
        panel.add ( degreesSpinner );
        return panel;
      }  // getUIPanel
      //  DegreesTracker
      private class DegreesTracker implements ChangeListener {
        public void stateChanged ( ChangeEvent e ) {
          Integer i = (Integer)((JSpinner)e.getSource()).getValue();
          degrees   = i.intValue ();
          repaint();
      }  // DegreesTracker
      //  main
      public static void main ( String[] args ) {
        JFrame f = new JFrame ( "AngleText" );
        f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        AngleText app = new AngleText();
        f.getContentPane().add ( app );
        f.getContentPane().add ( app.getUIPanel(), BorderLayout.SOUTH );
        f.setSize ( 200, 200 );
        f.setVisible ( true );
      }  // main
    }  // AngleText

  • How to draw a vertical string?

    I use Graphics2D to draw a 2D graph with x-axis and y-axis. I would like to put the name of the y-axis vertically along the y-axis. This means I need to rotate my drawString 90 degrees. How can we do that? I would be very thankful if anyone can help me out.
    Thank you

    I had the same problem when I started developing JFreeChart:
    http://www.object-refinery.com/jfreechart/index.html
    Here is the code I use:
         * A utility method for drawing rotated text.
         * <P>
         * A common rotation is -Math.PI/2 which draws text 'vertically' (with the top of the
         * characters on the left).
         * @param text The text.
         * @param g2 The graphics device.
         * @param x The x-coordinate.
         * @param y The y-coordinate.
         * @param rotation The clockwise rotation (in radians).
        public static void drawRotatedString(String text, Graphics2D g2,
                                             float x, float y, double rotation) {
            AffineTransform saved = g2.getTransform();
            AffineTransform rotate = AffineTransform.getRotateInstance(rotation, x, y);
            g2.transform(rotate);
            g2.drawString(text, x, y);
            g2.setTransform(saved);
        }Regards,
    Dave Gilbert
    JFreeChart Project Leader

  • How to Draw a vertical line in flex

    I was just wondering the simplest way to draw a vertical line , preferably dashed.

    You could always just use the graphics class of your chart component.  Just access its graphics object, set the line style/thickness, move to the start point, and line to the end point.  Something like this,
    this.graphics.lineStyle(1, 0x000000);
    this.graphics.moveTo(startX, startY);
    this.graphics.lineTo(endX, endY);

  • How to draw vertical lines in SMART FORMS

    Hi Guys,
    Can anyone please let me know how to draw vertical and horizontal lines in smart forms, i have to do this in the secondary window.
    thanks,
    Ramesh

    Hi Ramesh,
    In the window output options you have option of check box to get lines.
    Then you need to give the spacing for vertical and horizontal.
    Another option is putting a template on window and getting the boxes, but it is quite little bit complex.
    Put the cursor on the WINDOW in which the lines you want.
    Right click on it>create>complex section.
    In that select the TEMPLATE radio button.
    Goto TAB TEMPLATE.
    Name: give some name of line.
    From: From coloumn.
    To: To coloumn
    Height: specify the height of the line.
    Next give the coloumn widths.
    Like this you can draw the vertical and horzontal lines.
    If the above option doesnot workout then u can try the below option also
    any how you can draw vertical and horizontal lines using Template and Table.
    for Template First define the Line and divide that into coloumns and goto select patterns and select the required pattern to get the vertical and horizontal lines.
    For table, you have to divide the total width of the table into required no.of columns and assign the select pattern to get the vertical and horizontal lines.
    if this helps, reward with points.
    Regards,
    Naveen

  • How can I show vertical text?

    Hi all, does any body knows how can I show a vertical text using g2.drawString() method?
    For example:
    g2.drawString("Help", x, y);
    I want the text appear like:
    p
    l
    e
    H
    of course with the correct rotation of each character.
    thanks in advance

    Here's the code we use in the JFreeChart project:
         * A utility method for drawing rotated text.
         * <P>
         * A common rotation is -Math.PI/2 which draws text 'vertically' (with the top of the
         * characters on the left).
         * @param text  the text.
         * @param g2  the graphics device.
         * @param x  the x-coordinate.
         * @param y  the y-coordinate.
         * @param rotation  the clockwise rotation (in radians).
        public static void drawRotatedString(String text, Graphics2D g2,
                                             float x, float y, double rotation) {
            if ((text == null) || (text.equals(""))) {
                return;
            AffineTransform saved = g2.getTransform();
            // apply the rotation...
            AffineTransform rotate = AffineTransform.getRotateInstance(rotation, x, y);
            g2.transform(rotate);
            // workaround for JDC bug ID 4312117 and others...
            TextLayout tl = new TextLayout(text, g2.getFont(), g2.getFontRenderContext());
            tl.draw(g2, x, y);
            // replaces this code...
            //g2.drawString(text, x, y);
            g2.setTransform(saved);
        }That bug workaround is causing trouble in some JDKs, try the original code and see if it works for you.
    Regards,
    Dave Gilbert
    www.jfree.org

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • How to Draw table in SAPscript ???

    Hi all Guru of SAPScript!
    I want to draw a table with column and row in SAPscript. Who can help me step by step?
    Thanks!
    Edited by: kathy a on May 6, 2008 11:53 AM

    Hi,
    Use BOx Syantax  How to Draw table in SAPscript ??? Pls Read the description
    Syntax:
    1. /: BOX [XPOS] [YPOS] [WIDTH] [HEIGHT] [FRAME] [INTENSITY]
    2. /: POSITION [XORIGIN] [YORIGIN] [WINDOW] [PAGE]
    3. /: SIZE [WIDTH] [HEIGHT] [WINDOW] [PAGE]
    BOX
    Syntax:
    /: BOX [XPOS] [YPOS] [WIDTH] [HEIGHT] [FRAME] [INTENSITY]
    Effect: draws a box of the specified size at the specified position.
    Parameters: For each parameter (XPOS, YPOS, WIDTH, HEIGHT and FRAME), both a measurement and a unit of measure must be specified. The INTENSITY parameter should be entered as a percentage between 0 and 100.
    •&#61472;XPOS, YPOS: Upper left corner of the box, relative to the values of the POSITION command.
    Default: Values specified in the POSITION command.
    The following calculation is performed internally to determine the absolute output position of a box on the page:
    X(abs) = XORIGIN + XPOS
    Y(abs) = YORIGIN + YPOS
    •&#61472;WIDTH: Width of the box.
    Default: WIDTH value of the SIZE command.
    •&#61472;HEIGHT: Height of the box.
    Default: HEIGHT value of the SIZE command.
    •&#61472;FRAME: Thickness of frame.
    Default: 0 (no frame).
    •&#61472;INTENSITY: Grayscale of box contents as %.
    Default: 100 (full black)
    Measurements: Decimal numbers must be specified as literal values (like ABAP/4 numeric constants) by being enclosed in inverted commas. The period should be used as the decimal point character. See also the examples listed below.
    Units of measure: The following units of measure may be used:
    •&#61472;TW (twip)
    •&#61472;PT (point)
    •&#61472;IN (inch)
    •&#61472;MM (millimeter)
    •&#61472;CM (centimeter)
    •&#61472;LN (line)
    •&#61472;CH (character).
    The following conversion factors apply:
    •&#61472;1 TW = 1/20 PT
    •&#61472;1 PT = 1/72 IN
    •&#61472;1 IN = 2.54 CM
    •&#61472;1 CM = 10 MM
    •&#61472;1 CH = height of a character relative to the CPI specification in the layout set header
    •&#61472;1 LN = height of a line relative to the LPI specification in the layout set header
    Examples:
    /: BOX FRAME 10 TW
    Draws a frame around the current window with a frame thickness of 10 TW (= 0.5 PT).
    /: BOX INTENSITY 10
    Fills the window background with shadowing having a gray scale of 10 %.
    /: BOX HEIGHT 0 TW FRAME 10 TW
    Draws a horizontal line across the complete top edge of the window.
    /: BOX WIDTH 0 TW FRAME 10 TW
    Draws a vertical line along the complete height of the left hand edge of the window.
    /: BOX WIDTH '17.5' CM HEIGHT 1 CM FRAME 10 TW INTENSITY 15
    /: BOX WIDTH '17.5' CM HEIGHT '13.5' CM FRAME 10 TW
    /: BOX XPOS '10.0' CM WIDTH 0 TW HEIGHT '13.5' CM FRAME 10 TW
    /: BOX XPOS '13.5' CM WIDTH 0 TW HEIGHT '13.5' CM FRAME 10 TW
    Draws two rectangles and two lines to construct a table of three columns with a highlighted heading section.
    POSITION
    Syntax:
    /: POSITION [XORIGIN] [YORIGIN] [WINDOW] [PAGE]
    Effect: Sets the origin for the coordinate system used by the XPOS and YPOS parameters of the BOX command. When a window is first started the POSITION value is set to refer to the upper left corner of the window (default setting).
    Parameters: If a parameter value does not have a leading sign, then its value is interpreted as an absolute value, in other words as a value which specifies an offset from the upper left corner of the output page. If a parameter value is specified with a leading sign, then the new value of the parameter is calculated relative to the old value. If one of the parameter specifications is missing, then no change is made to this parameter.
    •&#61472;XORIGIN, YORIGIN: Origin of the coordinate system.
    •&#61472;WINDOW: Sets the values for the left and upper edges to be the same of those of the current window (default setting).
    •&#61472;PAGE: Sets the values for the left and upper edges to be the same as those of the current output page (XORIGIN = 0 cm, YORIGIN = 0 cm).
    Examples:
    /: POSITION WINDOW
    Sets the origin for the coordinate system to the upper left corner of the window.
    /: POSITION XORIGIN 2 CM YORIGIN '2.5 CM'
    Sets the origin for the coordinate system to a point 2 cm from the left edge and 2.5 cm from the upper edge of the output page.
    /: POSITION XORIGIN '-1.5' CM YORIGIN -1 CM
    Shifts the origin for the coordinates 1.5 cm to the left and 1 cm up.
    SIZE
    Syntax:
    /: SIZE [WIDTH] [HEIGHT] [WINDOW] [PAGE]
    Effect: Sets the values of the WIDTH and HEIGHT parameters used in the BOX command. When a window is first started the SIZE value is set to the same values as the window itself (default setting).
    Parameters: If one of the parameter specifications is missing, then no change is made to the current value of this parameter. If a parameter value does not have a leading sign, then its value is interpreted as an absolute value. If a parameter value is specified with a leading sign, then the new value of the parameter is calculated relative to the old value.
    •&#61472;WIDTH, HEIGHT: Dimensions of the rectangle or line.
    •&#61472;WINDOW: Sets the values for the width and height to the values of the current window (default setting).
    •&#61472;PAGE: Sets the values for the width and height to the values of the current output page.
    Examples:
    /: SIZE WINDOW
    Sets WIDTH and HEIGHT to the current window dimensions.
    /: SIZE WIDTH '3.5' CM HEIGHT '7.6' CM
    Sets WIDTH to 3.5 cm and HEIGHT to 7.6 cm.
    /: POSITION WINDOW
    /: POSITION XORIGIN -20 TW YORIGIN -20 TW
    /: SIZE WIDTH +40 TW HEIGHT +40 TW
    /: BOX FRAME 10 TW
    A frame is added to the current window. The edges of the frame extend beyond the edges of the window itself, so as to avoid obscuring the leading and trailing text characters.
    Reward Helpfull Answers
    Regards
    Fareedas

  • How to embed string into rectangle?

    Hi all.
    I have a rectangular area to draw the string, but the string can be wider than the rectangle it should fit. How to draw truncated string? For example:
    public void paintComponent(Graphics g) {
              String s = new String("This is a very long string");
              int x = 0;
              int y = 0;
              int rectWidth = 20;
              int rectHeight = 10;
              Rectangle r = new Rectangle(x, y, rectWidth, rectHeight);
              int strWidth = g.getFontMetrics().stringWidth(s);
              if (strWidth > rectWidth) {
                   System.err.println("How to do that?");
              } else {
                   g.drawString(s, x, y);
         }Thank you in advance.

    If what you want is for your clipped string to display the "..." just like JLabel does, here is an algorythm that you can use:
    1- If the font metrics tells you that your string is going to get clipped, start removing chars from the end
    2- add "..." to the shortened string.
    3- if that string now fits, done
    4- else goto 1

  • How to draw grid?

    I want to draw a grid in an application. how do i do that?
    I want to use a efficient & effective way of doing it.
    I was thinking along the lines of drawing a 2D rectangle and draw horizontal/vertical lines in position to make up the grid. (this probably would be a hard coded way)
    would above work then?
    Any ideas?

    I was thinking along the lines of drawing a 2D rectangle and draw horizontal/vertical lines in position to make up the grid. (this probably would be a hard coded way)
    would above work then?Yes, this will work. Give it a try.
    You should also store a variable like gridX and gridY that you can change. These variables specify the amount of desired grid lines in the x and y direction. Then at draw time, based on the width and height of the component you caculate the interspacing betwen lines required to meet your desired # of lines and draw accordingly.

  • How to draw a line(shortest distance)  between two ellipse using SWING

    how to draw a line(should be shortest distance) between two ellipse using SWING
    any help will be appreciated
    regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ELine extends JPanel {
        Ellipse2D.Double red = new Ellipse2D.Double(150,110,75,165);
        Ellipse2D.Double blue = new Ellipse2D.Double(150,50,100,50);
        Line2D.Double line = new Line2D.Double();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.blue);
            g2.draw(blue);
            g2.setPaint(Color.red);
            g2.draw(red);
        private void connect() {
            double flatness = 0.01;
            PathIterator pit = blue.getPathIterator(null, flatness);
            double[] coords = new double[2];
            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        Point2D.Double p = getClosestPoint(coords[0], coords[1]);
                        double dist = p.distance(coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            x1 = coords[0];
                            y1 = coords[1];
                            x2 = p.x;
                            y2 = p.y;
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("blue type: " + type);
                pit.next();
            line.setLine(x1, y1, x2, y2);
        private Point2D.Double getClosestPoint(double x, double y) {
            double flatness = 0.01;
            PathIterator pit = red.getPathIterator(null, flatness);
            double[] coords = new double[2];
            Point2D.Double p = new Point2D.Double();
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        double dist = Point2D.distance(x, y, coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            p.setLocation(coords[0], coords[1]);
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("red type: " + type);
                pit.next();
            return p;
        public static void main(String[] args) {
            final ELine test = new ELine();
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Graphics g = test.getGraphics();
                    g.drawString("drag me", 175, 80);
                    g.dispose();
        private MouseInputAdapter mia = new MouseInputAdapter() {
            Point2D.Double offset = new Point2D.Double();
            boolean dragging = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(blue.contains(p)) {
                    offset.x = p.x - blue.x;
                    offset.y = p.y - blue.y;
                    dragging = true;
            public void mouseReleased(MouseEvent e) {
                dragging = false;
            public void mouseDragged(MouseEvent e) {
                if(dragging) {
                    double x = e.getX() - offset.x;
                    double y = e.getY() - offset.y;
                    blue.setFrame(x, y, blue.width, blue.height);
                    connect();
                    repaint();
    }

  • How to draw a simple little line.

    I have a JApplet that loads images from a jar file. This applet can scale the images, and move them left right, up and down.
    I just want to be able to draw a line on top of the images and then erase it if needed. How do I do this?
    Currently, I have a the jpg images loaded into an Image, which is then converted to an ImageIcon, which is then used to create a JLabel, which is used to create a JScrollPane which finally gets added as a tab on a JTabbedPane.
    I was told to use BufferedImage but that didn't help me. Here is what I have currently:
    private void draw()
    //Get the current image to draw on
    JScrollPane jsp = (JScrollPane)m_tabbedPane.getSelectedComponent();
    JViewport port = jsp.getViewport();
    GrabAndScrollLabel gnsLabel = (GrabAndScrollLabel) port.getView();
    ImageIcon ii = (ImageIcon) gnsLabel.getIcon();
    BufferedImage bi = new BufferedImage (ii.getIconWidth(),
    ii.getIconHeight(),
    BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.setPaint(Color.blue);
    g2.drawLineRect(100, 200, 300, 500);
    g2.drawImage(ii.getImage(),null,null);
    ImageIcon newIcon = new ImageIcon(ii.getImage());
    gnsLabel.setIcon(newIcon);
    port.setView(gnsLabel);
    jsp.setViewport(port);
    getRootPane().revalidate();
    getRootPane().repaint();
    Please help. I can't believe it has to be this difficult to draw a little line.
    Thanks.

    I have a little more insight into my problem.
    I built a sample form Sun (the Map_Line sample). It looks like this:
    public class Map_Line extends Applet
    private BufferedImage bi;
    public Map_Line()
    setBackground(Color.white);
    Image img = getToolkit().getImage("bld.jpg");
    try
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(img, 0);
    tracker.waitForID(0);
    catch (Exception e)
    int iw = img.getWidth(this);
    int ih = img.getHeight(this);
    bi = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
    Graphics2D big = bi.createGraphics();
    big.drawImage(img, 0, 0, this);
    public void paint(Graphics g)
    Graphics2D g2 = (Graphics2D) g;
    int w = getSize().width;
    int h = getSize().height;
    int bw = bi.getWidth(this);
    int bh = bi.getHeight(this);
    g2.drawImage(bi, null, 0, 0);
    g2.setColor(Color.white);
    g2.setStroke(new BasicStroke(5.0f));
    g2.drawLine(10, 10, bw - 10, bh - 10);
    public static void main(String[] s)
    WindowListener l = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    Frame f = new Frame("Map_Line");
    f.addWindowListener(l);
    f.add("Center", new Map_Line());
    f.pack();
    f.setSize(new Dimension(350, 250));
    f.show();
    Note how the drawing is done in paint. This applet works just fine for me.
    The difference is that I'm trying to use the BufferedImage to get my Graphics2D object where as this one gets it from paint (casts Graphics to Graphics2D).
    This applet works just fine, but if you try to use the Graphics2D that comes back from the BufferedImage, it doesn't work!.
    For example, if I create a member variable:
    Graphics2D big;
    And then in paint do this:
    //Graphics2D g2 = (Graphics2D) g;
    Grahics2D g2 = big;
    It no longer works!
    So, it looks like I need to use something other than the
    BufferedImage.createGraphics() to get the Graphics2D object I need.
    Does this seem right?
    Thanks!

  • How to make baseline vertical

    Hello All,
         how to make baseline vertical.
    Always baseline is horizontal i.e we can draw the text only in
    horizontal line . How to make baseline vertical . Is there any method
    in jdk1.1.8 to make baseline vertical.
    Can any one answere?
    Sharmila

    in 1.1.8, no
    AffineTransform (introduced in java1.2) allows an arbitrary transform to be applied to the origin, so it can be used to perform the task you want. However, this functionality is unavailable in <1.2 JREs.
    rob,

  • How to draw rectanlge in the panel, clear, repaint?

    when i was taking my coding, i found a problem which i could not solve.So, i hope someone can help. Thank you.
    the question :
    1. how to draw Rectangle in the Panel?
    2. how to clear?
    3. how to repaint?
    The following is my coding.
    import javax.swing.*;
    import java.awt.*;
    public class DrawScreen extends JFrame {
    Color rectColor=Color.white;
    int hight=100;
    Panel Button_panel = new Panel();
    Button button1 = new Button();
    Button button2 = new Button();
    Button button3 = new Button();
    Panel Draw_Panel = new Panel();
    public DrawScreen(String title) {
         super(title);
         try {
         Init();
         catch(Exception e) {
         e.printStackTrace();
    private void Init() throws Exception {
    setResizable(false);
    setFont(new Font("Serif",Font.ITALIC,12));
         this.getContentPane().setLayout(null);
         Button_panel.setBackground(SystemColor.control);
         Button_panel.setLocale(java.util.Locale.getDefault());
         Button_panel.setBounds(new Rectangle(14, 17, 118, 259));
         Button_panel.setLayout(null);
         button1.setLabel("Draw Square");
         button1.setBounds(new Rectangle(0, 69, 115, 22));
         button2.setLabel("Colour Red");
         button2.setBounds(new Rectangle(0, 111, 115, 22));
         button3.setLabel("Clear Screen");
         button3.setBounds(new Rectangle(2, 152, 115, 22));
         Draw_Panel.setBackground(Color.white);
         Draw_Panel.setBounds(new Rectangle(138, 15, 254, 266));
    //     System.out.println(Draw_Panel.getBounds());
         this.getContentPane().setBackground(Color.white);
         this.getContentPane().add(Button_panel, "East");
         Button_panel.add(button3, null);
         Button_panel.add(button2, null);
         Button_panel.add(button1, null);
         this.getContentPane().add(Draw_Panel, "West");
         addWindowListener(new java.awt.event.WindowAdapter(){
              public void windowClosing(java.awt.event.WindowEvent e){
                   System.exit(0);
    button1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button1ActionPerformed(evt);
    button2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button2ActionPerformed(evt);
    button3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button3ActionPerformed(evt);
    pack();
    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
         hight=(int)(Math.random()*100);
         rectColor=Color.black;
    repaint();
    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {
         rectColor=Color.red;
    repaint();
    private void button3ActionPerformed(java.awt.event.ActionEvent evt) {
    rectColor=Color.white;
    repaint();
    public void paint(Graphics g){
         g.setColor(rectColor);
         g.drawRect(50, 50,hight,hight);
    public static void main(String[] args) {
    DrawScreen ds=new DrawScreen("Square Plotter");
         ds.setSize(600,350);
         ds.setVisible(true);

    Few changes and it works:
    import javax.swing.*;
    import java.awt.*;
    public class DrawScreen extends JFrame
         Color  rectColor    = Color.white;
         int    hight        = 100;
         Panel  Button_panel = new Panel();
         Button button1      = new Button();
         Button button2      = new Button();
         Button button3      = new Button();
         DPanel Draw_Panel   = new DPanel();
    public DrawScreen(String title)
         super(title);
         setResizable(false);
    //     setFont(new Font("Serif",Font.ITALIC,12));
    //     this.getContentPane().setLayout(null);
         Button_panel.setBackground(SystemColor.control);
         Button_panel.setLocale(java.util.Locale.getDefault());
         Button_panel.setBounds(new Rectangle(14, 17, 118, 259));
         Button_panel.setLayout(null);
         button1.setLabel("Draw Square");
         button1.setBounds(new Rectangle(0, 69, 115, 22));
         button2.setLabel("Colour Red");
         button2.setBounds(new Rectangle(0, 111, 115, 22));
         button3.setLabel("Clear Screen");
         button3.setBounds(new Rectangle(2, 152, 115, 22));
         Draw_Panel.setBackground(Color.white);
         Draw_Panel.setBounds(new Rectangle(138, 15, 254, 266));
    //  System.out.println(Draw_Panel.getBounds());
    //     this.getContentPane().setBackground(Color.white);
         this.getContentPane().add(Button_panel, "East");
         Button_panel.add(button3);
         Button_panel.add(button2);
         Button_panel.add(button1);
         this.getContentPane().add(Draw_Panel, "Center");
         addWindowListener(new java.awt.event.WindowAdapter()
              public void windowClosing(java.awt.event.WindowEvent e)
                   System.exit(0);
         button1.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
                   button1ActionPerformed(evt);
         button2.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
              button2ActionPerformed(evt);
         button3.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
                   button3ActionPerformed(evt);
    //     pack();
    private void button1ActionPerformed(java.awt.event.ActionEvent evt)
         hight=(int)(Math.random()*100);
         rectColor=Color.black;
         repaint();
    private void button2ActionPerformed(java.awt.event.ActionEvent evt)
         rectColor=Color.red;
         repaint();
    private void button3ActionPerformed(java.awt.event.ActionEvent evt)
         rectColor=Color.white;
         repaint();
    public class DPanel extends JPanel
    public DPanel()
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.setColor(rectColor);
         g.drawRect(50, 50,hight,hight);
    public static void main(String[] args)
         DrawScreen ds=new DrawScreen("Square Plotter");
         ds.setSize(600,350);
         ds.setVisible(true);
    }Noah

  • How to draw in a JPanel and refresh it?

    Hey guys,
    i want to draw a map, consisting of a lot of colored rectangles, in a JPanel.
    it is part of project i am working on. a robot is discovering a track and i want to draw this track step by step, the informations are sent via bluetooth.
    i am not sure how to draw it step by step and how to refresh it?
    i am able to draw a static graphic with the abstract class Graphics and the method paintComponent of the class JPanel.
    How do I add one or more rectangles to the existing graphic?
    thanks for your help!

    i would like to realize the standard approach.
    but i am not quite sure how.
    i tried to realize it like this, but there is an error, if the i uncomment the two lines and i do not understand why!
    import java.awt.image.*;
    import java.awt.*;
    import javax.swing.*;
    public class TrackWindow extends JFrame {   
         public TrackWindow() {
              super("Mapping");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setAlwaysOnTop(true);
              this.setLocationByPlatform(true);
              this.setSize(500, 500);
              this.add(new TrackPanel());
              this.setVisible(true);
         public static void main(String[] args) {
              new TrackWindow();
         public class TrackPanel extends JPanel {
              public BufferedImage track = null;
              public TrackPanel() {
                   track = (BufferedImage)this.createImage(200, 200);
                   //Graphics2D g2 = track.createGraphics();
                   //g2.fillRect(0, 0, 15, 15);
              public void paintComponent(Graphics g) {
    }could you please help me a little.
    Thank you!

Maybe you are looking for

  • Sharepoint 2010 - SPUCWorkerProcess - Could not create file

    I have some type of permission issue that is preventing my User Code Host service from running (it starts then stops).    I am seeing the following in my ULS: 03/01/2011 09:59:13.42 SPUCWorkerProcess.exe (0x0F78) 0x1254 SharePoint Foundation Unified

  • Setting control bar to resume auto-play (Captivate 6)

    Hi, I am currently using Captivate 6 to create an eLearning course.  We have decided to display the bottom control bar to allow flexibility for the student to move between screens in each lesson.  Currently if the student uses the progress arrow in t

  • Insert into SQL database

    Hi, I am using xMII v 11.5..I need to insert into SQL database. In BLS Step 1:I am using an SQL Query1 it fetches data Step 2:  I am using 4 calculation Action block to calculate the values Step 3: I am inserting the Calculated values using an SQL Qu

  • Abstract class, Interface and two models issue

    Hi! I will post my code and then ask the question (text between code snippets is bold, so you don't miss it, it's not shouting): public class AppScreen extends JFrame                        implements ActionListener {   private MemoryTableModel model

  • Photoshop on creative cloud

    i cannot download photoshop. all items say install, photoshop says up to date? purchased subscription to creative cloud, when in adope manager photoshop is only item on list I cannot install, its states up to date?