Won't paint to canvas

Hi,
I know this is a bit of a chunk of code but it is all beginner stuff. I posted earlier on this. It won't paint with the to the canvas.
Any help very much appreciated.
Warby
package Stejava;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/** An example class used to demonstrate the basics of
* creating components such as panels, arranging
* components using layout objects, and nesting
* components inside each other.
public class Assignment_2 extends JFrame
     JMenuBar menuBar;
     JMenu menu;
     JMenuItem menuItem;
     public JPanel grid, gridBag, flow, outputScreen, optionsBox, message, baseButtons,
          another, centreOne, centreTwo, centreThree, lower, style, size, colours, shapes,
          menuPane;
     JRadioButtonMenuItem rbMenuItem1, rbMenuItem2;
     public JTextField text;
     public JButton black, red, green;
     public JCheckBox checkStyle;
     /** Class constructor method
          * @param titleText Window's title bar text
     public Assignment_2( String titleText ) // constructor
          super( titleText );
          // listener for close event
          addWindowListener( new WindowAdapter() {
          /** End the program when the user
* closes the window
public void
windowClosing( WindowEvent e )
Assignment_2.this.dispose();
System.exit( 0 );
               }// end windowclosing()
          }// end WindowAdaptor()
          // end parameter listing of addWindowListener(). No code it seems.
          // menu bar
          menuBar = new JMenuBar();
setJMenuBar(menuBar);
          //Build the first menu.
menu = new JMenu("A Menu");
menuBar.add(menu);
          //a group of JMenuItems
menuItem = new JMenuItem("none" );
          menu.add(menuItem);
menuItem = new JMenuItem("Point" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Line" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Triangle" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Square" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Circle" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Oval" );
          menu.add(menuItem);
          menuItem = new JMenuItem("Text" );
          menu.add(menuItem);
          outputScreen = new JPanel();
          outputScreen.setSize(300,240);
          outputScreen.setMinimumSize(new Dimension(300, 200) );
          outputScreen.setPreferredSize( new Dimension(300, 200 ));
          outputScreen.setBorder(BorderFactory.createTitledBorder( "Output" ) );
          outputScreen.setLayout( new BorderLayout() );
          style = new JPanel();
          style.setBorder(BorderFactory.createTitledBorder( "Style" ) );
          style.setLayout( new GridLayout( 0, 1 ) );
          style.add( new JCheckBox( "Bold" ) );
          style.add( new JCheckBox( "Italics" ) );
          size = new JPanel();
          size.setBorder(BorderFactory.createTitledBorder( "Size" ) );
          size.setLayout( new BoxLayout( size, BoxLayout.Y_AXIS));
          size.setMinimumSize(new Dimension(100, 100) );
          size.setPreferredSize( new Dimension(100, 100 ));
          menuPane = new JPanel();
          menuPane.setBorder(BorderFactory.createTitledBorder( "" ) );
          menuPane.setMinimumSize( new Dimension(250, 400));
          menuPane.setLayout( new BorderLayout() );
          menuPane.add( menuBar );
          centreOne = new JPanel();
          centreOne.setBorder(BorderFactory.createTitledBorder( "Text Options" ) );
          centreOne.setLayout( new GridLayout( 0, 1 ) );
          centreOne.setMinimumSize(new Dimension(100, 220) );
          centreOne.setPreferredSize( new Dimension(100, 220 ));
          centreOne.add( style );
          centreOne.add( size );
          centreTwo = new JPanel();
          centreTwo.setBorder(BorderFactory.createTitledBorder( "Colours" ) );
          centreTwo.setLayout( new GridLayout( 0, 1 ) );
          centreTwo.setMinimumSize(new Dimension(100, 220) );
          centreTwo.setPreferredSize( new Dimension(100, 220 ));
          //centreTwo.add ( colours );
          centreThree = new JPanel();
          centreThree.setBorder(BorderFactory.createTitledBorder( "Shapes" ) );
          centreThree.setLayout( new BorderLayout() );
          centreThree.setPreferredSize( new Dimension(100, 220 ));
          centreThree.setMinimumSize( new Dimension(100, 220));
          centreThree.add ( menuPane );
          optionsBox = new JPanel();
     //optionsBox.setLayout( new BorderLayout() );
          optionsBox.setPreferredSize( new Dimension(300, 220 ));
          optionsBox.setMinimumSize( new Dimension(300, 220));
          optionsBox.setSize ( 300, 220 );
          optionsBox.add ( centreOne );
          optionsBox.add ( centreTwo );
          optionsBox.add ( centreThree );
          lower = new JPanel();
          lower.setBorder(BorderFactory.createTitledBorder( "" ) );
          lower.setMinimumSize( new Dimension(250, 400));
          lower.setLayout( new GridLayout( 0, 1 ) );
          message = new JPanel();
          message.setBorder(BorderFactory.createTitledBorder("Message" ) );
          message.setLayout( new BorderLayout() );
          text = new JTextField( "hhhh" );
          message.add( text, BorderLayout.CENTER );
          //button bar and buttons
          baseButtons = new JPanel();
          baseButtons.setBorder( BorderFactory.createTitledBorder( "" ) );
          baseButtons.setLayout( new FlowLayout( FlowLayout.CENTER ) );
          black = new JButton( "About" );
          black.addActionListener( new ButtonListener( Color.black ) );
          baseButtons.add( black );
          red = new JButton( "Draw" );
          red.addActionListener( new ButtonListener( Color.red ) );
          baseButtons.add( red );
          green = new JButton( "Exit" );
          green.addActionListener(new ButtonListener( Color.green ) );
          baseButtons.add( green );
          // radio buttons for text size
          menu.addSeparator();
ButtonGroup group1 = new ButtonGroup();
          size.setLayout( new GridLayout( 0, 1 ) );
          rbMenuItem1 = new JRadioButtonMenuItem("Small");
group1.add(rbMenuItem1);
size.add(rbMenuItem1);
rbMenuItem1 = new JRadioButtonMenuItem("Medium");
group1.add(rbMenuItem1);
size.add(rbMenuItem1);
          rbMenuItem1 = new JRadioButtonMenuItem("Large");
group1.add(rbMenuItem1);
size.add(rbMenuItem1);
          // radio buttons
          menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
          //size.setLayout( new FlowLayout( FlowLayout.CENTER ) );
          rbMenuItem2 = new JRadioButtonMenuItem("Black");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
rbMenuItem2 = new JRadioButtonMenuItem("Red");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
          rbMenuItem2 = new JRadioButtonMenuItem("Orange");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
          rbMenuItem2 = new JRadioButtonMenuItem("Yellow");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
rbMenuItem2 = new JRadioButtonMenuItem("Green");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
          rbMenuItem2 = new JRadioButtonMenuItem("Blue");
group2.add(rbMenuItem2);
centreTwo.add(rbMenuItem2);
          //aCanvas.repaint();
          //aCanvas.setSize( 100, 100 );
          //aCanvas.setVisible( true );
          //aCanvas.setLayout( new GridLayout( 0, 1 ) );
          //aCanvas.setMinimumSize(new Dimension(100, 100) );
          //aCanvas.setPreferredSize( new Dimension(100, 100 ));
          // container     
          Container cp = getContentPane();
          cp.setLayout( new BorderLayout() );
          cp.add( outputScreen, BorderLayout.NORTH );
          cp.add( optionsBox, BorderLayout.CENTER );
          cp.add( lower, BorderLayout.SOUTH );
          lower.add( message );
          lower.add( baseButtons );
          pack();
          setSize (350, 580);
          setResizable( false );
          setVisible( true );
          outputScreen.add( new myCanvas() );
     }// ends what ??? Constructor???
                    //inner class for painting
     class myCanvas extends Canvas
          /** Class constructor
               public myCanvas()
                    repaint();
                    setBackground( Color.white );
                    //setBorder( BorderFactory.createTitledBorder( "Sample output from drawing methods:" ) );
               }// end paint constructor
          public void paint(Graphics g)
               super.paint(g); // clears background
               g.drawLine( 50, 50, 100, 200 );
               g.setColor( Color.blue );
               g.drawRoundRect( 150, 300, 100, 125, 15, 15 );
               g.setColor( Color.red );
               g.fillOval( 400, 200, 50, 180 );
          }// end method paint()     
     } // end myClass;
          //myCanvas aCanvas = new myCanvas();
/** The class representing the button event
* listeners
class ButtonListener implements ActionListener
     public Color c;
/** Class constructor
* @param c the color for this button
public ButtonListener( Color c )
this.c = c;
/** Respond to the action events
* @param e The click event
public void actionPerformed( ActionEvent e )
text.setForeground( c );
          outputScreen.repaint(7);
          //outputScreen.aCanvas.paint();
}// end class ButtonListener()
/** The class representing the colored icons on
* the buttons
class ColorIcon implements Icon
public Color c;
public static final int DIAMETER = 10;
/** Class constructor
* @param c the color for this button
public ColorIcon( Color c )
this.c = c;
/** Paint the color icon with a black border
* @param cp the component holding the icon
* @param g the graphics context for the icon
* @param x the x draw start position
* @param y the y draw start position
public void paintIcon( Component cp, Graphics g, int x, int y )
g.setColor( c );
g.fillOval( x, y, DIAMETER, DIAMETER );
g.setColor( Color.black );
g.drawOval( x, y, DIAMETER, DIAMETER );
/** Get the icon's height
* @return the height of the icon
public int getIconHeight()
return DIAMETER;
/** Get the icon's width
* @return the width of the icon
public int getIconWidth()
return DIAMETER;
}// end class colorIcon
}// end colorIcon
/** The test method for the class
* @param args not used
public static void main( String[] args )
new Assignment_2( "Assignment_2" );
}// end class Assignment_2

No, does not look correct.
Canvas is a "heavyweight" awt component.
It is generally a bad idea to mix these with the "lightweight" swing JComponents.
Forget that and let's move on
Paint directly on the JPanel
example(strech and maximize to see what happens):import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
   public Test()
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setSize(100,100);
      OutputScreen oScr = new OutputScreen();
      getContentPane().add(oScr, BorderLayout.CENTER);
      oScr.setToolTipText("<html>Test<br>Patern</html>");
   public static void main(String[] args)
          new Test().setVisible(true);
class OutputScreen extends JPanel
   public void paint(Graphics g)
      Rectangle r = getBounds();
      g.setColor(Color.white);
      g.clearRect(r.x, r.y, r.width, r.height);
      g.setColor(Color.red);
      g.fillOval(r.x, r.y, r.width, r.height);
}

Similar Messages

  • Painting on canvas in native cocoa

    Hi Friends,
    I need a make a java canvas in which i have to paint thumbnail images by native cocoa code.
    I had got drawing surface(ds) and drawing surface interface(dsi).Also i am able to read the thumbnail images but donot know how to paint images in canvas using cocoa.
    Please suggest and if possible give some example or code sample.
    Thanks in advance.

    the bare minimum to render to a fullscreen frame in the fastest way possible...
    Frame f = new Frame();
    f.getGraphicsConfiguration().getDefaultDevice().setFullScreenWindow(f);
    f.createBufferStrategy(2);
    BufferStrategy bs = f.getBufferStrategy();
    Random r = new Random();
    while(true)
       Graphics g = bs.getDrawGraphics();
       g.setColor(new Color(r.nextInt));
       g.fillRect(0,0,getWidth(),getHeight());
       g.dispose();
       bs.show();
    }

  • How to Achieve Oil Painting on Canvas Effect?

    A friend took a picture of an portrait of her grandfather painted in oil on canvas.  She has asked me to "Photoshop" the picture so that the canvas effect shows up in the picture.  I use PSE 8 in Win 7.  Thanks.

    Filter>Texture>Texturizer>Canvas. However, you may need to play with this to make it large enough to show in a print, if that's your intended output.
    You might also try loading a burlap texture, which may give a more visible woven effect.

  • File generator words won't show up Canvas

    I'm using Motion 4 and I'm trying to create a promo video like the NBA Big Playoffs where the words flash on the screen.
    I tried to use the file generator and opened up a .txt file, but the words won't show up in Canvas.
    Any suggestions?

    If you go into Library > Generators, there's a generator called File. It allows you to use a .txt file as a text source. It can be used to either "flash" single lines of text from the file, or randomly display lines of text from a file.

  • Why won't Painter erase a keyword on only ONE image at a time?

    This has been driving me crazy - I'd like to delete a keyword on select images. I have hundreds of keywords and many are nested, so sometimes I screw up and need to erase selectively. I thought this problem was a bug, but it has persisted into LR 2.4!
    In Grid mode, I select Painter, choose a keyword and search through images where the eraser icon shows. However, if I then click on that image, Lightroom sometimes erases that one image, but more commonly erases four or five at a time! (No, they aren't highlighted.)
    Any ideas? I'd sure appreciate them!
    Deb

    Thanks, Ian, but now I think it's a bug, not me. Occasionally, erasing with the Painter tool works fine, but more often it's truly a spray can out of control! I am using a tablet, not a mouse. Even if I highlight one image and then click quickly on the Painter, sometimes it will erase 3-6 additional images. I can't figure a rhyme or reason, except it seems more likely when I have hundreds of images showing.
    I had wondered if there was a way to set the Painter to only erase one image at a time. If I slide it over images (like spraying), it often is out of control.
    Thanks!

  • Calculated field won't display on canvas

    I am importing login and logout times to Xcelsius v 5.4.0.0 using a web service.  Once the data is imported I am calculating the minutes between the login and logout by subtracting the login from the logout in the Xcelsius spreadsheet.
    I import DATE, USER, LOGIN, & LOGOUT to columns A:D in  my spreadsheet.  Column E contains the formula D2 - C2 to calculate the minutes, where D2 is the logout and C2 is the login.
    I cannot get the calculated times to display on the canvas.  I have tried both a list view and a spreadsheet table.  I set the DISPLAY DATA property of either the list view or spreadsheet table to columns A:E in my spreadsheet.  When I do Preview and import my data, all the data shows up EXCEPT THE MINUTES CALCULATION.  That field is always blank.
    I tried displaying the raw data tab, and the minutes calc is always blank. I created another tab named display data, added formulas to it to copy over the info from the raw data tab and tried displaying that instead.  I thought perhaps the actual calculation was causing a problem.  That didnu2019t work either.  The minutes calc column is always blank.
    I tried changing the format of the labels in the spreadsheet table or list view from general to numeric to time, but it makes no difference.  There is no data in the column to format.
    If I paste data into the spreadsheet while in design mode, the calculated minutes DO APPEAR in the list view on the canvas.  If I then go to Preview mode, the data is still there, including the calculated minutes. However as soon as I give it a new date range in Preview mode and refresh the data through the web service, the minutes column is again blank.
    Since the list view does display the calculated minutes if I paste data in the spreadsheet in design mode, and since the exported spreadsheet snapshot contains the correct calculations when I import data using the web service,  it appears that the data is being displayed on the canvas before the time calculations are taking place, resulting in a blank column.
    Has anyone else experienced this?  What am I doing wrong?  I am sure I should be able to do this, but evidently donu2019t understand how. Iu2019ve attached the exported spreadsheet snapshot as a reference.
    Thanks!

    Hi there - I checked your site on my PC and it does not display. I've found this on a number iWeb created site, so you are not alone.
    However, I have found iWeb created sites that display well on PC's, they are http://leapfrogenterprise.com and http://donandkasha.com - if you view the 'source', notice they used frames to display their site... Best wishes on your project, Rick
    iMac G5 iSight 20" - 30G iPOD - HP Pav 15" WS and Toshiba Sat 17" WS   Mac OS X (10.4.7)   Canon 20D & A620

  • Painting on Canvas or Applet?

    1) I have been writing an RPG for some time using j2sdk1.4.1_01 in windowsxp, The main component I'm drawing on is now a Canvas but was originally an Applet, Which is a better choice to use? I am using a double buffering system with VolatileImage and Fullscreen Exclusive mode with a Frame at 640x480 screen size. I have set the framerate to repaint at 25 fps. 2) Any performance boosting suggestions?

    the bare minimum to render to a fullscreen frame in the fastest way possible...
    Frame f = new Frame();
    f.getGraphicsConfiguration().getDefaultDevice().setFullScreenWindow(f);
    f.createBufferStrategy(2);
    BufferStrategy bs = f.getBufferStrategy();
    Random r = new Random();
    while(true)
       Graphics g = bs.getDrawGraphics();
       g.setColor(new Color(r.nextInt));
       g.fillRect(0,0,getWidth(),getHeight());
       g.dispose();
       bs.show();
    }

  • Re: adding canvas to applet

    Hi
    I am trying to add a canvas to an applet. I am successful in doing so. There is a JMenuBar added to the applet. when I click on the file menu The contents are being displayed behind the canvas and as a result I am neither able to see the buttons nor select them. Could some one help me with this.
    Note: Once you compile the code you wouldn't be able to see the contents right away. Click on left top,immidiately below the applet menu. This will repaint the contentpane. This is some thing I am working on.
    applet class
    package aple;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Shape;
    import java.awt.geom.AffineTransform;
    import java.util.ArrayList;
    import javax.swing.JApplet;
    public class NewJApplet extends JApplet{
        public Graphics2D g2;
        AffineTransform atf = new AffineTransform();
        sketch sk = new sketch();   
            @Override
        public void init() {      
            getContentPane().add(sk);
           Gui gui = new Gui();
            // menubar
            this.setJMenuBar(gui.Gui());     
        @Override
    gui class
    package aple;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class Gui {
        JMenuBar menuBar;
        JMenu file,edit,insert,view,draw,circle;
        JMenuItem nu,close,saveAs,open,centreandradius,line,rectangle,point,arc;
        public JMenuBar Gui(){
            //Menubar
            menuBar = new JMenuBar();
            //Menus
            file = new JMenu("File");
            menuBar.add(file);
            edit = new JMenu("Edit");
            menuBar.add(edit);
            view = new JMenu("View");
            menuBar.add(view);
            insert = new JMenu("Insert");       
            draw = new JMenu("Draw");
            circle = new JMenu("Circle");
            draw.add(circle);
            insert.add(draw);       
            menuBar.add(insert);
            //MenuItems
            nu = new JMenuItem("New");
            file.add(nu);
            open = new JMenuItem("Open");
            file.add(open);
            saveAs = new JMenuItem("SaveAs");
            file.add(saveAs);
            close = new JMenuItem("Close");
            file.add(close);
            line = new JMenuItem("Line");
            draw.add(line);
            centreandradius = new JMenuItem("Centre and Radius");
            circle.add(centreandradius);
            rectangle = new JMenuItem("Rectangle");
            draw.add(rectangle);
            point = new JMenuItem("Point");
            draw.add(point);
            arc = new JMenuItem("arc");
            draw.add("Arc");
            return(menuBar);
    sketch class
    package aple;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    public class sketch extends Canvas{
        public void sketch(){
            this.setBackground(Color.green);
        @Override
        public void paint(Graphics g){
         // g.fillRect(50,50, 50, 50); 
    }

    When you were using JPanel, your "setBackground" didn't work because you were overriding its paint(Graphics) method without calling "super.paint(g);". If you don't do this, the panel won't paint its background.
    You should also override "protected void paintComponent(Graphics g)" in any JComponent, such as JPanel, instead of just "paint(Graphics)". (And don't forget to call super.paintComponent(g) FIRST in your subclass's overridden method, if you want the background painted):
    class MyJPanelSubclass extends JPanel {
       protected void paintComponent(Graphics g) {
          super.paintComponent(g); // Paints background and any other stuff normally painted.
          // Do your custom painting here.
    }

  • Photoshope Elements when selecting an action, the paint brush tool doesn't work and system keeps freezing, then catching up every 30-45 seconds

    I have been having this problem with elements ever since the last OS upgrade, but it wasn't all the time and it wasn't very bad. Now, I have upgraded my macbook again, and I cannot even edit a photo!! I open the photo, choose an action, say "smooth skin", then choose the paint brush, I start to "paint" over their face and it won't paint a line, I have to keep clicking it, click - it paints, move brush, click again - it paints. Plus, every time I choose a tool or an action, it freezes for about 10 seconds, then catches up to what I am doing, 30 seconds later, it freezes again. HELP!! I have 8 sessions to finish editing by this weekend!! I just want to cry!!

    Try deleting the prefs and the saved application state:
    A Reminder for Mac Folks upgrading to Yosemite | Barbara's Sort-of-Tech Blog

  • Convert photo to oil on canvas?

    Is there a way to do this? I've played around with some of the filters and stuff - artistic, sketch, water colors, etc - as well as some of the background layer options in some of these filters as well. I'm just not that familiar with how they all work and what they're meant to do.
    What I want to do is to convert a family photo to look like it was given the 'painted on canvas' look that some professional studios offer - such as for senior pictures or family portraits and the like. Suitable for framing in other words.
    Is there anyone familiar with that process and how it might be done in a few PSE 3 steps?
    Thanks,
    Dennis

    Dennis,
    You can get the canvas texture part of your request by clicking Filter >
    Texture > Texturizer...
    Select Canvas from the Texture drop-down, and adjust the other parameters to
    your preference. If you don't like the outcome, just Undo and try again
    with different settings.
    As far as the oil part of your request - someone else will need to advise,
    as I have no eye for that sort of thing.
    HTH,
    Byron

  • How to smooth lines of original oil painting

    I had an artist paint an oil painting (on canvas) of our wedding venue to use as part of our wedding invitation. However, I didn't realize how an oil painting would print on paper and the brush strokes are nonuniform and visible. How can I smooth out the brush strokes?

    50mm will be fine.  I expect its sweet spot will be around f8
    Align the lens axis with the center of the image and perpendicular to the image.
    If the sun is bright, find some shade.  In fact find some shade anyway.
    Use a tripod
    Take a test image with a sheet of white paper in front to the painting to set white balance to in Photoshop. But try to take the image well away from any brightly coloured surfaces that might reflect colour onto the painting.
    DO NOT USE FLASH
    Try and leave an inch or two of space around the painting.  This will help you square it up in Photoshop
    Later versions of Photoshop have a Perspective Crop tool that would let you correct any out of squareness of the photograph, but you can still do this with CS5
    Open the image, and make any adjustments like black and white point.
    Copy the background layer.
    Turn on the grid (Ctrl ')
    Free Transform (Ctrl t)
    Hold down the Ctrl key, and drag each corner in turn to align the edges to the grid to square it up.
    Crop out what is left.
    Sharpen for print (View at 60% and go by the preview)
    Be amazed by how much better it looks compared to the scanned version
    Have a great special day, and best wishes to your SO
    Now that's definitely me for today. (12.39am and I NEED my sleep)

  • Change origin of canvas

    hey, i have a canvas that positions itself in the middle of the screen with two lines (x and y axis). the problem is that i want to be able to move the origin, which then draws the axis again.
    thanks
    Pedge
    // GCanvas.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This class extends the canvas class to include the input and drawing of a polygon
    * @author Geoff Hobson
    * @version 1.1 (24 Nov 99)
    class GCanvas extends Canvas
    * the polygon object associated with this canvas.
    private GPolygon polygon;
    * indicates whether currently in process of colecting the vertices of a polygon.
    private boolean building = false;
    * the size of one pixel in the logical coordinates of the polygon - the scaling factor.
    float pixelSize;
    * the screen x coordinate of the logical origin - screen x position of y-axis.
    int centerX;
    * the screen y coordinate of the logical origin - screen y position of x-axis.
    int centerY;
    * the radius of the circle around the start point,
    * a mouse press anywhere in this circle will be treated as selecting the centre point.
    private int circleSize = 3;
    * Constructs a GCanvas and associates it with the given Polygon poly.
    * @param poly the polygon object which is to be drawn and manipulated
    GCanvas(GPolygon poly)
    polygon = poly;
    addMouseListener
    (new MouseAdapter()
    { public void mousePressed(MouseEvent evt)
    pointSelected(evt.getX(), evt.getY());
    ); // end of new MouseAdapter
    setBackground(Color.gray);
    private int cX, cY;
    * clears the canvas and sets it ready for the input of a new polygon.
    public void newPoly()
    building = true;
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    repaint();
    * The action to be performed when a point is selected by a mouse press.
    * @param x the x coordinate of the selected point
    * @param y the y coordinate of the selected point
    private void pointSelected(int x, int y)
    if (building)
    addVertex(x, y);
    * Add a new vertex to the polygon object
    * @param x the x coordinate of the new vertex
    * @param y the y coordinate of the new vertex
    private void addVertex(int x, int y)
    if (polygon.size() == 0)
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add first vertex to a polygon
    else
    Point2D v0 = polygon.getVertex(0);
    int dx = x - iX(v0.x), dy = y - iY(v0.y);
    if (dx * dx + dy * dy < circleSize * circleSize)
    {    // mouse in circle around first vertex
    polygon.closePolygon(); // the polygon has been closed
    building = false;
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    else
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add an other vertex to polygon
    repaint();
    * Converts logical to screen x coordinate
    * @param x the logical x coordinate
    * @return the screen x coordinate
    int iX(float x)
    return Math.round(centerX + x/pixelSize);
    * Converts logical to screen y coordinate
    * @param x the logical y coordinate
    * @return the screen y coordinate
    int iY(float y)
    return Math.round(centerY - y/pixelSize);
    * Converts screen to logical x coordinate
    * @param x the screen x coordinate
    * @return the logical x coordinate
    float fX(int x)
    return (x - centerX) * pixelSize;
    * Converts screen to logical y coordinate
    * @param x the screen y coordinate
    * @return the logical y coordinate
    float fY(int y)
    return (centerY - y) * pixelSize;
    * Paints the canvas with current state of polygon
    * @param g the graphic context for the paint method
    public void paint(Graphics g)
    // initialise a blank canvas and draw axes etc
    int maxX = getSize().width - 1; // get size of screen
    int maxY = getSize().height - 1;
    float rWidth = polygon.logicalWidth(); // get logical size of polygon
    float rHeight = polygon.logicalHeight();
    pixelSize = Math.max(rWidth/maxX, rHeight/maxY); // calculate scaling factor
    centerX = maxX/2; // calculate position of axes
    centerY = maxY/2;
    int left = iX(-rWidth/2); // calculate edges of logical polygon
    int right = iX(rWidth/2);
    int bottom = iY(-rHeight/2);
    int top = iY(rHeight/2);
    // draw white rectangle for logical polygon
    g.setColor(Color.white);
    g.fillRect(left, top, right - left+1, bottom - top+1);
    // draw frame around logical polygon rectangle
    g.setColor(Color.darkGray);
    g.drawRect(left, top, right - left, bottom - top);
    g.setColor(Color.lightGray);
    g.drawLine(left,centerY, right,centerY); // draw x axis
    g.drawLine(centerX,top, centerX,bottom); // draw y-axis
    // draw current state of the polygon
    int n = polygon.size();
    if (n == 0) return; // if there are no vertices
    Point2D A, B;
    A = (polygon.getVertex(0));
    // Show tiny circle around first vertex:
    g.setColor(Color.red);
    if (!polygon.isClosed())
    g.drawOval(iX(A.x)-circleSize, iY(A.y)-circleSize, circleSize*2, circleSize*2);
    // draw the polygon
    g.setColor(Color.blue);
    for (int i=1; i<n; i++)
    B = (polygon.getVertex(i));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    A = B;
    if (polygon.isClosed()) // draw side from last to first vertex
    B = (polygon.getVertex(0));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    } // end of paint
    } // end of class GCanvas

    How about declaring changing centerx and centery in the constructor?

  • Canvas screen

    i'm using the palm os emulator and can't seem to get the whole screen when i want to paint a canvas.
    i use getWidth and getHeight to get the size of the canvas and paints the entire thing but for some reason, there is always an area below that can't be painted. it's the area where all the commands would normally appear. how do i paint the entire screen?

    Hi,
    You cannot use full screen when you are using canvas. for that you have to use FullCanvas whicg comes in MIDP 2.0, but beware not all device supports this, even some device that are MIDP 2.0 compatible does not support FullCanvas.

  • Canvas and BufferedImage display different.

    I use the same method to paint the Canvas and the BufferedImage. But the Graphics2D drawString method
    shows up correctly on the Canvas but not on the BufferedImage (JPEG). Why is there a difference?
    I use the Graphics2D to rotate the text 90 degrees.
    I can't think of any reason why the display comes out different.
    Any suggestions???
    Thanks.

    Here is the code for putting the Canvas graphics onto the BufferedImage (JPEG).
    public void save(HCanvas comp) {
         int w = comp.getWidth();
         int h = comp.getHeight();
         Frame frame = new Frame();
         BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
         Graphics2D g2 = im.createGraphics();
         g2.setPaint(Color.white);
         g2.fillRect(0,0,w,h);
         g2.setPaint(Color.black);          // back to default color
         comp.paint(g2);                              // Graphics argument
         g2.dispose();
         FileDialog fd = new FileDialog(frame,"Save As JPEG",FileDialog.SAVE);
         fd.show();
         try {
              String dum;
              dum = fd.getDirectory() + fd.getFile();
              OutputStream out = new FileOutputStream(dum);
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              encoder.encode(im);
              out.flush();
              out.close();
              im.flush();
         } catch (Exception FileNotFoundException) {
              String errormsg = "File Not Assigned";
              JOptionPane.showMessageDialog(frame, errormsg);

  • Canvas and BufferedImage display drawString differently.

    I use the same method to paint the Canvas and the BufferedImage. But the Graphics2D drawString method
    shows up correctly on the Canvas but not on the BufferedImage (JPEG). Why is there a difference?
    I use the Graphics2D to rotate the text 90 degrees.
    I can't think of any reason why the display comes out different.
    Any suggestions???
    Thanks.

    Here is the code for putting the Canvas graphics onto the BufferedImage (JPEG).
    public void save(HCanvas comp) {
    int w = comp.getWidth();
    int h = comp.getHeight();
    Frame frame = new Frame();
    BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = im.createGraphics();
    g2.setPaint(Color.white);
    g2.fillRect(0,0,w,h);
    g2.setPaint(Color.black); // back to default color
    comp.paint(g2); // Graphics argument
    g2.dispose();
    FileDialog fd = new FileDialog(frame,"Save As JPEG",FileDialog.SAVE);
    fd.show();
    try {
    String dum;
    dum = fd.getDirectory() + fd.getFile();
    OutputStream out = new FileOutputStream(dum);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(im);
    out.flush();
    out.close();
    im.flush();
    } catch (Exception FileNotFoundException) {
    String errormsg = "File Not Assigned";
    JOptionPane.showMessageDialog(frame, errormsg);

Maybe you are looking for