Static canvas

Hi,
How do you make a canvas class static, I have an applet which contains a canvas 'can', when I try and call this canvas from another class - can.repaint() in a mouselistener, I keep getting can't reference a static method from a non static context.
can anyone help please!
NTK1

Hope this helps://
//  Applet1.java
import java.awt.*;
import java.awt.Graphics2D.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.*;
//this is the class with the canvas to be repainted
public class Applet1 extends JApplet implements ActionListener{
    Applet1Canvas can = new Applet1Canvas();
    Button SurveyButton;
    public final static TextArea appletTextArea = new TextArea("no value yet");
    //Global drawing canvas object
    //Initialize the applet
    public void init() {
        try {
            jbInit();
        }catch(Exception e) {
            e.printStackTrace();
    private void jbInit() {
        SurveyButton = new Button("Survey");
        SurveyButton.addActionListener(this);
        can.add(appletTextArea, BorderLayout.NORTH);
        can.add(SurveyButton, BorderLayout.CENTER);
        setContentPane(can);
    public void actionPerformed(ActionEvent e) {
        if ( e.getSource() == SurveyButton ) {
            MyFrame SurveyFrame = new MyFrame(can);
            //trying to pass canvas object to frame class
    static class Applet1Canvas extends JPanel {
        // Define paint() method for 2D graphical output
        public void paint(Graphics screen) {
            Graphics2D screen2D = (Graphics2D)screen;
            super.paint(screen2D);
        public void setText(String txt) {
            appletTextArea.setText(txt);
//  MyFrame.java
import java.awt.*;
import java.awt.Graphics2D.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
//frame class with mouse events
public class MyFrame extends JFrame implements MouseListener, MouseMotionListener{
    MyFrameCanvas SurveyCan = new MyFrameCanvas();
    Applet1.Applet1Canvas m_canvas;
    public MyFrame(Applet1.Applet1Canvas c) {
        m_canvas = c;
        addMouseListener(this);
        addMouseMotionListener(this);
        SurveyCan.setBackground(Color.white);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
        try {
            jbInit();
        }catch(Exception e) {
            e.printStackTrace();
        setBounds(200,200,200,390);
        show();
    static class MyFrameCanvas extends JPanel {
        // Define paint() method for 2D graphical output
        public void paint(Graphics screen) {
            Graphics2D screen2D = (Graphics2D)screen;
            super.paint(screen2D);
    public void mouseMoved(MouseEvent e) {
    public void mouseDragged (MouseEvent e) {
        System.out.println(e.getX() + " " + e.getY());
        SurveyCan.repaint();
        m_canvas.setText("mouse dragged at "+e.getX() + " " + e.getY());
        m_canvas.repaint();
    public void mousePressed(MouseEvent e) {
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    private void jbInit() throws Exception {
        JLabel instructionLabel
            = new JLabel(
                "<html><center><font face=\"Arial\"><b><br><br>"+
                "drag mouse here<br>to change applet value"+
                "</b></font></center></html>");
        SurveyCan.add(instructionLabel, BorderLayout.CENTER);
        setContentPane(SurveyCan);
}

Similar Messages

  • Libraries in new version of Solaris functionally similar to suntools

    Please find a C++ program attached . This program was used by my Professor a few years back and it uses some libraries in Suntools: sunview, canvas, etc. Since Suntools is no longer in use in the present versions of Solaris, I am not able to run the program. Please have a look at the C++ program and provide me with some information about the libraries to be included which could carryout the same function as sunview,canvas etc.
    Thank You
    filename="sun.c"
    #include <stdio.h>
    #include <suntool/sunview.h>
    #include <suntool/canvas.h>
    #include <suntool/panel.h>
    #include <suntool/tty.h>
    static Frame frame;
    static Canvas canvas;
    static Panel panel;
    static Pixwin *pw;
    static Tty tty;
    Panel_item fname_item1, fname_item2;
    int screenxsize, screenysize;
    float factor;
    static void inputdata(), mesh(), pressure(), laser(), quit_proc(),
    resize_proc(),
    velocity(), horivel(), vertvel(), streamline(), vorticity();
    main(argc, argv)
    int argc;
    char **argv;
    char name, getenv();
    /* try to quick check that we are in suntools */
    name = getenv("WINDOW_ME");
    if (!name)
    fprintf(stderr, "Apparently not in suntools.\n");
    fprintf(stderr, "Are you running this on the machine in front of
    you?\n");
    exit(0);
    frame = window_create(NULL, FRAME,
    WIN_WIDTH, 640,
    WIN_HEIGHT, 693,
    FRAME_ARGS, argc, argv,
    FRAME_LABEL, "CFD Lab (Lin)",
    0);
    panel = window_create(frame, PANEL, 0);
    /* make a panel at the top that reads a file name and has "doit" and
    "quit" buttons */
    create_panel_items();
    /* create a canvas below to draw into */
    canvas = window_create(frame, CANVAS,
    CANVAS_RESIZE_PROC, resize_proc,
    0);
    /* make a pixwin */
    pw = canvas_pixwin(canvas);
    /* start the window up */
    window_main_loop(frame);
    exit(0);
    create_panel_items()
    fname_item1 = panel_create_item(panel, PANEL_TEXT,
    PANEL_LABEL_STRING, "Plot File: ",
    PANEL_VALUE, "plot.data",
    PANEL_VALUE_DISPLAY_LENGTH, 30,
    0);
    /* make the button that will cause execution */
    fname_item2 = panel_create_item(panel, PANEL_TEXT,
    PANEL_LABEL_STRING, "Result File: ",
    PANEL_VALUE, "result.data",
    PANEL_VALUE_DISPLAY_LENGTH, 30,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel,
    "inputdata", 15, 0),
    PANEL_NOTIFY_PROC, inputdata,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel, "mesh",
    15, 0),
    PANEL_NOTIFY_PROC, mesh,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel,
    "pressure", 15, 0),
    PANEL_NOTIFY_PROC, pressure,
    0);
    /* make the button that will delete the window when you are done */
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel, "print",
    15, 0),
    PANEL_NOTIFY_PROC, laser,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel, "quit",
    15, 0),
    PANEL_NOTIFY_PROC, quit_proc,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel,
    "velocity", 15, 0),
    PANEL_NOTIFY_PROC, velocity,
    0);
    panel_create_item(panel, PANEL_BUTTON,
    PANEL_LABEL_IMAGE, panel_button_image(panel,
    "HoriVel", 15, 0),
    PANEL_NOTIFY_PROC, horivel,
    0);

    Hi ,
    Have you set UseAccounts=true in config.cfg for the new environment ?
    Thanks
    Srinath

  • Basic questions about programing for J9 VM

    I need to create a java application to run on a Pocket PC 2003 OS and I'm limited to using IBM's Websphere J9 Virtual Machine. I'm new to using java in this capacity and therefore have lots of questions which I'm guessing are pretty basic. Despite my best efforts, I've found very little to help me online. Below are a couple questions I have that I'm hoping someone can help me with. Even better, if you know of any resources that could help me with these and other questions, I'd love to have them. Thanks in advance.
    1. I'm using standard AWT for the GUI but I'm having problems getting frames, dialogs, etc., to come up in anything less then full screen. setSize() and resize() have no effect, even if I extend the frame and override the setMinimumSize, setPreferredSize, setMaximumSize methods. What do I need to do to get a child window to appear in something less than full screen?
    2. I'd like to be able to add menu's to the buttom toolbar (with the keyboard) but have no idea how I would add something to it. Can someone point me in the right direction?
    3. When my application gets an iconified event I go ahead and call a System.exit() to exit the application. This doesn't kill the java VM though, which continues to run in the background (taking up plenty of memory). If I run my application using the J9w.exe so that it runs without the console, then not only does the VM continue to run, but I have no way to stop it (the running program list can't see it). Since each time I run my application it starts a new VM, it only takes a couple of times before I'm out of memory and have to do a soft reset of the PDA to make things right. Can I kill the VM when I kill my application?
    4. I learn best by looking at example code, but have been unable to find any code people are running on J9. I have the GolfScoreTracker installed and running on my PDA, but the jar file contains only the classes. Since it's supposed to be a demo, I had hoped that the source code would be included, is that hoping too much or is the source code available somewhere? In addition, if you know of any applications out there with available source code that are known to run well on a PocketPC J9 environment I'd appreciate the link.

    Hi there, I saw your questions, im currently developing a java pocket pc application as well and here's what i go so far:
    AWT seem to be hard to use on pocket pc, instead i recommend that you use SWT, which is a technology developed by eclipse. It's already installed on the eclipse plugins, you just need to download the jar and dll files for the pocket pc. They are available at: http://www.eclipse.org/downloads/index.php
    I assume that you already have the J9 working on your device. So you only need to copy the SWT.jar file and the swt-win32-3064.dll to the folder containing the .class files on your device.
    Now, on your java IDE(im using eclipse) Add the SWT.jar library to your project which should be on C:/eclipse/plugins/org.eclipse.swt.win32_3.0.2/ws/win32/swt.jar or something like taht depending on your eclipse root.
    Now you are ready to code some SWT, here is a sample program from Carolyn MacLeod, i modified a few things so it could run on the pocket pc but it's almost the same. Once you coded in eclipse run it, then copy the class file from your desktop to your device(There should be like 4 or 5 classes like sample.class, sample$1.class etc. copy all of them) where you put the jar and dll files(If program does not run you may try to rename the dll file for swt-win32-3050.dll instead of 3064.dll). Now after you have everything set up you need to create the lnk file in order to run the program. On your desktop create a new textfile and write the following on it:
    255#"\Archivos de Programa\J9\PPRO10\bin\j9w.exe" "-jcl:PPRO10" "-cp" "\My
    Documents\Java\swt.jar" ;\My Documents\Java" sample
    Paths depend on your install, and the place where you put your classes and jar file. path for j9w is usually "\Program Files\J9\PPRO10\bin\j9w.exe", and the last word should be the classname.
    Currently this form only displays an image on a canvas, click on the browse button and choose a pic and it will display on the canvas. Im trying to connect the form to an oracle database but no success yet on the device.
    Hope it helps, if you have any questions about the code or something, and I know the answer, please feel free to ask.
    See ya
    import org.eclipse.swt.*;
    import org.eclipse.swt.widgets.*;
    import org.eclipse.swt.layout.*;
    import org.eclipse.swt.events.*;
    import org.eclipse.swt.graphics.*;
    public class sample {
    static Shell shell;
    static Display display;
    static Text dogName;
    static Text textdb;
    static Combo dogBreed;
    static Canvas dogPhoto;
    static Image dogImage;
    static List categories;
    static Text ownerName;
    static Text ownerPhone;
    static String[] FILTER_EXTS = {"*.jpg"};
    public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display, SWT.RESIZE | SWT.CLOSE);
    Menu menu = new Menu(shell, SWT.BAR);
    shell.setText("Dog ShowS Entry");
    shell.setMenuBar(menu);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    shell.setLayout(gridLayout);
    new Label(shell, SWT.NONE).setText("Dog's NameS:");
    dogName = new Text(shell, SWT.SINGLE | SWT.BORDER);
    GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.horizontalSpan = 2;
    gridData.widthHint = 60;
    dogName.setLayoutData(gridData);
    new Label(shell, SWT.NONE).setText("Breed:");
    dogBreed = new Combo(shell, SWT.NONE);
    dogBreed.setItems(new String [] {"Collie", "Pitbull", "Poodle", "Scottie"});
    dogBreed.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    Label label = new Label(shell, SWT.NONE);
    label.setText("Categories");
    label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    new Label(shell, SWT.NONE).setText("Photo:");
    dogPhoto = new Canvas(shell, SWT.BORDER);
    gridData = new GridData(GridData.FILL_BOTH);
    gridData.widthHint = 60;
    gridData.verticalSpan = 3;
    dogPhoto.setLayoutData(gridData);
    dogPhoto.addPaintListener(new PaintListener() {
    public void paintControl(final PaintEvent event) {
    if (dogImage != null) {
    event.gc.drawImage(dogImage, 0, 0);
    categories = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    categories.setItems(new String [] {
    "Best of Breed", "Prettiest Female", "Handsomest Male",
    "Best Dressed", "Fluffiest Ears", "Most Colors",
    "Best Performer", "Loudest Bark", "Best Behaved",
    "Prettiest Eyes", "Most Hair", "Longest Tail",
    "Cutest Trick"});
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
    gridData.widthHint = 60;
    gridData.verticalSpan = 4;
    int listHeight = categories.getItemHeight() * 12;
    Rectangle trim = categories.computeTrim(0, 0, 0, listHeight);
    gridData.heightHint = trim.height;
    categories.setLayoutData(gridData);
    Button browse = new Button(shell, SWT.PUSH);
    browse.setText("BrowsePic");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.widthHint = 60;
    browse.setLayoutData(gridData);
    browse.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
              FileDialog dialog = new FileDialog(shell, SWT.OPEN);
              dialog.setFilterExtensions(new String[] {"*.*"});
              String fileName = dialog.open();
    if (fileName != null) {
    dogImage = new Image(display, fileName);
    shell.redraw();
    Button delete = new Button(shell, SWT.PUSH);
    delete.setText("No action");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING);
    gridData.widthHint = 60;
    delete.setLayoutData(gridData);
    delete.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
    Button enter = new Button(shell, SWT.PUSH);
    enter.setText("No action");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
    gridData.horizontalSpan = 3;
    enter.setLayoutData(gridData);
    enter.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
         shell.open();
         while (!shell.isDisposed()) {
              if (!display.readAndDispatch())
                   display.sleep();
         display.dispose();
    if (dogImage != null) {
    dogImage.dispose();
    }

  • Pong Game - HELP

    Hi guys, I'd firstly like to apologise if I've posted in the wrong forum - as you've moved probably guessed, I'm new round "there here parts"! :P
    I recently started attempting some basic java graphics in a swing. So far, everything is working but I have the following questions:
    1) How do I stop the graphics flickering? - I know it's due to the thread refresh rate in the continuous loop, but can I stop the flickers?
    2) How do I add a JPanel ABOVE the canvas in which I can add buttons to restart the game? - I assume it would involve a GridBagLayout which I'm unfamiliar with, so your assistance would be appreciated. Note: I'll only need assistance in adding the JPanel above the canvas, I can do the rest! :)
    My current code is shown below - please don't complain about imperfections, as it's just a development:
    import javax.swing.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Pong
       private static JFrame frame;
       private static Canvas canvas;
       private static KeyListener listener;
       private static boolean inPlay = true;
       private static boolean gamePaused = false;
       private static int yP1 = 160;
       private static int yP2 = 160;
       private static Graphics Bgfx;
       private static boolean update = false;
       private static BufferedImage bi;
       private static int ballPosx = 600;
       private static int ballPosy = 200;
       private static int ballXSpeed = 1;
       private static int ballYSpeed = 1;
       private static int ballOffSetx = 1;
       private static int ballOffSety = -1;
       private static int paddleSpeed = 10;
       private static boolean winnerP1 = false;
       private static boolean winnerP2 = false;
       //Upper panel variables
       private static JPanel upperPNL;
       private static JButton restartButton;
       private static GridBagConstraints gbc;
       public static void main (String args[])
          //Initialize GUI
          frame = new JFrame("Pong Game");
           //Canvas / frame parameters
          canvas = new Canvas();
          canvas.setSize(1200, 500);
           //Content pane
           Container content = frame.getContentPane();
           content.add(canvas);
          frame.setIgnoreRepaint(true);                
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
          frame.pack();
          frame.setVisible(true);
           frame.addKeyListener(listener);
           frame.addKeyListener(new KeyListener() {
              public void keyPressed(KeyEvent e) {
                   if (e.getKeyCode() == 'Q') {
                        if (yP1 > 20) {
                             yP1 -= paddleSpeed;
                             update = true;
                      if (e.getKeyCode() == 'A') {
                           if (yP1 < 380) {
                             yP1 += paddleSpeed;
                             update = true;
                   if (e.getKeyCode() == 'P') {
                        if (yP2 > 20) {
                             yP2 -= paddleSpeed;
                             update = true;
                   if (e.getKeyCode() == 'L') {
                        if (yP2 < 380) {
                             yP2 += paddleSpeed;
                             update = true;
                   public void keyReleased(KeyEvent e) {
                   update = false;
                    public void keyTyped(KeyEvent e) {}
          gameLoop(canvas.getGraphics());                     //Begin Game Loop
       private static void gameLoop(final Graphics gfx)
          //Create a BufferedImage to use it's graphics.
          bi = new BufferedImage(1200, 500, BufferedImage.TYPE_INT_RGB);
          //While the game isn't paused
          while(inPlay)
         while(!gamePaused)
              try
                      Thread.sleep(1);
              catch(Exception ex)
                   System.out.println("Interrupted Sleep");
              gameRender(bi, gfx);
              moveBall();
              checkCollisions();
       private static void moveBall()
              if (winnerP1 || winnerP2) { ballOffSety = 0; ballOffSetx = 0; }
              ballPosx += ballXSpeed * ballOffSetx;
              ballPosy += ballYSpeed * ballOffSety;
              if (ballPosy < 0) {
                   ballOffSety *= -1;
              if (ballPosy > 500) {
                   ballOffSety *= -1;
              if (ballPosx < 0) {
                   ballOffSetx *= -1;
              if (ballPosx > 1200) {
                   ballOffSetx *= -1;
         private static void checkCollisions() {
              if ((ballPosx >= 72 && ballPosx <= 107) && (ballPosy >= yP1 && ballPosy <= (yP1 + 100)))
                   ballOffSetx *= -1;
              if ((ballPosx >= 1072 && ballPosx <= 1107) && (ballPosy >= yP2 && ballPosy <= (yP2 + 100)))
                   ballOffSetx *= -1;
              if (ballPosx < 107)
                   winnerP2 = true;
              if (ballPosx > 1107)
                   winnerP1 = true;
       private static void gameRender(BufferedImage bi, Graphics gfx)
           if (winnerP1) {
              bi.getGraphics();
              Font font = new Font("Arial", Font.PLAIN, 36);
              gfx.setFont(font);
              gfx.setColor(Color.RED);
              gfx.drawString("PLAYER 1 WINS!!!", 520, 200);
              gfx.drawImage(bi, 0, 0, null);
           if (winnerP2) {
              bi.getGraphics();
              Font font = new Font("Arial", Font.PLAIN, 36);
              gfx.setFont(font);
              gfx.setColor(Color.RED);
              gfx.drawString("PLAYER 2 WINS!!", 520, 200);
              gfx.drawImage(bi, 0, 0, null);
          //Get Buffered Graphics to Draw To
          Bgfx = bi.getGraphics();
          //Draw Background
          Bgfx.setColor(Color.BLACK);
          Bgfx.fillRect(0,0,1200,500);
          //Draw Bar 1
          gfx.setColor(Color.GREEN);
           gfx.fillRect(72,yP1,35,100);
          //Draw Bar 2
          gfx.fillRect(1072,yP2,35,100);
          //Draw Ball
          gfx.fillRect(ballPosx,ballPosy,20,20);
          //Draw the Buffered Graphics to the screen
          gfx.drawImage(bi, 0, 0, null);
    }Constructive criticism is welcomed, but major edits which I'm not likely to understand as of yet are not.
    Many thanks for your assistance, it's appreciated.
    Edited by: -Barto- on Jun 30, 2010 5:21 PM

    -Barto- wrote:
    Hi guys, I'd firstly like to apologise if I've posted in the wrong forum - as you've moved probably guessed, I'm new round "there here parts"! :PWelcome, and not to worry -- this is the correct forum for your question.
    I recently started attempting some basic java graphics in a swing. So far, everything is working but I have the following questions:
    1) How do I stop the graphics flickering? - I know it's due to the thread refresh rate in the continuous loop, but can I stop the flickers?
    2) How do I add a JPanel ABOVE the canvas in which I can add buttons to restart the game? - I assume it would involve a GridBagLayout which I'm unfamiliar with, so I think that you're main problem is that you're trying to mix AWT components (i.e., Canvas) and Swing components (everything else) in one program. In addition, you need to update your game loop and graphics to be in line with Swing best practices. So, get rid of Canvas, read up in the tutorials on how to do graphics in Swing (using paintComponent override for instance) and use a Swing Timer for your Game loop and you'll be half way there. Best of luck!

  • How to freeze stacked window vertically ?

    Hi all,
    I have a stacked windows with many column scroll vertically and horizontally. It is any way to freeze certain column on title and keep on scroll to the right hand size of the screen for some others column ? The freeze on vertical panel will work alike Mircosoft Excel and whether possible doing the same in form 6i ?
    Please advise.
    Thanks.
    Lim

    Hi in addition to what manu has already written. ensure that your canvas Viewport properties have
    been set correctly.
    For example the static canvas
    Functional
    Raise on Entry: Yes
    Viewport
    Viewport X Position: 5
    Viewport Y Position: 5
    Viewport Width: 12
    Viewport Height: 8
    The properties for the scrolling canvas
    Functional
    Raise on Entry: Yes
    Viewport
    Viewport X Position: 17
    Viewport Y Position: 4
    Viewport Width: 57
    Viewport Height: 9
    Physical
    Show Horizontal Scroll Bar: Yes

  • JS-Linter,a static javascript analysis extension for HTML5 Canvas documents in Flash Pro CC

    JSLinter is a  extension for Flash Pro CC for static code analysis of timeline javascript in ’HTML5 Canvas’ docs.It helps to detect errors and potential problems in your timeline javascript code .
    You can download the extension form my blog here
    http://hemanthkumarr.wordpress.com/2013/12/05/js-lintera-static-javascript-analysis-extens ion-for-html5-canvas-documents-in-flash-pro-cc/

    Checked just now .It is working for me and i can download the extension.
    Can you just verify again and let me know?
    -Hemanth

  • Place image on canvas

    Hi.
    I am trying to place image on canvas.
    However the image doesn't show!!!!!!!!!!!!! :(
    no error and compiles well....
    private void AddTile(String image, int startx, int starty, int endx, int endy)
    try{
    tiles = ImageIO.read(new File(image));
    catch(Exception e)
    System.out.println("Image not Found");
    Graphics2D a =(Graphics2D)tiles.getGraphics();
    a.drawImage(tiles, 20,20,20,20,TileCanvas);
    if the above function is called the image should be placed on canvas right?
    TileCanvas is a canvas, and tiles is BufferedImage.
    just in case I'll put my source code followed by this
    * MapEditor.java
    * Created on 2006�� 7�� 20�� (��), ���� 11:48
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.imageio.*;
    import java.io.*;
    * @author SeiKwon
    public class EditorComponent extends javax.swing.JFrame
    private java.awt.Button AddTile;
    private java.awt.Button DeleteTile;
    private javax.swing.JMenu FileMenu;
    private javax.swing.JMenuItem LoadFile;
    private javax.swing.JPanel ManageTilePanel;
    private java.awt.Canvas MapCanvas;
    private javax.swing.JMenuBar MenuBar;
    private javax.swing.JMenuItem SaveFile;
    private javax.swing.JScrollPane ShowMapScroll;
    private java.awt.Canvas TileCanvas;
    private javax.swing.JScrollPane TileScroll;
    private BufferedImage tiles;
    private int tilecount = 0;
    /** Creates new form MapEditor */
    public EditorComponent()
    initComponents();
    AddTile("test.jpg", 0, 0, 10, 10);
    private void initComponents()
    ManageTilePanel = new javax.swing.JPanel();
    TileScroll = new javax.swing.JScrollPane();
    TileCanvas = new java.awt.Canvas();
    AddTile = new java.awt.Button();
    DeleteTile = new java.awt.Button();
    ShowMapScroll = new javax.swing.JScrollPane();
    MapCanvas = new java.awt.Canvas();
    MenuBar = new javax.swing.JMenuBar();
    FileMenu = new javax.swing.JMenu();
    SaveFile = new javax.swing.JMenuItem();
    LoadFile = new javax.swing.JMenuItem();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    ManageTilePanel.setLayout(null);
    ManageTilePanel.setBorder(new javax.swing.border.TitledBorder("Tiles"));
    TileCanvas.setBackground(new java.awt.Color(255, 255, 255));
    TileScroll.setViewportView(TileCanvas);
    ManageTilePanel.add(TileScroll);
    TileScroll.setBounds(10, 22, 100, 230);
    AddTile.setLabel("Add");
    ManageTilePanel.add(AddTile);
    AddTile.setBounds(10, 260, 50, 26);
    DeleteTile.setLabel("Delete");
    ManageTilePanel.add(DeleteTile);
    DeleteTile.setBounds(60, 260, 50, 26);
    getContentPane().add(ManageTilePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 10, 119, 290));
    ManageTilePanel.getAccessibleContext().setAccessibleName("TilesPanel");
    MapCanvas.setBackground(new java.awt.Color(255, 255, 255));
    MapCanvas.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseEntered(java.awt.event.MouseEvent evt)
    MapCanvasMouseEntered(evt);
    ShowMapScroll.setViewportView(MapCanvas);
    getContentPane().add(ShowMapScroll, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 10, 290, 290));
    FileMenu.setText("File");
    FileMenu.setContentAreaFilled(false);
    SaveFile.setIcon(new javax.swing.ImageIcon("D:\\java\\MapEditor\\Image\\Save16.gif"));
    SaveFile.setText("Save");
    SaveFile.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(java.awt.event.ActionEvent evt)
    SaveFileActionPerformed(evt);
    FileMenu.add(SaveFile);
    LoadFile.setIcon(new javax.swing.ImageIcon("D:\\java\\MapEditor\\Image\\Open16.gif"));
    LoadFile.setText("Load");
    LoadFile.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(java.awt.event.ActionEvent evt)
    LoadFileActionPerformed(evt);
    FileMenu.add(LoadFile);
    MenuBar.add(FileMenu);
    setJMenuBar(MenuBar);
    pack();
    private void MapCanvasMouseEntered(java.awt.event.MouseEvent evt)
    Cursor cursorshape = MapCanvas.getCursor();
    MapCanvas.setCursor(cursorshape.getPredefinedCursor(CROSSHAIR_CURSOR));
    private void AddTile(String image, int startx, int starty, int endx, int endy)
    try{
    tiles = ImageIO.read(new File(image));
    catch(Exception e)
    System.out.println("Image not Found");
    Graphics2D a =(Graphics2D)tiles.getGraphics();
    a.drawImage(tiles, 20,20,20,20,TileCanvas);
    private void LoadFileActionPerformed(java.awt.event.ActionEvent evt)
    FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
    //fd.setFile("*.map");
    fd.setDirectory(".");
    fd.setVisible(true);
    String filename = fd.getFile();
    System.out.println(filename);
    private void SaveFileActionPerformed(java.awt.event.ActionEvent evt)
    FileDialog fd = new FileDialog(this, "Save", FileDialog.SAVE);
    //fd.setFile("*.map");
    //fd.setFilenameFilter("*.map"); // HOW TO USE?????????????
    fd.setDirectory(".");
    fd.setVisible(true);
    String filename = fd.getFile();
    System.out.println(filename);
    public static void main(String args[])
    java.awt.EventQueue.invokeLater(new Runnable()
    public void run()
    new EditorComponent().setVisible(true);
    }

    You have at least two problems.
    1) You are mixing AWT and Swing. Instead of using a Canvas you should use either a JComponent or a JPanel.
    2) In Swing, drawing such are you are doing should be done within the paintComponent(Graphics g) method using the Graphics provided as an argument to the method.
    P.S. I can't test you code because for some reason you feal the need to use a NetBeans specific layout manager.

  • How can I convert OPENGL canvas graphics into bitmap image format.

    I used the following code... but no conversion made... plz tell the write way..
    public static void savePaintingJPG(GLCanvas canvas, String fileName) {
            // saves the content of the 'panel' in a file 'file'.jpg
            String name = "";
    int framewidth = canvas.getSize().width; // get the canvas' dimensions
    int frameheight = canvas.getSize().height;
    System.out.println(framewidth);
    System.out.println(frameheight);
      java.nio.ByteBuffer pixelsRGB = BufferUtils.newByteBuffer(framewidth * frameheight * 3); // create a ByteBuffer to hold the image data
    GL gl = canvas.getGL(); // acquire our GL Object
          // read the Frame back into our ByteBuffer
    gl.glReadBuffer(GL.GL_BACK);
    gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1);
    gl.glReadPixels(0, 0, framewidth, frameheight, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, pixelsRGB);
    int[] pixelInts = new int[framewidth * frameheight*3];       // Convert RGB bytes to ARGB ints with no transparency. Flip image vertically by reading the
         // rows of pixels in the byte buffer in reverse - (0,0) is at bottom left in OpenGL.
    int p = framewidth * frameheight * 3; // Points to first byte (red) in each row.
         int q;   // Index into ByteBuffer
      int i = 0;   // Index into target int[]
      int w3 = framewidth*3;    // Number of bytes in each row
      for (int row = 0; row < frameheight; row++) {
        p -= w3;
        q = p;
        for (int col = 0; col < framewidth; col++) {
          int iR = pixelsRGB.get(q++);
          int iG = pixelsRGB.get(q++);
          int iB = pixelsRGB.get(q++);
          pixelInts[i++] = 0xFF000000 | ((iR & 0x000000FF) << 16) | ((iG & 0x000000FF) << 8) | (iB & 0x000000FF);
            BufferedImage bimg = new BufferedImage(framewidth,frameheight,BufferedImage.TYPE_INT_ARGB);
              bimg.setRGB(0,0,framewidth, frameheight, pixelInts, 0, framewidth);
            try
                File imageFile = new File("final.jpg");
                File imagf = new File("final.png");
                File image = new File("final.bmp");
                ImageIO.write(bimg, "jpg", imageFile); // saves files
                ImageIO.write(bimg, "png", imagf);
                ImageIO.write(bimg, "bmp", image);
                   System.out.println("Success");
            catch (IOException e) {
                e.printStackTrace();
        }

    You want to convert it to an array of what? Of numbers? Of LabVIEW colors?
    The "Read BMP File.vi" VI outputs a 1-D array of the pixels, but I suspect it is not exactly in the format that you need. I am NOT sure, but I think that each group of 3 elements of that 1-D array (which is inside the cluster "image data" that the VI outputs) represents the red, green and blue levels of a single pixel (but it may be hue, saturation and lum.). Also, since it is a 1-D array, you would have to divide it by the width (which is also included in the "image data" cluster) to get some sort of 2-D array of data.
    You can find the "Read BMP File.vi" VI in the functions palete> "Graphics & sound">"Graphics Formats".

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • Pb to get a static variable value from an main program...

    Hi my lifegards !
    I am not a king of java and I thing I need explication about the way to get static values from an other class throw a method...
    here is my objects :
    CapturesBuffer(class extends canvas)
    static int nbCapts...
    public getNbCapts() return nbCaptsSendCapture (servlet)
    "captures = new CapturesBuffer();" in init()
    captures.getNbCapts(); return the good number of capturesSendToPD (program with static void main())
    "captures = new CapturesBuffer();" in constructor
    new SendToPD() in main(String args[])
    captures.getNbCapts(); return a bad value (the initial value)I hope it's anderstandable..:-)
    I have try to instance SendToPD object in the servlet (not to use the main method) and it is working !
    For me it's coming from main method. Am I wrong ?
    And more useful, what is the solution (I hope and I am sure there is one...)
    Thanx a lot and I wish u and happy year with all forms of java
    Guillaume.

    I didn�t understand very weel your aims neither why it is Thread extended .. but, anyway, here comes my guess:
    //package cicv.hatefulworld.server;
    public class DataPict implements Runnable
         private volatile Thread activeInstance = null;
         public void start()
              activeInstance = new Thread(this);
              activeInstance.start();
         public void stop()
              activeInstance = null;
         public void run()
              CapturesBuffer captures = new CapturesBuffer();
              Thread thisInstance = Thread.currentThread();
              try
                   while (activeInstance == thisInstance)
                        int nb = captures.getNbCapt();
                        System.out.println("number of captures: " + nb);
                        thisInstance.sleep(1000); // waiting 1 second
              catch (InterruptedException threadError)
                   System.out.println("Thread error:");
                   threadError.printStackTrace();
              catch(Exception generalError)
                   System.out.println("General error:");
                   generalError.printStackTrace();
              finally
                   captures = null;
                   thisInstance = null;
         public static void main(String[] args)
              (new DataPict()).start();
    class CapturesBuffer
         private int numberOfCaptures = 0;
         public int getNbCapt()
              // I don�t know exactlly what this method is designed for..
              // then I just coded a counter ...
              return numberOfCaptures++;
    }just compile it and run:
    javac *.java
    java DataPict

  • Using a Canvas in a Panel

    Im doing a programming project for uni, and I need to know how to use the Graphics class, even although we have never covered it. The task is to create a game of hangman, and I am fine with every aspect of the program except when it comes to showing the actual hangman display. This figure must make use of the Graphics class (problem 1- ive no material on how to use it), and be inside a panel (which is in turn inside another panel). I was told today that I would need to create a Canvas in the panel I want to use for the Graphic, then place the graphic on the canvas (problem 2- same as problem 1).
    Question is: how do I do ANY of this?
    I would be really thankful for any help, because its due in pretty soon. Thanks.

    I wrote this game a year ago, it uses 2 gifs for the gallow and the hangman, if you like this 2 gif i can email them to you, or you can change it to plain graphics .
    import java.awt.*;
    import java.awt.event.*;
    public class HangA extends Frame implements ActionListener
         Label      l1 = new Label();
         String     theX;
         char[]     theC;
         int        cntT;
         TheGallows theG;
         ATextField af = new ATextField(12);
    public HangA() 
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(10,10,650,450);
         setBackground(new Color(206,206,206));
         setLayout(null);
         add(l1);
         theG = new TheGallows();
         add(theG);
         showAbc();     
         getWord();
         showl1();
         setVisible(true);
    public void getWord()
         theX = "encapsulate";
         theX = "cap";
         theC = new char[theX.length()];
         for (int j = 0; j < theX.length(); j++) theC[j] = '.';
         theX = theX.toUpperCase();
         cntT = 0;
    public void showl1()
         l1.setBounds(30,70,200,50);
         l1.setBackground(Color.pink);
         l1.setForeground(Color.black);
         l1.setText(new String(theC));
         l1.setFont(new Font("",0,20));
    public void showAbc()
         String s[] =
         {"A","B","C","D","E","F","G","H","I","J","K","L","M",
          "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
         for (int j=0; j < s.length; j ++)
              Button jb = new Button(s[j]);
              jb.setFont(new Font("",1,16));
              jb.setBounds(j*24+10,30,22,22);
              jb.setName(s[j]);
              jb.addActionListener(this);
              add(jb);
    public void newAbc()
         for (int i = 0; i < getComponentCount(); i++)
              Component jc = (Component)getComponent(i);
              jc.setEnabled(true);
         getWord(); 
         showl1();
         theG.clear();
    public void actionPerformed(ActionEvent be)
         cntT++;
         boolean hit = false;
         char c = be.getActionCommand().charAt(0);
         for (int j=0; j < theX.length(); j++)
              if (theX.charAt(j) == c)
                   theC[j] = c;
                   hit = true;
         if (hit) showl1();
              else theG.hangm();
         String s = be.getActionCommand();
         for (int i = 0; i < getComponentCount(); i++)
              Component jc = (Component)getComponent(i);
              if (jc.getName() != null &&  jc.getName().equals(s))
                   jc.setEnabled(false);
         if (theG.cntM > 9)
              new dialog(this,(""+cntT+ "    try's  Very Bad"));
              newAbc();
         if (theX.equals(new String(theC)))
              new dialog(this,(""+cntT+ "    try's  Very Nice"));
              newAbc();
    public class TheGallows extends Canvas
         Image          gall;
         Image          hang;
         int            cntM;
    public TheGallows()
         super();
         gall = getToolkit().getImage("gallows.gif");
         hang = getToolkit().getImage("gallowh.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(gall,0);
         tracker.addImage(hang,0);
         try   {tracker.waitForID(0);}
         catch (InterruptedException e){}
         clear();
         setBounds(300,70,gall.getWidth(null),gall.getHeight(null));
    public void clear()
         cntM = 0;
         repaint();
    public void hangm()
         cntM = cntM + 1;
         repaint();
    public void paint(Graphics g)
         if (cntM < 1) super.paint(g);
         int h = gall.getHeight(null) / 10 * cntM;
         int w = gall.getWidth(null);
         g.drawImage(gall,0,0,w,h,0,0,w,h,null);
         if (cntM > 9) g.drawImage(hang,0,0,null);
    public void update(Graphics g)
         paint(g);
    public class dialog extends Dialog
    public dialog(Frame frame, String s)
         super(frame,"",true);
         Label l = new Label(" "+s);
         l.setFont(new Font("",0,16));
         add(l);
         pack();
         setLocation(200,200);
         this.addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   setVisible(false);
         setVisible(true);
    public static void main (String[] args)
         new HangA();
    Noah
    unformatted
    import java.awt.*;
    import java.awt.event.*;
    public class HangA extends Frame implements ActionListener
         Label l1 = new Label();
         String theX;
         char[] theC;
         int cntT;
         TheGallows theG;
         ATextField af = new ATextField(12);
    public HangA()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(10,10,650,450);
         setBackground(new Color(206,206,206));
         setLayout(null);
         add(l1);
         theG = new TheGallows();
         add(theG);
         showAbc();     
         getWord();
         showl1();
         setVisible(true);
    public void getWord()
         theX = "encapsulate";
         theX = "cap";
         theC = new char[theX.length()];
         for (int j = 0; j < theX.length(); j++) theC[j] = '.';
         theX = theX.toUpperCase();
         cntT = 0;
    public void showl1()
         l1.setBounds(30,70,200,50);
         l1.setBackground(Color.pink);
         l1.setForeground(Color.black);
         l1.setText(new String(theC));
         l1.setFont(new Font("",0,20));
    public void showAbc()
         String s[] =
         {"A","B","C","D","E","F","G","H","I","J","K","L","M",
         "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
         for (int j=0; j < s.length; j ++)
              Button jb = new Button(s[j]);
              jb.setFont(new Font("",1,16));
              jb.setBounds(j*24+10,30,22,22);
              jb.setName(s[j]);
              jb.addActionListener(this);
              add(jb);
    public void newAbc()
         for (int i = 0; i < getComponentCount(); i++)
              Component jc = (Component)getComponent(i);
              jc.setEnabled(true);
         getWord();
         showl1();
         theG.clear();
    public void actionPerformed(ActionEvent be)
         cntT++;
         boolean hit = false;
         char c = be.getActionCommand().charAt(0);
         for (int j=0; j < theX.length(); j++)
              if (theX.charAt(j) == c)
                   theC[j] = c;
                   hit = true;
         if (hit) showl1();
              else theG.hangm();
         String s = be.getActionCommand();
         for (int i = 0; i < getComponentCount(); i++)
              Component jc = (Component)getComponent(i);
              if (jc.getName() != null && jc.getName().equals(s))
                   jc.setEnabled(false);
         if (theG.cntM > 9)
              new dialog(this,(""+cntT+ " try's Very Bad"));
              newAbc();
         if (theX.equals(new String(theC)))
              new dialog(this,(""+cntT+ " try's Very Nice"));
              newAbc();
    public class TheGallows extends Canvas
         Image gall;
         Image hang;
         int cntM;
    public TheGallows()
         super();
         gall = getToolkit().getImage("gallows.gif");
         hang = getToolkit().getImage("gallowh.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(gall,0);
         tracker.addImage(hang,0);
         try {tracker.waitForID(0);}
         catch (InterruptedException e){}
         clear();
         setBounds(300,70,gall.getWidth(null),gall.getHeight(null));
    public void clear()
         cntM = 0;
         repaint();
    public void hangm()
         cntM = cntM + 1;
         repaint();
    public void paint(Graphics g)
         if (cntM < 1) super.paint(g);
         int h = gall.getHeight(null) / 10 * cntM;
         int w = gall.getWidth(null);
         g.drawImage(gall,0,0,w,h,0,0,w,h,null);
         if (cntM > 9) g.drawImage(hang,0,0,null);
    public void update(Graphics g)
         paint(g);
    public class dialog extends Dialog
    public dialog(Frame frame, String s)
         super(frame,"",true);
         Label l = new Label(" "+s);
         l.setFont(new Font("",0,16));
         add(l);
         pack();
         setLocation(200,200);
         this.addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
                   setVisible(false);
         setVisible(true);
    public static void main (String[] args)
         new HangA();

  • How to create a jpg file for a desired  part of the canvas

    i hav to create a jpg file from the canvas which contains basic shapes which are drawn using methods like drawOval(),drawRectangle(). i need only a part of the canvas to be saved as a jpg file i.e for example from xpos 50-100 & ypos 200-250.i need all the portions of the shapes already drawn in that area as a jpg file..
    can anyone help me?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    public class CanvasClip extends Canvas implements ActionListener
        Rectangle clip;
        boolean showClip;
        public CanvasClip()
            clip = new Rectangle(50, 50, 150, 150);
            showClip = false;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w,h)/4;
            g2.setPaint(getBackground());
            g2.fillRect(0,0,w,h);
            g2.setPaint(Color.blue);
            g2.drawRect(w/16, h/16, w*7/8, h*7/8);
            g2.setPaint(Color.red);
            g2.fillOval(w/8, h/12, w*3/4, h*5/6);
            g2.setPaint(Color.green.darker());
            g2.fillOval(w/2-dia/2, h/2-dia/2, dia, dia);
            g2.setPaint(Color.orange);
            g2.drawLine(w/16+1, h/16+1, w*15/16-1, h*15/16-1);
            if(showClip)
                g2.setPaint(Color.magenta);
                g2.draw(clip);
        public void actionPerformed(ActionEvent e)
            Button button = (Button)e.getSource();
            String ac = button.getActionCommand();
            if(ac.equals("show"))
                showClip = !showClip;
                repaint();
            if(ac.equals("save"))
                save();
        private void save()
            int w = clip.width;
            int h = clip.height;
            BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = img.createGraphics();
            g2.translate(-clip.x, -clip.y);
            paint(g2);
            g2.dispose();
            String ext = "jpg";  // or "png"; "bmp" okay in j2se 1.5
            try
                ImageIO.write(img, "jpg", new File("canvasClip.jpg"));
            catch(IOException ioe)
                System.err.println("write error: " + ioe.getMessage());
        private Panel getUIPanel()
            Button show = new Button("show clip");
            Button save = new Button("save");
            show.setActionCommand("show");
            save.setActionCommand("save");
            show.addActionListener(this);
            save.addActionListener(this);
            Panel panel = new Panel();
            panel.add(show);
            panel.add(save);
            return panel;
        public static void main(String[] args)
            CanvasClip cc = new CanvasClip();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(cc);
            f.add(cc.getUIPanel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Alternative to Double-Buffered Canvas

    I am working on a program in which I use a double-buffered Canvas inside a JScrollPane. The problem is that the Canvas draws over the scrollbars. I have tried extending JComponent, JPanel, JApplet, and Component instead of Canvas, and none of them are double buffered. Here is the code I used to debug this problem:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Test implements  Runnable
         JFrame f;
         JScrollPane scroller;
         JPanel panel;
         TestCanvas canvas;
         Thread runner;
         BufferStrategy strategy;
         public static void main (String[] args) {
              Test app = new Test();
              app.init();
         public void init() {
              f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              panel = new JPanel();
              canvas = new TestCanvas();
              panel.add(canvas);
              scroller = new JScrollPane(panel);
              scroller.setWheelScrollingEnabled(true);
              f.getContentPane().add(scroller);
              f.pack();
              f.setSize(300,300);
              f.setVisible(true);
              canvas.createBufferStrategy(2);
              strategy = canvas.getBufferStrategy();
              runner = new Thread(this);
              runner.run();
         public void run() {
              int x = 0;
              while(x != 65536) {
                   Graphics2D g = (Graphics2D)strategy.getDrawGraphics().create();
                   g.setColor(new Color(x%256,0,0));
                   g.fill(new Ellipse2D.Double(0,0,600,600));
                   strategy.show();
                   x++;
    }Any suggestions?

    The main culprit is that you are mixing AWT components with Swing ones.
    In addition, your are doing so many of useless things and wrong things in your code.
    Swing components are defaulted for using double-buffering.
    See: http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    Try and study this code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Fox1229{
      JFrame f;
      JScrollPane scroller;
      TestCanvas canvas;
      int x;
      Timer t;
      public static void main (String[] args) {
        Fox1229 app = new Fox1229();
        app.init();
      public void init() {
        x = 0;
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new TestCanvas();
        scroller = new JScrollPane(canvas);
        scroller.setWheelScrollingEnabled(true);
        f.getContentPane().add(scroller, BorderLayout.CENTER);
        f.setSize(300, 300);
        f.setVisible(true);
        t = new Timer(50, new ActionListener(){
          public void actionPerformed(ActionEvent e){
            canvas.setOc(new Color(x % 256, 0, 0));
            canvas.repaint();
            if (++x == 1024){
              t.stop();
        t.start();
    class TestCanvas extends JPanel{
      Color oc;
      public TestCanvas (){
        oc = new Color(0, 0, 0);
      public void setOc(Color c){
        oc = c;
      public Dimension getPreferredSize(){
        return new Dimension(600, 600);
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle(0, 0, 600, 600));
        g2d.setColor(oc);
        g2d.fill(new Ellipse2D.Double(0, 0, 600, 600));
    }

  • Non-static method destroyApp(boolean) cannot be referenced from a static co

    Hi guys, ive been writing, erasing and rewriting code, and finally my midlet runs well. It get complicated when i began to use the class Canvas, because the main process required values from the Canvas class. Im not sure if the program is well designed. Sugestions are apreciated.
    Well, i used static public boolean hilo; to share that variable between classes, and its working, however there is just a final procedure I want to implement, and that is that terminate the midlet when the user press the erase button.
    When I detect the button, i cant call the notifyDestroyed() method.
    Here's the code
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class TS_Online extends MIDlet implements CommandListener {
    public static Display display;                    // Objeto para que muestre en pantalla
    private SSCanvas sscInicio;               // Objeto canvas para mostrar imagenes
    private Form frmServidor;                    // Objeto forma
    private TextField ip1;                         // Direcci�n IP
    private TextField ip2;                         // Direcci�n IP
    private TextField ip3;                         // Direcci�n IP
    private TextField ip4;                         // Direcci�n IP
    private TextField puerto;                    // Puerto a conectarse
    private Command cmdEntrada;               // Objeto comando
    private Command cmdSalida;                    // Objeto comando
    private Command cmdVolver;                    // Objeto comando
    // * Constructor *
    public TS_Online() {
         display = Display.getDisplay(this);                    // Obtiene la pantalla
         sscInicio = new SSCanvas();                              // Nueva forma
         cmdEntrada = new Command("Entrada", Command.STOP, 2);
         cmdSalida = new Command("Salida", Command.STOP, 2);
         cmdVolver = new Command("Volver", Command.BACK, 1);
         sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
         sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
         sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
         ip1 = new TextField("Direcci�n IP:", "0", 3, TextField.NUMERIC);     // Caja de texto
         ip2 = new TextField(null, "0", 3, TextField.NUMERIC);
         ip3 = new TextField(null, "0", 3, TextField.NUMERIC);
         ip4 = new TextField(null, "0", 3, TextField.NUMERIC);
         puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
         frmServidor = new Form("Configuraci�n");          // Titulo de la forma
         frmServidor.append(ip1);
         frmServidor.append(ip2);
         frmServidor.append(ip3);
         frmServidor.append(ip4);
         frmServidor.append(puerto);
         frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
    // * Metodos *
    public void startApp() {
         sscInicio.hilo = true;                                   // Habilita el hilo
         new Thread(sscInicio).start();                         // Hilo en Canvas
         display.setCurrent(sscInicio);                         // Define objeto a mostrar
         sscInicio.setTitle("TicketShop S.A.");               // Titulo de la forma
    // Metodos comunes en todos los Midlet
    public void pauseApp() {
         System.out.println("*** Pausado ***");
         sscInicio.hilo = false;                                   // Detiene el hilo
    public void destroyApp(boolean unconditional) {
         sscInicio.hilo = false;
         System.out.println("*** Terminado ***");
         notifyDestroyed();
    public void commandAction(Command c, Displayable s) {
         if (c == cmdEntrada) {
              if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
                   sscInicio.hilo = false;
                   sscInicio.ip = true;
                   System.out.println(sscInicio.hilo);
                   frmServidor.setCommandListener(this);
                   display.setCurrent(frmServidor);
              } else {
                   sscInicio.valido();                              // Tiquete valido
         } else if (c == cmdSalida) {
              sscInicio.invalido();                              // Tiquete invalido
         } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
              sscInicio.setCommandListener(this);
              sscInicio.hilo = true;                              // Arranca el hilo
              new Thread(sscInicio).start();                    // Hilo en Canvas
              display.setCurrent(sscInicio);
              System.out.println(sscInicio.hilo);
    // * Clase graficadora *
    class SSCanvas extends Canvas implements Runnable {
    private int sleepTime;                                        // Tiempo de retrazo
    static public boolean ip;                                   // Configurar IP
    static public boolean hilo;                              // Continuar hilo
    static public Image ts = null;                         // Contenedor imagen
    static public Image rojo = null;                         // Contenedor imagenpri
    static public Image verde = null;                         // Contenedor imagen
    static public Image img = null;                         // Contenedor imagen
    static public String mensaje = null;                    // Cadena de salida
    //private CommConnection cc = null;                         // Conector para puerto
    private SocketConnection sc = null;                    // Conector para red
    private SocketConnection cc = null;                    // Conector para red
    public SSCanvas() {
         // Cargamos las im�genes a usar
         try {
              ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
              rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
              verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
         } catch (IOException e) {}                              // Error si no encuentra las imagenes
    void iniciar() {
         img = ts;                                                  // Imagen de bienvenida
         mensaje = "Conectando al servidor";                    // Mensaje de inicio
         // Tiempo de espera para configurar servidor
         for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
              try {
                   mensaje = mensaje + ".";                    // Mensaje de inicio
                   repaint();                                        // Redibuja la pantalla
                   serviceRepaints();                              // Espera que termine
                   Thread.sleep(1000);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
         sleepTime = 50;
         img = verde;
         System.out.println("Iniciar");
    void codigo() {
    void valido() {
         img = verde;                                             // Imagen OK
         mensaje = "Tiquete OK";                                   // Tiquete valido
         AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
    void invalido() {
         img = rojo;                                                  // Imagen OK
         mensaje = "Tiquete Inv�lido";                         // Tiquete valido
         AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    // thread que contiene el game loop
    public void run() {
         System.out.println("*** Hilo arrancado ***");
         if (img == null)
              iniciar();
         while (hilo) {
              System.out.println("Hilo");
              // Actualizar pantalla
              repaint();                                                  // Redibuja la pantalla
              serviceRepaints();                                        // Espera que termine
              try {
                   Thread.sleep(sleepTime);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
    public void keyPressed(int keyCode) {
         if (keyCode == -8) {                                        // Si presiona borrar
              hilo = false;                                   // Salir de la aplicacion
              System.out.println("*** Terminado ***");
              TS_Online.destroyApp(true);
              notifyDestroyed();
    public void paint(Graphics g) {
         // Borrar la pantalla
         g.setColor(255,255,255);
         g.fillRect (0, 0, getWidth(), getHeight());
         // Coloca la imagen correspondiente
         g.drawImage (img, getWidth()/2, 10, Graphics.HCENTER|Graphics.TOP);
         // Poner texto
         Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
         g.setFont(fuente);
         g.setColor(0,0,0);
         g.drawString(mensaje, getWidth()/2, getHeight() - 40,Graphics.TOP|Graphics.HCENTER);
    }Im using the boolean hilo to stop the thread. I seems to work fine for me. By the way, im using 4 textFields to get the IP address, however they appear one over the other, id like to see them one next to the other, or a better way to validate an IP address.
    Thanks for the help!!

    Well, the solution was really easy, i just needed to create a reference to the midlet inside the Canvas class public SSCanvas(MIDlet m), so i got this new code, however, it seems cool in the emulator but i still cant get two comands in a row in the phone.
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.rms.*;
    public class TS_Online extends MIDlet implements CommandListener {
    public static Display display;               // Objeto para que muestre en pantalla
    private SSCanvas sscInicio = null;          // Objeto canvas para mostrar imagenes
    private Form frmServidor;                    // Objeto forma
    private StringItem subtitulo;               // Subtitulo de la forma
    private TextField[] ip;                    // Direcci�n IP
    private TextField puerto;                    // Puerto a conectarse
    private Command cmdEntrada;               // Objeto comando
    private Command cmdSalida;                    // Objeto comando
    private Command cmdVolver;                    // Objeto comando
    private String direccion;                    // Direcci�n del socket
    private RecordStore rsDireccion = null;     // Almacenamiento RMS
    // * Constructor *
    public TS_Online() {
         display = Display.getDisplay(this);                    // Obtiene la pantalla
         sscInicio = new SSCanvas(this);                    // Nueva forma con ref este midlet
         cmdEntrada = new Command("Entrada", Command.STOP, 2);
         cmdSalida = new Command("Salida", Command.STOP, 2);
         cmdVolver = new Command("Volver", Command.BACK, 1);
         sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
         sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
         sscInicio.setTitle("TicketShop S.A.");               // Titulo del canvas
         // Constructor forma Configurar Servidor
         ip = new TextField[4];                                   //
         ip[0] = new TextField(null, "190", 3, TextField.NUMERIC);     // Caja de texto
         ip[1] = new TextField(null, "65", 3, TextField.NUMERIC);
         ip[2] = new TextField(null, "161", 3, TextField.NUMERIC);
         ip[3] = new TextField(null, "158", 3, TextField.NUMERIC);
         puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
         ip[0].setLayout(Item.LAYOUT_2);                         // Coloca los elementos pegados
         ip[1].setLayout(Item.LAYOUT_2);
         ip[2].setLayout(Item.LAYOUT_2);
         ip[3].setLayout(Item.LAYOUT_2);
         frmServidor = new Form("Configuraci�n");          // Titulo de la forma
         subtitulo = new StringItem("Direccion IP:", "");
         frmServidor.append(subtitulo);                         // Coloca cadena de texto
         frmServidor.append(ip[0]);
         frmServidor.append(ip[1]);
         frmServidor.append(ip[2]);
         frmServidor.append(ip[3]);
         frmServidor.append("\n ");
         frmServidor.append(puerto);
         frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
    // * Metodos *
    public void startApp() {
         sscInicio.hilo = true;                                   // Habilita el hilo
         new Thread(sscInicio).start();                         // Hilo en Canvas
         sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
         display.setCurrent(sscInicio);                         // Define objeto a mostrar
    // Metodos comunes en todos los Midlet
    public void pauseApp() {
         System.out.println("*** Pausado ***");
         sscInicio.hilo = false;                                   // Detiene el hilo
    public void destroyApp(boolean unconditional) {
    public void salir() {
         sscInicio.hilo = false;
         System.out.println("*** Terminado ***");
         destroyApp(false);                                        // Destruir objetos
         notifyDestroyed();                                        // Salir de la aplicacion
    String cargarIP() {
    String cadena;
    // Cargar la direccion del servidor
         try {
              rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
         } catch (Exception error) {}
         try {
              byte[] byteOutputData = rsDireccion.getRecord(1);     // Lee el primer registro
              cadena = new String(byteOutputData);
              System.out.println("Cargada: " + cadena);
         } catch (Exception error) {
              cadena = "190.65.161.158:24300";
         try {
              rsDireccion.closeRecordStore();                         // Cerrar
         } catch (Exception error) {}
         return cadena;
    void guardarIP (String cadena) {
    // Almacenar la direcci�n ip y puerto
         try {
              RecordStore.deleteRecordStore("ipRecordStore");     // Borrar si existe
         } catch (Exception error) {}
         try {
              rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
         } catch (Exception error) {}
         try {
              byte[] byteOutputData = cadena.getBytes();     // Almacena los datos
              rsDireccion.addRecord(byteOutputData, 0, byteOutputData.length);
              System.out.println("Guardada: " + cargarIP());     // rsDireccion.getNumRecords()
         } catch (Exception error) {}
         try {
              rsDireccion.closeRecordStore();                    // Cerrar
         } catch (Exception error) {}
    void mostrarIP(String cadena) {
    int i, j=0, k;
         for (k=0; k<=2; k++) {
              i = cadena.indexOf('.', j);                         // Posicion del punto
              if (i < 0) {
                   ip[k].setString("0");                         // Si hay error coloca 0
              } else {
                   ip[k].setString(cadena.substring(j, i)); // Extrae direccion
              j = i + 1;
         i = cadena.indexOf(':', j);                              // Posicion del punto
         ip[3].setString(cadena.substring(j, i));          // Extrae direccion
         i = cadena.lastIndexOf(':');                         // Posicion dos puntos
         puerto.setString(cadena.substring(i+1));               // Extrae puerto
    public void commandAction(Command c, Displayable s) {
         if (c == cmdEntrada) {
              if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
                   sscInicio.hilo = false;
                   direccion = cargarIP ();                    // Cargar del record
                   mostrarIP(direccion);                         // Mostrar en la forma
                   System.out.println("*** OK ***");
                   frmServidor.setCommandListener(this);
                   display.setCurrent(frmServidor);
              } else {
                   sscInicio.entrada = true;                    // Tiquete entrada
                   AlertType.ERROR.playSound(TS_Online.display);     // Sonido
         } else if (c == cmdSalida) {
              sscInicio.entrada = false;                         // Tiquete salida
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
         } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
              direccion = ip[0].getString() + "." + ip[1].getString() + "."
                   + ip[2].getString() + "." + ip[3].getString() + ":" + puerto.getString();
              guardarIP(direccion);                              //Almacenar en record
              sscInicio.setCommandListener(this);
              sscInicio.hilo = true;                              // Arranca el hilo
              new Thread(sscInicio).start();                    // Hilo en Canvas
              display.setCurrent(sscInicio);
              System.out.println(sscInicio.hilo);
    // * Clase graficadora *
    class SSCanvas extends Canvas implements Runnable {
    private int sleepTime;                                        // Tiempo de retrazo
    static public boolean entrada = true;                    // Tiquete de entrada
    static public boolean hilo;                              // Continuar hilo
    static public Image ts = null;                         // Contenedor imagen
    static public Image rojo = null;                         // Contenedor imagenpri
    static public Image verde = null;                         // Contenedor imagen
    static public Image img = null;                         // Contenedor imagen
    static public String mensaje = null;                    // Cadena de salida
    static public String mensaje2 = "";                    // Cadena de salida Codigo de barras
    MIDlet midlet;                                                  // Enlace al midlet inicial
    CommConnection cc = null;                         // Conector para puerto
    //SocketConnection sc = null;                    // Conector para red
    //SocketConnection cc = null;                    // Conector para red
    public SSCanvas(MIDlet m) {
         midlet = m;                                                  // Referencia al MIDlet iniciado
         // Cargamos las im�genes a usar
         try {
              ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
              rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
              verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
         } catch (IOException e) {}                              // Error si no encuentra las imagenes
         img = ts;                                                  // Imagen de bienvenida
         mensaje = "Conectando";
         mensaje2 = "";                                             // Mensaje de inicio
    void iniciar() {
         img = ts;                                                  // Imagen de bienvenida
         // Tiempo de espera para configurar servidor
         for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
              try {
                   mensaje = mensaje + ".";                    // Mensaje de inicio
                   repaint();                                        // Redibuja la pantalla
                   serviceRepaints();                              // Espera que termine
                   Thread.sleep(1000);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
         mensaje = "Conectado!";
         img = verde;
         repaint();                                        // Redibuja la pantalla
         serviceRepaints();                              // Espera que termine
         sleepTime = 50;
         System.out.println("Iniciar");
    void codigo() {
         try {
              System.out.println("Leyendo");
              CommConnection cc = (CommConnection)Connector.open("comm:com0;baudrate=9600");
              //cc = (SocketConnection)Connector.open("socket://127.0.0.1:24300");
              //int baudrate = cc.getBaudRate();
              InputStream ic  = cc.openInputStream();          // Entrada serial
              //OutputStream oc = cc.openOutputStream();
              StringBuffer sbCodigo = new StringBuffer();     // Cadena de diferentes tipos de datos
              int ch = 255;
              while(ch > 32) {
                   ch = ic.read();
                   //oc.write(ch);
                   if (ch > 32)
                        sbCodigo.append((char)ch);
              mensaje2 = sbCodigo.toString();                    // Codigo de barras
              if (mensaje2.equals("2864634059CULIB")) {
                   valido();
              } else {
                   invalido();
              ic.close();                                             // Cierra las conexiones
              //oc.close();
              cc.close();
         } catch (Exception e) {
              Alert a = new Alert("Error!", e.toString(), rojo, AlertType.ERROR);
              a.setTimeout(Alert.FOREVER);                                   // Alerta hasta que oprima boton
              TS_Online.display.setCurrent(a);               // Despues de la alerta vuelve a Inicio
              try {
                   Thread.sleep(5000);
              } catch (Exception x) {}
    void valido() {
         img = verde;                                             // Imagen OK
         mensaje = "Tiquete OK";                                   // Tiquete valido
         AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
    void invalido() {
         img = rojo;                                                  // Imagen OK
         mensaje = "Tiquete Inv�lido";                         // Tiquete valido
         AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    // thread que contiene el game loop
    public void run() {
         System.out.println("*** Hilo arrancado ***");
         if (img == ts)
              iniciar();
         while (hilo) {
              //System.out.println("Hilo");
              // Leer codigo de barras
              codigo();
              // validar codigo de barras
              //validar();
              // Actualizar pantalla
              repaint();                                                  // Redibuja la pantalla
              serviceRepaints();                                        // Espera que termine
              try {
                   Thread.sleep(sleepTime);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
    protected void keyPressed(int keyCode) {
    mensaje = Integer.toString(keyCode);
    //int action = getGameAction(keyCode);
         if ((keyCode == -8) || (keyCode == 42)) {               // Si presiona borrar o *
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
              ((TS_Online)midlet).salir();
         } else if (keyCode == -51 || keyCode == -52 || keyCode == -53) {
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    public void paint(Graphics g) {
         // Borrar la pantalla
         g.setColor(255,255,255);
         g.fillRect (0, 0, getWidth(), getHeight());
         // Coloca la imagen correspondiente
         g.drawImage (img, getWidth()/2, 20, Graphics.HCENTER|Graphics.TOP);
         // Poner texto
         Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
         g.setFont(fuente);
         g.setColor(0,0,0);
         g.drawString(mensaje, getWidth()/2, getHeight()/2,Graphics.TOP|Graphics.HCENTER);
         g.drawString(mensaje2, getWidth()/2, 5,Graphics.TOP|Graphics.HCENTER);
    }

  • Cant add() a Canvas into a JPane

    Hello all!
    i having problem to include canvas within a JPanel.
    i subclass the Canvas with an image , i test it and its works :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.net.*;
    public class testImage extends JFrame{
      public testImage(){
        imageViewer m = new imageViewer();
        m.initImage("http://127.0.0.1/image/samifox.gif");
        getContentPane().add(m);
      public static void main(String[] args) {
        JFrame frame = new testImage();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
          //frame.pack();
          frame.setSize(300,300);
          frame.setVisible(true);
    class imageViewer extends Canvas{
      Image image;
      URL url;
      Toolkit tool;
      public void initImage(String path){
        try{
          url = new URL(path);
        }catch(Exception e){
          System.out.println(e.toString());
        image = Toolkit.getDefaultToolkit().getImage(url);
        setImage(image);
      void setImage(Image image){
        this.image = image ;
        repaint() ;
      public void paint(Graphics g){
        super.paint(g) ;
        try{
           g.drawImage(image,0,0,this) ;
           //g.drawString("ssss",25,25,this);
        } catch (NullPointerException e) {
              System.out.println(e.toString());
    }but i cant include this canvas subclass into a JPane i tried :
    //xxx
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers
    import java.awt.event.*;        //for action and window events
    import com.borland.jbcl.layout.*;
    public class testPanel extends JFrame{
      myJPane mypanel;
       public testPanel(){
        mypanel=new myJPane();
        getContentPane().add(mypanel);
      public static void main(String[] args) {
        JFrame frame = new testPanel();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
          //frame.pack();
          frame.setSize(300,300);
          frame.setVisible(true);
    class myJPane extends JPanel{
      imageViewer imgViewer;
      public myJPane(){
        imgViewer = new imageViewer();
        imgViewer.initImage("http://127.0.0.1/image/samifox.gif");
        add(imgViewer);
    i add and remove from  JPanel lots of component but when i had the use canvas it seem like i dont understand someting that very basic...
    any kind of help will be appriciated
    Shay

    hi Pual!
    Are you getting error messages? no , i dont get any compiler or run-time error
    Or does the program run and not do what you expect? yes , exectly , you see i extend Canvas and i draw in it an Image. now i have extended JPane , i need to add the extended canvas to JPane, like i said i dont recieve any error but the program doesnt show the canvas on the JPane like i except it.
    the Canvas does show in a JFrame but when i try too add the Canvas to JPanel , i faild.
    i hope its more understandable now!
    thank you
    Shay

Maybe you are looking for