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

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 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

  • 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 draw tab key char into Graphics g as space?

    Hi, all.
    following pg.drawString(token, 0, y); keep draw "\t" strange character like "o".
    eg: "\tpublic static"--after draw..--> opublic static".
    As you see below, I replace "\t" with " "(blankes).
    I test replaceString method. it works fine.
    but, once it draw it, it keep draw "o" string where the "\t" was.
    What's problem?
    //called for print.
    public int print(Graphics pg, PageFormat pageFormat,
              int pageIndex) throws PrinterException {
    //some code...
    String tabReplace=" ";
    StringTokenizer parser = new StringTokenizer(contents, "\n");
         try {
         while(parser.hasMoreTokens()) {
              String token=replaceString(parser.nextToken(), "\t", tabReplace);
              pg.drawString(token, 0, y);
              y+=fm.getHeight();
              y+=lineSpace;//lineSpace comes from use option               
         } catch (NoSuchElementException e) {
         System.out.println(e);
    //some code..
         public String replaceString(String contents, String replace,
                                                 String with){
              int indexHead=0, indexTail=0;
              while(( indexTail = contents.indexOf(replace, indexHead) ) >0){
                   contents=contents.substring(indexHead, indexTail)+
                             with+contents.substring(indexTail+replace.length());
                   indexHead+=with.length();
              return contents;
    f

    Any unprintable character draws the square 'o' on a graphics object, not only \t. Since your code is correct, it will replace away all \t in the string, means there are no \t left in the string. Since there is still unprintable character resident in the string, you need to check that the string that you draw is the correct one or which character that is unprintable. How about looping through the string and print the char-as-int to system int. Look for fairly low numbers < 32 and 127 as they would not be printable by normal means.
    Regards,
    Peter Norell

  • 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!

  • How to print text vertically in smart forms

    hi,
    Can any one tell how to print text vertically in smartforms
    ADVANCE THANKS
    GUHAPRIYAN

    HI,
    Chk out  this thread.Maybe it proves helpful.
    Re: vertical writing in smartforms
    Regards,
    Gayathri

  • How to Plot number and string in one row (data logger counter) ?

    hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
    i have problem about plot the number & string in one row, as shown on the picture below :
    how to move that string on one row ? i attach my vi.
    Thanks~
    Attachments:
    MODBUS LIB Counter.vi ‏39 KB

    Duplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...

Maybe you are looking for

  • Connecting Aquos Sharp TV to Macbook pro

    Has anybody figured out how to do this? I have done everything by the manuals. I have a DVI connector to the HDMI Port 6 in the TV. All the right adapters. My TV model is:LC32LE700UN. All I get is a black screen. Computer does not recognize. Does the

  • Reference Monitor Question

    I'm in the market for a new TV. My old 19" Toshiba still works, but the quality isn't there anymore. Still good enough though to view video on before burning to DVD. My questions are: -- Will a flat screen LCD be comparable in any way to the CRT for

  • FM Process Chain Error!

    Hi All,   We are running a funds management process chain , there is a AND process and on executing the PC it throws an error @ AND process and when checked in the display messages it shows 'BI_PROCESS_AND' status is cancelled because of which all th

  • Print encoding / print settings in PS CC 2014 compared to CS 3

    Hello, I used to work with PS CS3 but recently tried out CC 2014. In CS 3 when printing a document one could select the encoding options (JPEG, ASCII, Binary) - is this option completely gone in CC 2014? I've huge problems printing a PS document in C

  • Java FX 2.2 WebEngine

    Hi everyone, I'm using WebEngine and WebView classes for manipulating with html pages (JavaFX 2.2). As far as I know, there is embedded WebKit browser underneath. I would like to change parameters for WebKit like User-Agent, ... Is there any possibil