2D Graphics in Canvas ?

I'm considering Flex for a project which will require that I be able to connect panels with lines.
Is there a way in Flex  that I could draw those connecting lines in a Canvas?

Hi there I think you're looking something like Chet Haase's top drawer, you can watch the videos or look at the code if you visit this link
http://graphics-geek.blogspot.com/search?q=top+drawer.

Similar Messages

  • Graphics and canvas

    Hello everybody
    I am not good at graphics and canvas. Who can help me how to draw graphics and use canvases to draw images ?
    I have created a program to draw a round rectangle but it does not work very well : the graphics remains at its last position when I want it to be displayed at a different location. I want a great help. Here is the code :
    package pack_graphics;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import oracle.jdeveloper.layout.*;
    * A Swing-based top level window class.
    * <P>
    * @author xxxx
    public class FGraphics extends JFrame {
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    Timer timer;
    int x=10;
    int y=23;
    * Constructs a new instance.
    public FGraphics() {
    super();
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    * Initializes the state of this instance.
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    this.setSize(new Dimension(200, 100));
    jPanel1.setLayout(xYLayout1);
    this.setTitle("Test graphics");
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    timer = new Timer(200, new ActionListener()
                             public void actionPerformed(ActionEvent evt)
    try
    after_timer_expired(evt);
    catch(Exception ex)
    return;
    timer.start();
    public void after_timer_expired(ActionEvent evt)
    x += 5;
    repaint();
    public void paint(Graphics g)
    g.drawRoundRect(x,y,50,20,25,15);
    Thank you very much indeed.

    I 'simplified' your code a bit, the results follow ... it seems to work fine. If this is not what you need, please clarify
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FGraphics extends JFrame {
      boolean      boo;
      int          x,
                   y;
      BorderLayout borderLayout;
      JPanel       jPanel;
      FlowLayout   flowLayout;
      Container    container;
      Timer        timer;
      Color        color;
      public FGraphics() {
        super("Test graphics");
        boo          = true;
        x            = 10;
        y            = 23;
        container    = getContentPane();
        color        = getBackground();
        borderLayout = new BorderLayout();
        jPanel       = new JPanel();
        flowLayout   = new FlowLayout();
        container.setLayout(borderLayout);
        jPanel.setLayout(flowLayout);
        container.add(jPanel, BorderLayout.CENTER);
        timer = new Timer(200, new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            try {
              afterTimerExpired(evt);
            catch(Exception ex) {
              ex.printStackTrace();
        timer.start();
        setSize(200,100);
        setDefaultCloseOperation( EXIT_ON_CLOSE );
        setVisible( true );
      public void afterTimerExpired(ActionEvent evt) {
        x += 5;
        repaint();
      public void paint(Graphics g) {
        g.setColor( color );
        g.fillRect(0,0,(int)getSize().getWidth(),(int)getSize().getHeight());
        g.setColor( Color.black );
        g.drawRoundRect(x,y,50,20,25,15);
      public static void main( String[] argv ) {
        new FGraphics();
    }

  • OutOf Memory Error while saving image of canvas

    Hi,
    I am facing a weired problem while saving the image of the graphics in Canvas. It's giving me OutOfMemory error. Here is snippet of code:
    if(cmd.equals(C.ACTION_SAVE)){
                try {
                    FileDialog fd = new FileDialog(frame, "Save ProcessInstance as JPEG", FileDialog.SAVE);
                    fd.setFile(processInstance.getProcessDefinition().getName() +processInstance.getProcessOwner() +processInstance.getProcessOwnerId() +".jpeg");
                    fd.show();
                    String name = fd.getDirectory()+fd.getFile();
                        int w = canvas.getWidth(), h = canvas.getHeight();
                        BufferedImage image = new BufferedImage(w, h,
                                BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2 = image.createGraphics();
                        canvas.paint(g2);
                        g2.dispose();
                        ImageIO.write(image, "jpeg", new File(name));
                    } catch (IOException e) {
                        System.err.println(e);
                    }

    Hi,
    I tried to run garbage collector for the same and now its working fine. I want to know is there any drawback of using this approach. I am new to java and waiting for ur expert comments. I added following lines in the above code just below ImageIO.write(image, "jpeg", new File(name));:
             image = null;
                        Runtime r = Runtime.getRuntime();
                        r.gc();

  • Graphics returning null in one place, but not another.

    If you want to compile and run my program.... you can get all the files here:
    http://s94182144.onlinehome.us/randomstuff/files.zip
    (The main classes you'll need to look at are DrawingCanvas, Trig and GraphEngine)
    Here's a visual just in case:
    http://s94182144.onlinehome.us/randomstuff/graph.jpg
    When I click the "Graph It" button, I'm sending all those variables in the window to another class. Except the method I need to call is passed Graphics g... and thus, I needed to create a graphics variable. But it's returning null.
    Here is my code in GraphEngine, which runs when a button is clicked. You'll notice for Graph It... I created a Graphics variable... this returns null. Except you'll also notice I do the same thing for "Clear"... but this works.
    NOTE: I was getting mad so I named some methods not so nicely :p .... you may notice they are different in my files.
         public void actionPerformed(ActionEvent e)
              userDisplay=e.getActionCommand();
              if(userDisplay.equals("Draw"))
                   String progChoice=grapher.graphType.getSelectedItem();
                   System.out.println(progChoice);
                   if(progChoice.equals("Lines"))
                        grapher.allButtons[0].enable();
                        draw();
                   else if(progChoice.equals("Scatter Plot"))
                        lineOfBestFit();
              else if(userDisplay.equals("Graph It"))
                   Trig.graphThisStuff();
                   Graphics g = canvas.getGraphics();
                   canvas.trig(g);
               else if(userDisplay.equals("Clear"))
                    Graphics g = canvas.getGraphics();
                   System.out.println(g);
                    canvas.clear(g);
            else if(userDisplay.equals("Reset"))
                Trig.restartThis();   
              else if(userDisplay.equals("Credits"))
                showInstructionsFrame();
            else if(userDisplay.equals("Help"))
                showHelpFrame();   
            else if(userDisplay.equals("Create Sinusodial Graph"))
                showTrigFrame();   

    1. Do you expect forum members to download and unzip your code? Good luck...
    2. Inside almost every "big" problem is a small one trying to get out. Write a minimal program
    demonstrating your problem (say <50 lines) and post that. The shorter code and the easier it
    is to copy, paste and run, the more forum members will actually give it a go.
    That being said, you problem is that you are using Component's getGraphics at all. Don't use it.
    It doesn't work very well -- they rendering you do is temporary, if you iconify and restore your
    window your changes will disappear (sometimes even moving another window past yours will do this!).
    What should you do instead? Put all your rendering code in paintComponent (or subroutines
    it calls). Changes in state of your app should trigger a call to repaint (or you will call it directly).
    Repainting will eventually cause your paintComponent to be called.

  • Getting Graphic to Follow Video

    Basically what I'm trying to accomplish is to have a smily face cover my 2-year-old son's privates as he's dancing around. I know how to use the "Ken Burns" effect in FCE, but never attempted to coordinate movement of a still image superimposed on video.

    Hi(Bonjour)!
    You're better to ask in Motion's forum.
    One problem with Match move or smooth cam behavior is that all your clip (including before IN and after OUT points) has to be analysed, a long process if your original clip is long.
    So export from FCP to a self contained quicktime movie, and import it in Motion to analyse movement.
    In Motion:
    You can use 2 or more trackers to mimic clip mouvments. Analize the movie
    Drag the "face" graphic in canvas, add a match move behavior, select "analyze motion" from your source clip in well.
    Michel Boissonneault

  • Null Graphics objects

    Hello, I am attempting to write a java program that places a graph within a panel that the user can interact with. I have chosen Canvas() as the method to acieve this, but am running into problems with the instantiation of the graphics object- it keeps returning null, and I haven't the faitest idea why. Here is my code in question:
    Canvas canvas = new Canvas();
    Graphics g = canvas.getGraphics();
    'g' is null- when I try to call g.drawLine(), it gives me a nullPointerException. Any help or information about why this is occuring would be greatly appreciated.

    Well, I figured out that I needed to add the canvas to the contentPane before it had a Graphics object associated with it. But now, where the canvas is, there is a just a gray box. SetColor doesn't work, drawLine doesn't work, nothing. Here is the code:
    Canvas canvas = new Canvas();
    contentPane.add(canvas, BorderLayout.WEST);
    show();
    Graphics g = canvas.getGraphics();
    Color white = new Color (255,255,255);
    g.setColor(white);
    setSize(300,200);
    //Sets up the graph lines and tic marks
    int size = 100;
    g.drawLine(0, 0, size, 0);
    g.drawLine(0, 0, 0, size);
    //Horizontal tics
    g.drawLine((size/4), 0, (size/4), (size/10));
    g.drawLine((size/2), 0, (size/2), (size/10));
    g.drawLine(((3*size)/4), 0, ((3*size)/4), (size/10));
    g.drawLine(size, 0, size, (size/10));
    //Vertical tics
    g.drawLine(0, (size/4), (size/10), (size/4));
    g.drawLine(0, (size/2), (size/10), (size/2));
    g.drawLine(0, ((3*size)/4), (size/10), ((3*size)/4));
    g.drawLine(0, size, (size/10), size);
    show();
    As I said, it compiles and runs fine, but there are no lines set up. I even added a bunch of show() statements as a desperate effort to get something to show up. Can anyone help? Thanks
    I hate programming.

  • JPanel loses keyboard focus

    Ok, i have a JTextField which is initially disabled. A JPanel draws some stuff and receives keyboard input. When i enable the textfield, type some stuff, then press Esc (which disables it), i cant get the keyboard focus back on the JPanel. Here is an example:
    (you can move the red circle before you enable the textfield, after you disable it, you cant move it anymore).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.util.Vector;
    public class example extends JPanel implements ActionListener,Runnable {
        JFrame frame;
        JMenuBar menubar;
        JMenu m_file;
        JMenuItem mi_open,mi_close;
        JPanel canvas,northpanel;
        JTextField textfield;
        Image canvasimg;
        Thread thread=new Thread(this);
        private Image dbImage;     // for flickering
         private Graphics dbg;     // for flickering
         int x1=400,y1=200;
        public example() {
            frame = new JFrame("Example");                         // window
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1000,700));
            frame.setLayout(new BorderLayout());
            northpanel=new JPanel();
            northpanel.setLayout(null);
            northpanel.setPreferredSize(new Dimension(1000,20));     northpanel.setLocation(0,0);
            menubar=new JMenuBar();
            m_file=new JMenu("File");   
            mi_open=new JMenuItem("Open");
            mi_close=new JMenuItem("Close");
            m_file.add(mi_open);
            m_file.add(mi_close);   
            m_file.getPopupMenu().setLightWeightPopupEnabled(false);   
            menubar.add(m_file);
            northpanel.add(menubar);
            menubar.setLocation(0,0);     menubar.setSize(80,20);
            textfield=new JTextField();
            northpanel.add(textfield);
            textfield.setSize(200,20);     textfield.setLocation(500,0);   
            textfield.setEnabled(false);
            frame.add(northpanel,BorderLayout.NORTH);
            canvas=new JPanel();
            canvas.setLayout(null);
            canvas.setSize(1000,600);
            canvas.setBackground(Color.white);
             frame.add(canvas,BorderLayout.CENTER);      
            frame.pack();
            frame.setVisible(true);       
            thread.start();                                   // start the thread
            textfield.addMouseListener(new MouseAdapter(){
                    public void mousePressed(MouseEvent e){
                         textfield.setEnabled(true);
               textfield.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){
                      int key=e.getKeyCode();
                      if(key==27){     // esc
                           textfield.setEnabled(false); 
                           canvas.setEnabled(true);                // not working
                           canvas.requestFocus();
                           canvas.requestFocusInWindow();
               frame.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){                   
                      int key=e.getKeyCode();
                      if(key==37){ //left
                           x1-=5;
                      if(key==38){ //up
                           y1-=5;
                      if(key==39){ //right
                           x1+=5;
                      if(key==40){ //down
                           y1+=5;
        // Create the GUI and show it. 
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            example ex = new example();
        public void run(){
             while(true){
                  try{
                       if(canvasimg==null)repaint();                   
                       Graphics g=canvas.getGraphics();
                       update(g);
                       thread.sleep(30);                                             // 1 sec
                  }      catch(InterruptedException ex){}
        // ActionPerformed handles button and menu events
        public void actionPerformed(ActionEvent e){              
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void update (Graphics g){          // get rid of flicker
              if (dbImage == null){
                   dbImage = canvas.createImage (canvas.getSize().width, canvas.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (canvas.getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (canvas.getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void paint(Graphics g){
              g.drawImage(canvasimg,0,0,this);          
              g.setColor(Color.red);
             g.fillOval(x1,y1,10,10);
        public void repaint(){     
             if(canvas!=null && canvasimg==null)canvasimg=canvas.createImage(1000,670);
             if(canvasimg==null)return;
             Graphics g=canvasimg.getGraphics();
             if(g==null)return;
             g.setColor(Color.white);
             g.fillRect(0,0,1000,600);
    }  

    OK great guru since you're so damn confident that you're doing everything right, find out for yourself why this works and yours doesn't.
    I could list a few dozen things wrong with your code, but I'd be wasting my keystrokes.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TextFieldDisableNoProblem extends JPanel {
       JPanel northPanel;
       JMenuBar menubar;
       JMenu m_file;
       JMenuItem mi_open,mi_close;
       JTextField textField;
       int x1 = 400;
       int y1 = 200;
       public TextFieldDisableNoProblem () {
          setBackground (Color.WHITE);
          addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                switch (key) {
                   case KeyEvent.VK_LEFT:
                         x1 -= 5;
                         break;
                   case KeyEvent.VK_UP:
                         y1 -= 5;
                         break;
                   case KeyEvent.VK_RIGHT:
                         x1 += 5;
                         break;
                   case KeyEvent.VK_DOWN:
                         y1 += 5;
                         break;
                repaint ();
       void makeUI () {
          JFrame frame = new JFrame ("");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (600, 500);
          frame.setLocationRelativeTo (null);
          menubar=new JMenuBar ();
          m_file=new JMenu ("File");
          mi_open=new JMenuItem ("Open");
          mi_close=new JMenuItem ("Close");
          m_file.add (mi_open);
          m_file.add (mi_close);
          menubar.add (m_file);
          frame.setJMenuBar (menubar);
          textField=new JTextField ();
          textField.setEnabled (false);
          textField.setBounds (200, 0, 200, 20);
          textField.addMouseListener (new MouseAdapter (){
             public void mousePressed (MouseEvent e){
                textField.setEnabled (true);
          textField.addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                if(key == KeyEvent.VK_ESCAPE){
                   textField.setEnabled (false);
                   requestFocus ();
          northPanel=new JPanel ();
          northPanel.setLayout (null);
          northPanel.setPreferredSize (new Dimension (600,20));
          northPanel.add (textField);
          frame.add (northPanel,BorderLayout.NORTH);
          frame.add (this, BorderLayout.CENTER);
          frame.setVisible (true);
          requestFocus ();
       public void paintComponent (Graphics g) {
          super.paintComponent (g);
          g.setColor (Color.RED);
          g.fillOval (x1, y1, 10, 10);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                JFrame.setDefaultLookAndFeelDecorated (true);
                new TextFieldDisableNoProblem ().makeUI ();
    }db

  • Is there any problems in IE if using RMI.?

    Hello buddies,
    this is my 3rd attempt to get answer. before it i tried 2 times but didn't get answered.
    actually i m making a chat application. in that there is a canvas on which we can draw something and send it to all users. i make an applet and from within the applet i m calling a frame. all this awt components like canvas and buttons etc. displays in the frame. applet is just a platform do call the frame. i m using RMI to do the chat. i tried to run it first in appletviewer and it works fine. but when i tried to run in IE from <applet> tag no frame is displays. i am trying to solve it from last 20 days but still unsolved. here is the code if anybody wishes to try it.
    // clinet frame...
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.awt.*;
    import java.applet.*;
    import java.applet.Applet;
    import java.awt.event.*;
    import java.util.*;
    import ru.zhuk.graphics.*;
    /*<applet code="ChatClient" width=600 height=300>
    </applet>
    public class ChatClient extends Frame implements IChatClient,ActionListener,MouseListener,MouseMotionListener
         // GLOBAL VARIABLES USED IN THE PROGRAMME...
         boolean flag=false;
         int n;
         String str="";
         String Coord=null;
         IChatService service=null;
         FrameApplet fa=null;
         TextField servername,serverport,username;
         Button connect,disconnect;
         TextField message;
         Button send,sendText;
         TextArea fromserver;
         int i=0,j=0;
         int x[] = new int[1000];
         int y[] = new int[1000];
         Drawer canvas;
         boolean connected=false;
         String title,user="";
         // Class Members //
         public ChatClient()
         public ChatClient(String str)
              super(str);
              setBounds(50,20,600,450);
              setLayout(new FlowLayout(FlowLayout.CENTER,45,10));
              title=str;
              setStatus();
              // Create controls //
              add(new Label("Chat Server Name : "));
              servername=new TextField(20);
              add(servername);
              servername.setText("localhost");
              add(new Label("Chat Server Port : "));
              serverport=new TextField(20);
              add(serverport);
              serverport.setText("900");
              add(new Label("Your User Name : "));
              username=new TextField(20);
              add(username);
              username.setText("Umesh");
              connect=new Button("Connect");
              connect.addActionListener(this);
              add(connect);
              disconnect=new Button("Disconnect");
              disconnect.addActionListener(this);
              add(disconnect);
              message=new TextField(30);
              add(message);
              sendText=new Button("Send Text");
              sendText.addActionListener(this);
              add(sendText);
              fromserver=new TextArea(10,50);
              add(fromserver);
              fromserver.setEditable(false);
    canvas = new Drawer();
              canvas.setSize(250,250);
              canvas.setBackground(Color.cyan);
              add(canvas);
              canvas.addMouseListener(this);
              canvas.addMouseMotionListener(this);
              send=new Button("Send");
              send.addActionListener(this);
              add(send);
              try
                   UnicastRemoteObject.exportObject(this);
              catch(Exception e)
              setVisible(true);
              for(j=0;j<1000;j++)
                   x[j]=0;
                   y[j]=0;
              Coord = new String();
              Coord = "";
    //          fa=new FrameApplet();
         public void mousePressed(MouseEvent me){}
         public void mouseReleased(MouseEvent me)
              Coord = Coord + "r";
         public void mouseClicked(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mouseDragged(MouseEvent me)
              if (Coord == "")
                   Coord = me.getX() + "," + me.getY();
              else
                   Coord = Coord + " " + me.getX() + "," + me.getY();
         public void mouseMoved(MouseEvent me){}
         // RMI connection //
         private void connect()
              try
                   service = (IChatService)Naming.lookup("rmi://pcname/ChatService");
                   service.addClient(this);
                   connected=true;
                   setStatus();
                   user=username.getText();
                   Coord = "";
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n" + e);
                   System.out.println(e);
                   connected=false;
                   setStatus();
                   service=null;
         private void disconnect()
              try
                   if(service==null)
                        return;
                   service.removeClient(this);
                   service=null;
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n");
              finally
                   connected=false;
                   setStatus();
         private void setStatus()
              if(connected)
                   setTitle(title+" : Connected");
              else
                   setTitle(title+" : Not Connected");
         // IChatClient methods //
         public String getName()
              return user;
         public void sendMessage(String msg)
              fromserver.append(msg+"\n");
         public void SendCanvasObject(String str)
              this.str = str;
              fromserver.append(str + "\n");
              Graphics g = canvas.getGraphics();
              paint(g);
         // Actionlistener //
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==connect)
                   connect();
                   if(connected)
                        servername.setEnabled(false);
                        serverport.setEnabled(false);
                        username.setEnabled(false);
                        connect.setEnabled(false);
                        Coord = "";
              else
              if(e.getSource()==disconnect)
                   disconnect();
                   servername.setEnabled(true);
                   serverport.setEnabled(true);
                   username.setEnabled(true);
                   connect.setEnabled(true);
              else
              if(e.getSource()==send)
                   flag = true;
                   if(service==null)
                        return;
                   try
                        fromserver.append("Sending an image...\n");
                        service.SendCanvasObject(this,Coord);
                        i=0;
                        for(j=0;j<1000;j++)
                             x[j]=0;
                             y[j]=0;
                        Coord = "";
                        fromserver.append("\n" + "Image Sent...");
                   catch(RemoteException re)
                        fromserver.append("Error Sending Message ...\n" + re);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
              else
              if(e.getSource()==sendText)
                   if(service==null)
                        return;
                   try
                        service.sendMessage(this,message.getText());
                        message.setText("");
                   catch(RemoteException exp)
                        fromserver.append("Remote Error Sending Message ...\n" + exp);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
         public void paint(Graphics g)
              if(flag==true)
                   i=0;
                   StringTokenizer stoken = new StringTokenizer(str,"r");
                   String strin = "";
                   while(stoken.hasMoreTokens())
                        strin = stoken.nextToken();
                        fromserver.append("\n" + strin + "\n");
                        StringTokenizer stoken1 = new StringTokenizer(strin," ");
                        String strin1 = "";
                        j=0;
                        while(stoken1.hasMoreTokens())
                             strin1 = stoken1.nextToken();
                             fromserver.append("\n" + strin1 + "\n");
                             x[j]=Integer.parseInt(strin1.substring(0,strin1.indexOf(",")));
                             y[j]=Integer.parseInt(strin1.substring(strin1.indexOf(",")+1,strin1.length()));
                             j++;
                        for(int k=0;k<j-1;k++)
                             g.drawLine(x[k],y[k],x[k+1],y[k+1]);     
                   i++;
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.util.*;
    import ru.zhuk.graphics.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class FrameApplet extends Applet implements ActionListener
         ChatClient f;
         public void init()
              Button b = new Button("Start Chat");
              b.addActionListener(this);
              add(b);
         public void actionPerformed(ActionEvent ae)
              f=new ChatClient("Chat");
              f.show();
              f.setSize(400,400);
    here is html file which i calls from IE
    <html>
    <title>Micky Chat</title>
    <body>
    <br>
    <br>
    <center>
    <applet code="FrameApplet.class" width=200 height=200>
    </applet>
    </center>
    </body>
    </html>
    and at last a shocking thing is it is runs in Netscape displaying frames but not calling paint method.
    pls. help me
    thanks a lot
    umesh

    Hi Umesh!
    Sorry that I cannot be too concrete about that since it has to be centuries ago when I fell over this problem.
    As far as I can remember, the JDK provided by MS has no RMI built-in. These was probably one of the main reasons why Sun sued Microsoft concering its handling of Java.
    Afterwards MS released a path for its Java Runtime that included RMI support, but AFAIK they never included it in the standard package. So much luck when searching for the ZIP! (-;
    A little bit of googling might help, e.g.:
    http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&oe=UTF-8&threadm=37f8ddf6.4532124%40news.online.no&rnum=17&prev=/groups%3Fq%3Dmicrosoft%2Bjvm%2Brmi%2Bsupport%26start%3D10%26hl%3Dde%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D37f8ddf6.4532124%2540news.online.no%26rnum%3D17
    cheers,
    kdi

  • How can I change  oval shape applet to (plot)

    Hi this is not my code so, the orignal code is freeware to www.neuralsemantics.com and is Copyright 1989 by Rich Gopstein and Harris Corporation.
    The site allows permission to play with the code or ammend it.
    how could I modify the applet to display (plot) several cycles of the audio signal instead of the elliptical shape. The amplitude and period of the waveform should change in accordance with the moving sliders
    Here is the code from www.neuralsemantics.com /applets/jazz.html
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JazzMachine extends Applet
                 implements Runnable, AdjustmentListener, MouseListener {
      // program name
      final static String TITLE = "The jazz machine";
      // Line separator char
      final static String LSEP = System.getProperty("line.separator");
      // Value range
      final static int MIN_FREQ = 1;   // min value for barFreq
      final static int MAX_FREQ = 200; // max value for barFreq
      final static int MIN_AMPL = 0;   // min value for barVolume
      final static int MAX_AMPL = 100; // max value for barVolume
      // Sun's mu-law audio rate = 8KHz
      private double rate = 8000d;      
      private boolean audioOn = false;     // state of audio switch (on/off)
      private boolean changed = true;      // change flag
      private int freqValue = 1;           // def value of frequency scrollbar
      private int amplValue = 70;          // def value of volume scrollbar
      private int amplMultiplier = 100;    // volume multiplier coeff
      private int frequency, amplitude;    // the requested values
      private int soundFrequency;          // the actual output frequency
      // the mu-law encoded sound samples
      private byte[] mu;
      // the audio stream
      private java.io.InputStream soundStream;
      // graphic components
      private Scrollbar barVolume, barFreq;
      private Label labelValueFreq;
      private Canvas canvas;   
      // flag for frequency value display
      private boolean showFreq = true;
      // width and height of canvas area
      private int cw, ch;
      // offscreen Image and Graphics objects
      private Image img;
      private Graphics graph;
      // dimensions of the graphic ball
      private int ovalX, ovalY, ovalW, ovalH;
      // color of the graphic ball
      private Color ovalColor;
      // default font size
      private int fontSize = 12;
      // hyperlink objects
      private Panel linkPanel;
      private Label labelNS;
      private Color inactiveLinkColor = Color.yellow;
      private Color activeLinkColor = Color.white;
      private Font inactiveLinkFont = new Font("Dialog", Font.PLAIN, fontSize);
      private Font activeLinkFont = new Font("Dialog", Font.ITALIC, fontSize);
      // standard font for the labels
      private Font ctrlFont;
      // standard foreground color for the labels
      private Color fgColor = Color.white;
      // standard background color for the control area
      private Color ctrlColor = Color.darkGray;
      // standard background color for the graphic ball area
      private Color bgColor = Color.black;
      // start value for the time counter
      private long startTime;
      // maximum life time for an unchanged sound (10 seconds)
      private long fixedTime = 10000;
      // animation thread
      Thread runner;
    //                             Constructors
      public JazzMachine() {
    //                                Methods
      public void init() {
        // read applet <PARAM> tags
        setAppletParams();
        // font for the labels
        ctrlFont = new Font("Dialog", Font.PLAIN, fontSize);
        // convert scrollbar values to real values (see below for details)
        amplitude = (MAX_AMPL - amplValue) * amplMultiplier;
        frequency = (int)Math.pow(1.2d, (double)(freqValue + 250) / 10.0);
        setLayout(new BorderLayout());
        setBackground(ctrlColor);
        setForeground(fgColor);
        Label labelVolume = new Label(" Volume ");
        labelVolume.setForeground(fgColor);
        labelVolume.setAlignment(Label.CENTER);
        labelVolume.setFont(ctrlFont);
        barVolume = new Scrollbar(Scrollbar.VERTICAL, amplValue, 1,
                         MIN_AMPL, MAX_AMPL + 1);
        barVolume.addAdjustmentListener(this);
        // assign fixed size to the scrollbar
        Panel pVolume = new Panel();
        pVolume.setLayout(null);
        pVolume.add(barVolume);
        barVolume.setSize(16, 90);
        pVolume.setSize(16, 90);
        Label labelFreq = new Label("Frequency");
        labelFreq.setForeground(fgColor);
        labelFreq.setAlignment(Label.RIGHT);
        labelFreq.setFont(ctrlFont);
        barFreq = new Scrollbar(Scrollbar.HORIZONTAL, freqValue, 1,
                      MIN_FREQ, MAX_FREQ);
        barFreq.addAdjustmentListener(this);
        // assign fixed size to the scrollbar
        Panel pFreq = new Panel();
        pFreq.setLayout(null);
        pFreq.add(barFreq);
        barFreq.setSize(140, 18);
        pFreq.setSize(140, 18);
        // show initial frequency value
        labelValueFreq = new Label();
        if (showFreq) {
          labelValueFreq.setText("0000000 Hz");
          labelValueFreq.setForeground(fgColor);
          labelValueFreq.setAlignment(Label.LEFT);
          labelValueFreq.setFont(ctrlFont);
        Panel east = new Panel();
        east.setLayout(new BorderLayout(10, 10));
        east.add("North", labelVolume);
        Panel pEast = new Panel();
        pEast.add(pVolume);
        east.add("Center", pEast);
        Panel south = new Panel();
        Panel pSouth = new Panel();
        pSouth.setLayout(new FlowLayout(FlowLayout.CENTER));
        pSouth.add(labelFreq);
        pSouth.add(pFreq);
        pSouth.add(labelValueFreq);
        south.add("South", pSouth);
        linkPanel = new Panel();
        this.composeLink();
        Panel west = new Panel();
        // dummy label to enlarge the panel
        west.add(new Label("      "));
        add("North", linkPanel);
        add("South", south);
        add("East", east);
        add("West", west);
        add("Center", canvas = new Canvas());
      private void composeLink() {
        linkPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 5));
        linkPanel.setFont(inactiveLinkFont);
        linkPanel.setForeground(Color.yellow);
        Label labelName = new Label(TITLE + " \u00a9");
          labelName.setForeground(inactiveLinkColor);
          labelName.setAlignment(Label.RIGHT);
        labelNS = new Label(" Neural Semantics   ");
          labelNS.setForeground(inactiveLinkColor);
          labelNS.setFont(inactiveLinkFont);
          labelNS.setAlignment(Label.LEFT);
        linkPanel.add(labelName);
        linkPanel.add(labelNS);
        // link to Neural Semantics website
        String h = getDocumentBase().getHost();
        if ((h.length() > 4) && (h.substring(0, 4).equals("www.")))
          h = h.substring(4);
        if ((h != null) && (! h.startsWith("neuralsemantics.com"))) {
          // create a hand cursor for the hyperlink area
          Cursor linkCursor = new Cursor(Cursor.HAND_CURSOR);
          linkPanel.setCursor(linkCursor);
          labelName.addMouseListener(this);
          labelNS.addMouseListener(this);
      private void switchAudio(boolean b) {
        // switch audio to ON if b=true and audio is OFF
        if ((b) && (! audioOn)) {
          try {
            sun.audio.AudioPlayer.player.start(soundStream);
          catch(Exception e) { }
          audioOn = true;
        // switch audio to OFF if b=false and audio is ON
        if ((! b) && (audioOn)) {
          try {
            sun.audio.AudioPlayer.player.stop(soundStream);
          catch(Exception e) { }
          audioOn = false;
      private void getChanges() {
        // create new sound wave
        mu = getWave(frequency, amplitude);
        // show new frequency value
        if (showFreq)
          labelValueFreq.setText((new Integer(soundFrequency)).toString() + " Hz");
        // shut up !
        switchAudio(false);
        // switch audio stream to new sound sample
        try {
          soundStream = new sun.audio.ContinuousAudioDataStream(new
                            sun.audio.AudioData(mu));
        catch(Exception e) { }
        // listen
        switchAudio(true);
        // Adapt animation settings
        double prop = (double)freqValue / (double)MAX_FREQ;
        ovalW = (int)(prop * cw);
        ovalH = (int)(prop * ch);
        ovalX = (int)((cw - ovalW) / 2);
        ovalY = (int)((ch - ovalH) / 2);
        int r = (int)(255 * prop);
        int b = (int)(255 * (1.0 - prop));
        int g = (int)(511 * (.5d - Math.abs(.5d - prop)));
        ovalColor = new Color(r, g, b);
        // start the timer
        startTime = System.currentTimeMillis();
        // things are fixed
        changed = false;
    //                               Thread
      public void start() {
        // create thread
        if (runner == null) {
          runner = new Thread(this);
          runner.start();
      public void run() {
        // infinite loop
        while (true) {
          // Volume or Frequency has changed ?
          if (changed)
            this.getChanges();
          // a touch of hallucination
          repaint();
          // let the children sleep. Shut up if inactive during more
          // than the fixed time.
          if (System.currentTimeMillis() - startTime > fixedTime)
            switchAudio(false);
          // let the computer breath
          try { Thread.sleep(100); }
          catch (InterruptedException e) { }
      public void stop() {
        this.cleanup();
      public void destroy() {
        this.cleanup();
      private synchronized void cleanup() {
        // shut up !
        switchAudio(false);
        // kill the runner thread
        if (runner != null) {
          try {
            runner.stop();
            runner.join();
            runner = null;
          catch(Exception e) { }
    //                     AdjustmentListener Interface
      public void adjustmentValueChanged(AdjustmentEvent e) {
        Object source = e.getSource();
        // Volume range : 0 - 10000
        // ! Scrollbar value range is inverted.
        // ! 100 = multiplier coefficient.
        if (source == barVolume) {
          amplitude = (MAX_AMPL - barVolume.getValue()) * amplMultiplier;
          changed = true;
        // Frequency range : 97 - 3591 Hz
        // ! Scrollbar value range represents a logarithmic function.
        //   The purpose is to assign more room for low frequency values.
        else if (source == barFreq) {
          freqValue = barFreq.getValue();
          frequency = (int)Math.pow(1.2d, (double)(freqValue + 250) / 10.0);
          changed = true;
    //                     MouseListener Interface
      public void mouseClicked(MouseEvent e) {
      public void mouseEntered(MouseEvent e) {
        // text color rollover
        labelNS.setForeground(activeLinkColor);
        labelNS.setFont(activeLinkFont);
        showStatus("Visit Neural Semantics");
      public void mouseExited(MouseEvent e) {
        // text color rollover
        labelNS.setForeground(inactiveLinkColor);
        labelNS.setFont(inactiveLinkFont);
        showStatus("");
      public void mousePressed(MouseEvent e) {
        try {
          java.net.URL url = new java.net.URL("http://www.neuralsemantics.com/");
          AppletContext ac = getAppletContext();
          if (ac != null)
            ac.showDocument(url);
        catch(Exception ex){ }
      public void mouseReleased(MouseEvent e) {
    //                              Painting
      public void update(Graphics g) {
        Graphics canvasGraph = canvas.getGraphics();
        if (img == null) {
          // get canvas dimensions
          cw = canvas.getSize().width;
          ch = canvas.getSize().height;
          // initialize offscreen image
          img = createImage(cw, ch);
          graph = img.getGraphics();
        // offscreen painting
        graph.setColor(bgColor);
        graph.fillRect(0, 0, cw, ch);
        graph.setColor(ovalColor);
        graph.fillOval(ovalX, ovalY, ovalW, ovalH);
        // canvas painting
        if (canvasGraph != null) {
          canvasGraph.drawImage(img, 0, 0, canvas);
          canvasGraph.dispose();
    //                          Sound processing
      // Creates a sound wave from scratch, using predefined frequency
      // and amplitude.
      private byte[] getWave(int freq, int ampl) {
        int lin;
        // calculate the number of samples in one sinewave period
        // !! change this to multiple periods if you need more precision !!
        int nSample = (int)(rate / freq);
        // calculate output wave frequency
        soundFrequency = (int)(rate / nSample);
        // create array of samples
        byte[] wave = new byte[nSample];
        // pre-calculate time interval & constant stuff
        double timebase = 2.0 * Math.PI * freq / rate;
        // Calculate samples for a single period of the sinewave.
        // Using a single period is no big precision, but enough
        // for this applet anyway !
        for (int i=0; i<nSample; i++) {
          // calculate PCM sample value
          lin = (int)(Math.sin(timebase * i) * ampl);
          // convert it to mu-law
          wave[i] = linToMu(lin);
        return wave;
      private static byte linToMu(int lin) {
        int mask;
        if (lin < 0) {
          lin = -lin;
          mask = 0x7F;
        else  {
          mask = 0xFF;
        if (lin < 32)
          lin = 0xF0 | 15 - (lin / 2);
        else if (lin < 96)
          lin = 0xE0 | 15 - (lin-32) / 4;
        else if (lin < 224)
          lin = 0xD0 | 15 - (lin-96) / 8;
        else if (lin < 480)
          lin = 0xC0 | 15 - (lin-224) / 16;
        else if (lin < 992)
          lin = 0xB0 | 15 - (lin-480) / 32;
        else if (lin < 2016)
          lin = 0xA0 | 15 - (lin-992) / 64;
        else if (lin < 4064)
          lin = 0x90 | 15 - (lin-2016) / 128;
        else if (lin < 8160)
          lin = 0x80 | 15 - (lin-4064) / 256;
        else
          lin = 0x80;
        return (byte)(mask & lin);
    //                             Applet info
      public String getAppletInfo() {
        String s = "The jazz machine" + LSEP + LSEP +
                   "A music synthetizer applet" + LSEP +
                   "Copyright (c) Neural Semantics, 2000-2002" + LSEP + LSEP +
                   "Home page : http://www.neuralsemantics.com/";
        return s;
      private void setAppletParams() {
        // read the HTML showfreq parameter
        String param = getParameter("showfreq");
        if (param != null)
          if (param.toUpperCase().equals("OFF"))
            showFreq = false;
        // read the HTML backcolor parameter
        bgColor = changeColor(bgColor, getParameter("backcolor"));
        // read the HTML controlcolor parameter
        ctrlColor = changeColor(ctrlColor, getParameter("controlcolor"));
        // read the HTML textcolor parameter
        fgColor = changeColor(fgColor, getParameter("textcolor"));
        // read the HTML fontsize parameter
        param = getParameter("fontsize");
        if (param != null) {
          try {
            fontSize = Integer.valueOf(param).intValue();
          catch (NumberFormatException e) { }
      private Color changeColor(Color c, String s) {
        if (s != null) {
          try {
            if (s.charAt(0) == '#')
              c = new Color(Integer.valueOf(s.substring(1), 16).intValue());
            else
              c = new Color(Integer.valueOf(s).intValue());
          catch (NumberFormatException e) { e.printStackTrace(); }
        return c;
    }thanks LIZ
    PS If you can help how do I Give the Duke dollers to you

    http://www.google.ca/search?q=java+oval+shape+to+plot&hl=en&lr=&ie=UTF-8&oe=UTF-8&start=10&sa=N
    Ask the guy who made it for more help

  • How can i make from a GUI application an Applet ?

    Hello, i have a gui appliction and i want to make an applet
    how can i do that, i read an article (i need to put away method main and write method init (must be same as a constructer , but my constructor is only public Grafika() ) but it doest help....
    Can you help me.. ?
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.JPanel;
    import java.awt.*;
    import javax.swing.*;
    public class Grafika{
         JPanel canvas;
         public static boolean pause = true;
         public static int algoritmus = 0;
         public static String[] algoritmy={"V�ber Algoritmu","QuickSort","BubbleSort"};
         public static long sleeper = 600;       
         public void borders(JPanel canvas,int[] cisla,int left,int right){
              Graphics g = canvas.getGraphics();
              for(int i=0;i<cisla.length;i++){               
                   if(cisla==cisla[left]){
                        g.setColor(Color.lightGray);
                        g.drawLine(10, 20+i*4, 500,20+i*4 );
                   if(cisla[i]==cisla[right]){
                        g.setColor(Color.lightGray);
                        g.drawLine(10, 20+i*4+1, 500,20+i*4+1 );
                   else {
                        g.setColor(Color.white);
                        g.drawLine(10, 20+i*4-1, 500,20+i*4-1 );
              g.dispose();
              //repaint();          
         public void drawIt(JPanel canvas,int[] cisla,int pivot){
              Graphics g = canvas.getGraphics();
              for(int i=0;i<cisla.length;i++){     
                   if(cisla[i]==pivot){
                        g.setColor(Color.green);
                   else {
                        g.setColor(Color.red);
                   g.fillRect(10, 20+i*4, cisla[i], 2);
                   g.setColor(Color.white);
                   g.fillRect(9+cisla[i]+1,20+ i*4, 1000, 2);
              g.dispose();
              //repaint();          
              public static void main(String[] Args){
              JFrame f = new JFrame("Triediace Algoritmy");     
              JPanel canvas = new JPanel();
              canvas.setBackground(Color.white);
              JButton sort = new JButton("Faster");
              JButton cancel = new JButton("Slower");
              sort.addActionListener(new ButtonListener());
              cancel.addActionListener(new ButtonListener());
              JComboBox algChooser = new JComboBox(algoritmy);
              algChooser.addActionListener(new ComboListener());
              JPanel controlPanel = new JPanel(new FlowLayout());
              controlPanel.add(algChooser);
              controlPanel.add(sort);
              controlPanel.add(cancel);
              canvas.setPreferredSize(new Dimension(200,200));
              // canvas.setBorder(BorderFactory.createLineBorder(Color.black));
              JPanel contentPane = new JPanel(new BorderLayout());
              // contentPane.setBounds(1, 1, 200, 200);
              contentPane.add(canvas,BorderLayout.CENTER);
              contentPane.add(controlPanel,BorderLayout.PAGE_END);
              // contentPane.setBorder(BorderFactory.createLineBorder(Color.red));
         f.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
         System.exit(0);
         f.add(contentPane);
         f.pack();
         f.setSize(800,375);
         f.setVisible(true);
         int[] cisla = fillArray(70);
    while (algoritmus == 0){
    try{
         Thread.sleep(1);
    }catch(InterruptedException ie){}
    if (algoritmus == 1){
    QuickSort qs = new QuickSort(canvas);
    qs.sort(cisla);
    if (algoritmus == 2){
    BubbleSort bs = new BubbleSort(canvas);
    bs.sort(cisla);
         public static int[] fillArray(int numbers){
              int temp=0;
              int[] arrayOfNumbers= new int[numbers];
              for (int i=0;i<numbers;i++){
                   arrayOfNumbers[i] = i;
              for (int i=0;i<numbers;i++){
                   Random generator = new Random();
                   int left =generator.nextInt(numbers);
                   int right =generator.nextInt(numbers);
                   temp=arrayOfNumbers[left];
                   arrayOfNumbers[left]=arrayOfNumbers[right];
                   arrayOfNumbers[right]=temp;
              return arrayOfNumbers;
    Thank you very much                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    //  <applet code="GrafikaApplet" width="400" height="400"></applet>
    //  use: >appletviewer GrafikaApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class GrafikaApplet extends JApplet {
        String[] algoritmy={"V�ber Algoritmu","QuickSort","BubbleSort"};
        int algoritmus = 0;
        boolean running = false;
        GrafikaPanel canvas;
        int[] cisla;
        public void init() {
            cisla = fillArray(70);
            canvas = new GrafikaPanel(cisla);
            canvas.setPreferredSize(new Dimension(200,200));
           resize(800,375);
            Container cp = getContentPane();
            cp.add(canvas, BorderLayout.CENTER);
            cp.add(getControlPanel(), BorderLayout.PAGE_END);
        private int[] fillArray(int numbers){
            Random generator = new Random();
            int temp=0;
            int[] arrayOfNumbers= new int[numbers];
            for (int i=0;i<numbers;i++){
                arrayOfNumbers[i] = i;
            for (int i=0;i<numbers;i++){
                int left = generator.nextInt(numbers);
                int right = generator.nextInt(numbers);
                temp=arrayOfNumbers[left];
                arrayOfNumbers[left]=arrayOfNumbers[right];
                arrayOfNumbers[right]=temp;
            return arrayOfNumbers;
        private void startAnimation() {
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    switch(algoritmus) {
                        case 1:
                            new QuickSort2(canvas).sort(cisla);
                    running = false;
            thread.setPriority(Thread.NORM_PRIORITY);
            thread.start();
        class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if(!running) {
                    running = true;
                    algoritmus = 1;
                    startAnimation();
        private JPanel getControlPanel(){
            JButton sort = new JButton("Faster");
            JButton cancel = new JButton("Slower");
            ButtonListener bl = new ButtonListener();
            sort.addActionListener(bl);
            cancel.addActionListener(bl);
            JComboBox algChooser = new JComboBox(algoritmy);
    //        algChooser.addActionListener(new ComboListener());
            JPanel controlPanel = new JPanel(new FlowLayout());
            System.out.println("default layout for JPanel = " +
                                new JPanel().getLayout().getClass().getName());
            controlPanel.add(algChooser);
            controlPanel.add(sort);
            controlPanel.add(cancel);
            return controlPanel;
    class GrafikaPanel extends JPanel {
       int[] cisla;
       int left;
       int right;
       int pivot;
        public GrafikaPanel(int[] cisla) {
            this.cisla = cisla;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for(int i=0;i<cisla.length;i++){               
                if(cisla==cisla[left]){
    g.setColor(Color.lightGray);
    g.drawLine(10, 20+i*4, 500,20+i*4 );
    if(cisla[i]==cisla[right]){
    g.setColor(Color.lightGray);
    g.drawLine(10, 20+i*4+1, 500,20+i*4+1 );
    else {
    g.setColor(Color.white);
    g.drawLine(10, 20+i*4-1, 500,20+i*4-1 );
    for(int i=0;i<cisla.length;i++){     
    if(cisla[i]==pivot){
    g.setColor(Color.green);
    else {
    g.setColor(Color.red);
    g.fillRect(10, 20+i*4, cisla[i], 2);
    g.setColor(Color.white);
    g.fillRect(9+cisla[i]+1,20+ i*4, 1000, 2);
    public void drawIt(int[] cisla, int pivot){
    this.cisla = cisla;
    this.pivot = pivot;
    repaint();
    class QuickSort2{
    GrafikaPanel component;
    public QuickSort2(GrafikaPanel gp){
    component = gp;
    public void sort (int[] vstupnePole) {
    QSort(vstupnePole,0,vstupnePole.length-1);
    public void QSort(int[] array,int zac,int kon){
    int i = zac;
    int j = kon;
    int pivot = array[(i+j)/2];
    while(i<=j){
    try {
    Thread.sleep(100);
    component.drawIt(array,pivot);          
    }catch(InterruptedException ie){break;}
    while(pivot<array[j]){j--;}
    while(pivot>array[i]){i++;}
    if (i<=j){
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
    i++;
    j--;
    if (zac<j){QSort(array,zac,j);}
    if (i<kon){QSort(array,i,kon);}

  • At a dead end.  A java student in need of help.

    I've hit a wall.
    The program is supposed to allow the user to draw five different polygons using the polygon class and let the user pick the color for each polygon and move each polygon around the screen once it is filled in. The user clicks to add the points and then double clicks to fill in the polygon. Then the polygon is added to the array. Up to the dragging around the screen the program works fine. When I click on a polygon with the shift down nothing happens and I've spent several hours trying to figure out why.
    I've placed several System.out.println's in the code and I think I've narrowed down the problem. (I hope) I think it might have something to do with the canvas repainting. Because the S.O.P's show that the program is going through and executing that code. It might also have something to the do with my polygon array, but to my knowledge that is setup fine.
    Thanks a bunch if you try to help.
    Brad
    // Full Code Below
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         private JButton reset;
         private Podly polyArray[] = new Podly[5];
         private Podly currentPoly = new Podly();
         private Podly movingPoly = new Podly();
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              count = 0;
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              reset = new JButton("Reset");
              reset.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(reset);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         public static void main(String [] args)
              JFrame main = new poly();
              main.setSize(600, 600);
              main.setVisible(true);
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else if (test instanceof JButton) // Repaints if Reset Button is Pressed
                   repaint();
                   currentPoly.reset();
                   count = 0;
                   overflowed = false;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon // Class adds Color Fuctionality to Polygon class
              Color polyColor;
              void setColor(Color y)
              {polyColor = y;}
              Color getColor()
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   System.out.println("Canvas is called");
                   System.out.println(polyArray);
                   for (int i=0; i>count;i++)
                        System.out.println("Loop is going");
                        Podly y = polyArray;
                        g.setColor(y.getColor());
                        g.fillPolygon(y);
                        System.out.println(y);
                        System.out.println("Loop has filled in polygon"); // Test
                   System.out.println("painting complete");
         class Points extends MouseAdapter
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // Allows user to play again.
                             repaint();
                             currentPoly.reset();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  System.out.println("Gets before Check loop");
                                  for (int r=count-1;r>=0;r--)
                                       System.out.println("Inside For Check Loop");
                                       System.out.println(polyArray[r]);
                                       if (!polyArray[r].contains(x,y))          
                                            System.out.println("Point is found");
                                            movingPoly = polyArray[r];
                                            System.out.println("MovingPoly Defined");
                                            moving = true;
                                            System.out.println("Moving is true"); // test
                                            break;
                             else
                                  currentPoly.setColor(currentColor);
                                  currentPoly.addPoint(x,y);
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  currentPoly.reset();
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true;}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        System.out.println("Gets here");
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();

    Here is the updated code still with the color error I talked about above.
    :) Thanks for all the help everyone.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         Podly [] polyArray;
         private Podly currentPoly;
         private Podly movingPoly;
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private Color polyColor;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // Exits program on window close.
              polyArray = new Podly[5];
              count = 0;                                      // Set count to zero.
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         /* Button Listeners */
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon  // Class adds Color Fuctionality to Polygon class
              void setColor(Color y)  // sets the Polygon's color.
              {polyColor = y;}
              Color getColor()   // returns the Polygon's color.
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                        for (int i=0; i<count;i++)
                             g.setColor(polyArray.getColor());
                             g.fillPolygon(polyArray[i]);
         class Points extends MouseAdapter
              /* Listens for mouse press, constructs polygons, stores them in array. */
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // allows user to play again by resetting.
                             repaint();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  for (int r=count-1;r>=0;r--)
                                       if (polyArray[r].contains(x,y))          
                                            movingPoly = polyArray[r];
                                            moving = true;
                                            break; // exits for loop after Polygon with point is found.
                             else
                                  currentPoly = new Podly();
                                  currentPoly.addPoint(x,y); // Adds the first point.
                                  currentPoly.setColor(currentColor); // Sets the Polygon Color
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             /* Close the current Polygon at double click,
                             * then moves on to the next. */
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true; canvas.repaint();}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              /* Listens for mouse release */
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         /* Moves selected Polygon around */
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();
         public static void main(String [] args)
              JFrame poly = new poly();
              poly.setSize(600, 600);
              poly.setVisible(true);

  • Help with simple shooter game

    I am doing a school project and no one seems to know how to use graphics, sound, and most importantly KEY AND MOUSE EVENTS.
    Anyways I can't get my events for the mouse and keyboard to work correctly, so if anyone knows what is wrong or has some suggestions I would really appreciate it. Here is the code:
    the program is called from an application just so you know... this is the application:
    public class AnimateTest
    public static void main (String[] args)
    Animate pic = new Animate (10);
    //and this is the proram itself
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.MouseListener.*;
    import java.awt.event.MouseAdapter.*;
    import java.awt.event.MouseEvent.*;
    import java.awt.event.KeyAdapter.*;
    import java.awt.event.KeyListener.*;
    import java.awt.event.KeyEvent.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.applet.AudioClip;
    public class Animate extends Frame //implements KeyListener//implements MouseListener
    // The image of the background.
    protected Image background;
    // The gun images.
    protected Image gun1, gun2, gun3, gun4, gun5, gun6, gun7, gun8, gun9, gun10;
    //the status bar images
    protected Image hpbox;
    protected Image scorebox;
    //declares the blood explosion image
    protected Image blood;
    //declares the window icon
    protected Image icon;
    // The canvas where the images are drawn.
    protected AnimatePictureCanvas canvas;
    // The number of guns.
    protected int numGuns;
    // Flag to indicate when to quit.
    protected boolean quitting = false;
    //declares the cursor so it can be set to a targeting reticle
    Cursor reticle;
    //declares a variable which designates which gun is in use
    int i = 0;
    //the user's health points
    int hp = 100;
    //enemy arrays
    boolean alive [];
    boolean onScreen [];
    //enemy integers
    int currentDude = 3;
    int liveCount = 10;
    int screenCount = 0;
    //damage variables
    int damage = 0;
    int moreHits;
    int chance;
    //the x and y coordinates of the enemies
    int ex1 = 175;
    int ex2 = 345;
    int ex3 = 520;
    int ex4 = 25;
    int ex5 = 240;
    int ex6 = 370;
    int ex7 = 470;
    int ex8 = 626;
    int ex9 = 260;
    int ex10 = 120;
    int ey1 = 228;
    int ey2 = 190;
    int ey3 = 115;
    int ey4 = 210;
    int ey5 = 35;
    int ey6 = 330;
    int ey7 = 202;
    int ey8 = 192;
    int ey9 = 210;
    int ey10 = 140;
    //blood variables
    int splat = 0;
    int bloodx = -100;
    int bloody = -100;
    // The constructor. Create the Frame, make it visible, load the
    // images, and when the images are loaded, call the animate method
    // to move the images around the window.
    public Animate (int numGuns)
    super ("Stupid Shooting Game"); // Create a Frame.
    //sets the window icon
    icon = getToolkit ().getImage ("icon.jpg");
    prepareImage (icon, this);
    setIconImage (icon);
    this.numGuns = numGuns;
    //initialize the arrays for the enemies
    alive = new boolean [10];
    for (int z = 0 ; z <= 9 ; z++)
    alive [z] = true;
    onScreen = new boolean [10];
    onScreen [0] = true;
    onScreen [1] = true;
    onScreen [2] = true;
    onScreen [3] = false;
    onScreen [4] = false;
    onScreen [5] = false;
    onScreen [6] = false;
    onScreen [7] = false;
    onScreen [8] = false;
    onScreen [9] = false;
    //initialize the cursor to make the mouse a targeting reticle
    reticle = new Cursor (Cursor.CROSSHAIR_CURSOR);
    setCursor (reticle);
    // Place the loading message in the window.
    Label loadingMessageLabel = new Label ("Loading images...");
    add ("North", loadingMessageLabel);
    // Display the window.
    pack ();
    setVisible (true);
    // Create the Images and add them to the tracker.
    MediaTracker tracker = new MediaTracker (this);
    background = getToolkit ().getImage ("midtown1.jpg");
    tracker.addImage (background, 0);
    //prepares the gun images for the image tracker
    gun1 = getToolkit ().getImage ("ggun1.jpg");
    tracker.addImage (gun1, 1);
    gun2 = getToolkit ().getImage ("ggun2.jpg");
    tracker.addImage (gun2, 2);
    gun3 = getToolkit ().getImage ("ggun3.jpg");
    tracker.addImage (gun3, 3);
    gun4 = getToolkit ().getImage ("ggun4.jpg");
    tracker.addImage (gun4, 4);
    gun5 = getToolkit ().getImage ("ggun5.jpg");
    tracker.addImage (gun5, 5);
    gun6 = getToolkit ().getImage ("ggun6.jpg");
    tracker.addImage (gun6, 6);
    gun7 = getToolkit ().getImage ("ggun7.jpg");
    tracker.addImage (gun7, 7);
    gun8 = getToolkit ().getImage ("ggun8.jpg");
    tracker.addImage (gun8, 8);
    gun9 = getToolkit ().getImage ("ggun9.jpg");
    tracker.addImage (gun9, 9);
    gun10 = getToolkit ().getImage ("ggun0.jpg");
    tracker.addImage (gun10, 10);
    //prepares the status bar images for the tracker
    hpbox = getToolkit ().getImage ("hpbox.jpg");
    tracker.addImage (hpbox, 11);
    scorebox = getToolkit ().getImage ("scorebox.jpg");
    tracker.addImage (scorebox, 12);
    //prepares the blood image
    blood = getToolkit ().getImage ("splash.jpg");
    tracker.addImage (blood, 13);
    // Load the images.
    try
    tracker.waitForAll ();
    catch (InterruptedException e)
    // This exception will not happen in our program, but
    // Java requires that we handle it anyway.
    System.out.println ("Wait interrupted.");
    if (tracker.isErrorAny ())
    loadingMessageLabel.setText ("Image loading failed!");
    else
    // All the images are now loaded. Remove the loading label.
    remove (loadingMessageLabel);
    // Create and place the canvas.
    canvas = new AnimatePictureCanvas (background);
    canvas.setSize (background.getWidth (null),
    background.getHeight (null));
    add ("Center", canvas);
    pack (); // Resize the Frame to fit the canvas.
    validate (); // Force the Frame to be redrawn.
    animate ();
    } // Animate constructor
    // Move the bouncers over the background.
    public void animate ()
    // Create the offscreen bitmap.
    int bgWidth = background.getWidth (null);
    int bgHeight = background.getHeight (null);
    Image offscreen = this.createImage (bgWidth, bgHeight);
    // Get the width and height of the guns.
    int gun1Width = gun1.getWidth (null);
    int gun1Height = gun1.getHeight (null);
    int gun2Width = gun2.getWidth (null);
    int gun2Height = gun2.getHeight (null);
    int gun3Width = gun3.getWidth (null);
    int gun3Height = gun3.getHeight (null);
    int gun4Width = gun4.getWidth (null);
    int gun4Height = gun4.getHeight (null);
    int gun5Width = gun5.getWidth (null);
    int gun5Height = gun5.getHeight (null);
    int gun6Width = gun6.getWidth (null);
    int gun6Height = gun6.getHeight (null);
    int gun7Width = gun7.getWidth (null);
    int gun7Height = gun7.getHeight (null);
    int gun8Width = gun8.getWidth (null);
    int gun8Height = gun8.getHeight (null);
    int gun9Width = gun9.getWidth (null);
    int gun9Height = gun9.getHeight (null);
    int gun10Width = gun10.getWidth (null);
    int gun10Height = gun10.getHeight (null);
    //finds the width and height of the status bar images
    int hpboxWidth = hpbox.getWidth (null);
    int hpboxHeight = hpbox.getHeight (null);
    int scoreboxWidth = scorebox.getWidth (null);
    int scoreboxHeight = scorebox.getHeight (null);
    // Create the arrays containining the location and
    // direction of the bouncers.
    int locX;
    int locY;
    // Initialize the gun Image's location
    locX = (bgWidth - gun1Width);
    locY = (bgHeight - gun1Height);
    // Get the graphics contexts for both the offscreen image and
    // the canvas.
    Graphics offscreenG = offscreen.getGraphics ();
    Graphics canvasG = canvas.getGraphics ();
    while (!quitting)
    //sets the mouse listener to check for shots being fired
    addMouseListener (new MouseAdapter ()
    public void mouseClicked (MouseEvent e)
    int xClick = e.getX ();
    int yClick = e.getY ();
    System.out.println (" " + xClick + " " + yClick);
    delay (1000000);
    fire (xClick, yClick);
    //sets the keylistener to check for a change in the current gun
    // addKeyListener (new KeyAdapter ()
    // public void keyTyped (KeyEvent e)
    // if (e.getKeyChar () == 'f')
    // i += 1;
    // if (i == 10)
    // i = 0;
    // if (e.getKeyChar () == 'd')
    // i -= 1;
    // if (i == -1)
    // i = 9;
    // Draw the background image to the offscreen bitmap, erasing
    // everything that is already there.
    offscreenG.drawImage (background, 0, 0, null);
    //draw the status bar at the bottom of the screen
    offscreenG.setColor (Color.black);
    offscreenG.fillRect (0, bgHeight - gun1Height, bgWidth, bgHeight);
    // Draw each bouncer to the offscreen image. Move each of
    // the bouncers, changing their direction when they encounter
    // an edge.
    offscreenG.drawImage (gun1, locX, locY, null);
    //draws the status bar
    offscreenG.drawImage (hpbox, 15, bgHeight - gun1Height + 10, null);
    offscreenG.drawImage (scorebox, hpboxWidth + 15 + 20, bgHeight - gun1Height + 25, null);
    //draws blood if a target is hit
    if (splat == 1)
    offscreenG.drawImage (blood, bloodx, bloody, null);
    delay (10000000);
    splat = 0;
    if (hp == 0)
    //drawString "you lose"
    break;
    else
    //determines the number of enemies still alive
    liveCount = 10;
    for (int a = 0 ; a <= 9 ; a++)
    if (alive [a] == true)
    else
    liveCount -= 1;
    if (liveCount == 0)
    //drawString "you win... get ready for LVL 2!!!"
    break;
    //determines the number of enemies onscreen and adds more if necessary
    screenCount = 0;
    for (int b = 0 ; b <= 9 ; b++)
    if (onScreen == true)
    screenCount += 1;
    if (screenCount < 3 && liveCount > 3)
    onScreen [currentDude] = true;
    if (currentDude == 9)
    else
    currentDude += 1;
    damage = 0;
    moreHits = 12 / screenCount;
    chance = (int) (Math.random () * moreHits) + 1;
    if (chance == moreHits)
    damage = 10;
    //sets the default color to white so things can be seen on the background
    offscreenG.setColor (Color.white);
    //checks all the enemies to see if they are alive and onscreen,
    //drawing them accordingly
    if (alive [0] == true && onScreen [0] == true)
    offscreenG.fillOval (ex1, ey1, 18, 18);
    if (alive [1] == true && onScreen [1] == true)
    offscreenG.fillOval (ex2, ey2, 13, 13);
    if (alive [2] == true && onScreen [2] == true)
    offscreenG.fillOval (ex3, ey3, 9, 9);
    if (alive [3] == true && onScreen [3] == true)
    offscreenG.fillOval (ex4, ey4, 15, 15);
    if (alive [4] == true && onScreen [4] == true)
    offscreenG.fillOval (ex5, ey5, 11, 11);
    if (alive [5] == true && onScreen [5] == true)
    offscreenG.fillOval (ex6, ey6, 30, 30);
    if (alive [6] == true && onScreen [6] == true)
    offscreenG.fillOval (ex7, ey7, 10, 10);
    if (alive [7] == true && onScreen [7] == true)
    offscreenG.fillOval (ex8, ey8, 10, 10);
    if (alive [8] == true && onScreen [8] == true)
    offscreenG.fillOval (ex9, ey9, 7, 7);
    if (alive [9] == true && onScreen [9] == true)
    offscreenG.fillOval (ex10, ey10, 10, 10);
    // Finally, draw the offscreen image to the canvas.
    canvasG.drawImage (offscreen, 0, 0, null);
    } // animate method
    public void delay (int d)
    for (int x = 1 ; x <= d ; d++)
    public void fire (int x, int y)
    splat = 1;
    bloodx = x;
    bloody = y;
    //play a sound
    //show bloody explosion
    //check to see if a stick man is alive and onscreen
    // Called by the system when an event occurs. Handle the
    // window's close box being pressed by halting the program.
    public boolean handleEvent (Event evt)
    if (evt.id == Event.WINDOW_DESTROY)
    quitting = true; // Set the flag so the animate loop will exit.
    setVisible (false); // Hide the window.
    System.exit (0);
    return true;
    return super.handleEvent (evt);
    } // handleEvent method
    } /* Animate */
    // The "AnimatePictureCanvas" class.
    // This class draws the image passed into its constructor, although it needs
    // only do so when the screen needs repainting.
    class AnimatePictureCanvas extends Canvas
    Image background; // The parent Frame containing all the image info.
    public AnimatePictureCanvas (Image background)
    this.background = background;
    } // AnimatePictureCanvas constructor
    // The paint method is called whenever the canvas needs to be redrawn.
    public void paint (Graphics g)
    g.setColor (Color.black);
    setBackground (Color.black);
    g.drawImage (background, 0, 0, null);
    } // paint method
    } /* AnimatePictureCanvas class */

    I wrote this a while ago so that i would not have to create events for every applet i created, instead I just extended this code. Since applet itself extends panel, you can just drop it anywhere you want (eg in a frame) and use its methpods. Otherwise you can change the code so that you extend frame/Jframe/...
    * EventApplet.java
    * Created on October 7, 2001, 10:55 PM
    package com.moss.util;
    import java.applet.Applet;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ContainerAdapter;
    import java.awt.event.ContainerEvent;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    /** Library that provides a set of handlers for most events.
    * @author  [Black Flag]
    * @version 1.0
    public class EventApplet extends Applet
        /** deals with component events
        public final void setComponentListeners()
            addComponentListener(new ComponentAdapter()
                public void componentResized(ComponentEvent evt)
                    formComponentResized(evt);
                public void componentMoved(ComponentEvent evt)
                    formComponentMoved(evt);
                public void componentShown(ComponentEvent evt)
                    formComponentShown(evt);
                public void componentHidden(ComponentEvent evt)
                    formComponentHidden(evt);
        /** Deals with container events
        public final void setContainerListeners()
            addContainerListener(new ContainerAdapter()
                public void componentAdded(ContainerEvent evt)
                    formComponentAdded(evt);
                public void componentRemoved(ContainerEvent evt)
                    formComponentRemoved(evt);
        /** Deals with focus events
        public final void setFocusListeners()
            addFocusListener(new FocusAdapter()
                public void focusGained(FocusEvent evt)
                    formFocusGained(evt);
                public void focusLost(FocusEvent evt)
                    formFocusLost(evt);
        /** Deals with key events
        public final void setKeyListeners()
            addKeyListener(new KeyAdapter()
                public void keyTyped(KeyEvent evt)
                    formKeyTyped(evt);
                public void keyPressed(KeyEvent evt)
                    formKeyPressed(evt);
                public void keyReleased(KeyEvent evt)
                    formKeyReleased(evt);
        /** Deals with mouse events
        public final void setMouseListeners()
            addMouseListener(new MouseAdapter()
                public void mousePressed(MouseEvent evt)
                    formMousePressed(evt);
                public void mouseReleased(MouseEvent evt)
                    formMouseReleased(evt);
                public void mouseClicked(MouseEvent evt)
                    formMouseClicked(evt);
                public void mouseExited(MouseEvent evt)
                    formMouseExited(evt);
                public void mouseEntered(MouseEvent evt)
                    formMouseEntered(evt);
        /** Deals with mouse motion events
        public final void setMouseMotionListeners()
            addMouseMotionListener(new MouseMotionAdapter()
                public void mouseMoved(MouseEvent evt)
                    formMouseMoved(evt);
                public void mouseDragged(MouseEvent evt)
                    formMouseDragged(evt);
        /** Override to provide this event
         * @param evt The event
        public void formComponentResized(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentMoved(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentShown(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentHidden(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentAdded(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentRemoved(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusGained(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusLost(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyTyped(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyPressed(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyReleased(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMousePressed(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseReleased(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseClicked(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseExited(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseEntered(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseMoved(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseDragged(MouseEvent evt)
    }You will probably want to declare those last methods abstract. i didn't because i just couldn't be arsed.
    have fun.

  • Output problem urgent!!

    Okay so heres the problem i have a piece of code to convert a decimal value that a user enters into a binary value. My algorithm works its just when the binary value is displayed only the last element of the binary value to be outputed is displayed. But i want all the values of the binary number to be displayed. I dont know what to do plz help.
    the code i am using is:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.swing.*;
    public class conversion extends JPanel implements ActionListener
         JPanel board;                // Panel for buttons
         JLabel canvas;               // Text Area for displaying answer
        JButton convert, reset;  // buttons
           JTextField input;       //input text box
             public conversion()
                 super(true); // Call constructor of parent
              // Standard layout (flow)
                 setLayout(new FlowLayout());
              // Set up two panels, control board and canvas
                 board = new JPanel(true);
              canvas = new JLabel();
                 board.setPreferredSize(new Dimension(100, 100));
                 canvas.setPreferredSize(new Dimension(300, 300));
              board.setBorder(BorderFactory.createLineBorder(Color.black));
              canvas.setBorder(BorderFactory.createLineBorder(Color.blue));
              // Create buttons and attach listeners
                 convert = new JButton("Convert");
                 convert.addActionListener(this);
                 reset = new JButton("Reset");
                 reset.addActionListener(this);
              input = new JTextField(8);
                 add(canvas); add(board);
              // Add button to board panel
            board.add(convert);
              board.add(input);
              board.add(reset);
         public void actionPerformed(ActionEvent e)
              String inputInfo;
              inputInfo = input.getText();
              if (e.getSource() == convert){           //action on convert button
               //algorithm for decimal to binary conversion
              int a = Integer.parseInt(inputInfo);    //Gets decimal number inputed
              if (a > 255){
                   canvas.setText("Please enter a number below 256");
              else {
              int b[] = new int[50];
              int i = 0;
              if (a / 2!=0 || a==1)               //Checks to see if decimal number is divisible by 2
              {                                             //Or exactly equal to 1
              while(a!= 1)                            //While loop for when the decimal inputted is not equal to 1
              b= a % 2;                              
              a = a / 2;                                   //Check to see if the remainder is divisible by 2
              i++;
              b[i]= 1;
              for(int x=i;x>=0;x--)
                                                      //Displays the binary answer
                   int answer = b[x];
                   String stringAns = Integer.toString(b[x]);     
                   System.out.println(stringAns);
                   canvas.setText ("The binary for your decimal is: " + stringAns); // this is the problem here, only the last element is displayed
              if (e.getSource() == reset){           //action on reset button
                   canvas.setText("");     
                   input.setText("");
              //Graphics g = canvas.getGraphics();}
         public static void main(String[] args)
         // Create a Blob entity
         conversion b = new conversion();
              // Set up outer frame, and its exit behaviour
         JFrame frame = new JFrame("Decimal to binary");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Set the main content frame to be the Blob,
              // size the frame (pack) and make it visible
         frame.setContentPane(b);
         frame.pack();
         frame.setVisible(true);

    pauze wrote:
              for(int x=i;x>=0;x--)
                                                      //Displays the binary answer
                   int answer = b[x];
                   String stringAns = Integer.toString(b[x]);     
                   System.out.println(stringAns);
                   canvas.setText ("The binary for your decimal is: " + stringAns);        // this is the problem here, only the last element is displayed
    Each element in the array b contains one digit of the binary representation. You need to convert each digit into a character and then concatenate all the characters into a String before displaying anything.

  • Help with Line of Best Fit equation!

    Alright, I'm making a graphing program where the user can input up to 10 coordinates (all ints) and when they click draw, the points will be graphed on a cartesian plain and the program will calculate and draw the line of best fit... including displaying the equation.
    I've got the yIntercept to work perfectly, but sometimes the slope comes out to be 0.0, and such.
    The equation to do it can be found on this site (in the big white space)
    http://people.hofstra.edu/faculty/Stefan_Waner/RealWorld/calctopic1/regression.html
    There are several things you must do first:
    - Find the sum of all the X values
    - Find the sum of all the Y values
    - Find the sum of all the X*Y values
    - Find the sum of all the X^2 values
    You then stick it into the equation (you can see on that site) and you will get the slope. You then take the slope value and insert it into another equation to get the y-intercept
    I was just wondering if you could just look over my calculation and see where I may be going wrong. (Sometimes, I get an error in the console saying I cannot divide by 0)
    public void lineOfBestFit(int numOfPoints, int largeNumX, float increment, float incrementY)
         Graphics g = canvas.getGraphics();
         float sumX = 0;
         float sumY = 0;
         float sumXY = 0;
         float sumXSqr = 0;
         int smallNumX=9999999;
         int firstPoint, lastPoint;
         //Creates the variables for the line of best fit equation
         for(int j=0;j<numOfPoints;j++)
              sumX+=xValue[j];
              sumY+=yValue[j];
              sumXY+=(xValue[j]*yValue[j]);
              sumXSqr+=(Math.pow(xValue[j],2));
         //Line of best fit equation
         float slope = ((numOfPoints*sumXY)-(sumX*sumY))/((numOfPoints*sumXSqr)-(sumX*sumX));
         float yInt = (sumY - (slope*sumX))/numOfPoints;
         for(int j=0;j<numOfPoints;j++)
              if(xValue[j]<smallNumX)
                   smallNumX=xValue[j];
         firstPoint=((int)((slope*smallNumX)+yInt)*50/(int)incrementY+210);
         lastPoint=((int)(slope*largeNumX+yInt)*50/(int)incrementY+210);
         int firstX=((int)(smallNumX*50/(int)increment+210));
         int lastX=((int)(largeNumX*50/(int)increment+210));
         g.drawLine(firstX,firstPoint,lastX,lastPoint);
         //Rounds and displays the line of best fit equation
         slope = (Math.round(slope*100))/100;
         yInt = (Math.round(yInt*100))/100;
         if(numOfPoints>1)
                     if(yInt < 0)
              g.drawString("y = " +slope+ "x " +yInt,250,350);
              else
                   g.drawString("y = " +slope+ "x +" +yInt,250,350);

    I think I may have solved it.... seems to be working now.
    I casted all the numOfPoints as (float) .... and commented out the rounding. Since some of the slopes were coming out to be 0.00003, that would display 0.0 if I rounded.

  • Flash CS3 vs. Flex Builder 2

    Here's the $64,000 question: should we be developing in Flash
    CS3 or should we shift over to Flex Builder 2? I maintain that AS
    3.0 is a pain in the proverbial, but I've been researching and
    finding as much help as possible online about it, and I've found
    that by and large people are using Flex Builder 2 as the basis of
    tutorials about AS 3.0. Does anyone have an official slant on this
    question? Should we abandon Flash for Flex? Will it help? Will it
    mitigate the difficulties non-programmers are experiencing with AS
    3.0 - or as I call it simply ***? Would I be getting more responses
    to my *** questions if I post them over in the *** forum under Flex
    Builder?
    Any thoughts on this matter would be most welcome, thank
    you.

    Beatie3,
    >> Help please.
    Sorry about that ... some days are crazier than others. :-/
    [From an earlier reply ...]
    > Thank you very much, that's exactly the sort of answer I
    > needed. Hmmm, cheque's in the mail. ;)
    Heh, good on ya! :)
    > I'm definitely a 'deseloper' and will stick with Flash.
    I wish
    > I had the luxury of only dipping into AS3.
    I don't know that I'd call it a luxury, really. Work is
    work. ;) As
    you might imagine, though, Flex Builder 2 provides a number
    of scripting
    improvements over the Actions panel (there's really no
    comparison; if you've
    tried them both, the Actions panel barely feels useful) and
    the Flex
    framework offers significantly more UI Components. Ideally,
    if the pocket
    book allows it, using both applications is the killer setup.
    > My problem is that I built a little program that draws
    scale bars
    > on uploaded images that can then be printed. It did
    everything
    > it needed to, but in AS2.0 you can't control the quality
    of the
    > imported jpgs.
    When you say imported, you mean dynamically loaded (loaded
    at runtime),
    right? Otherwise, I'm confused. The Flash IDE itself allows
    you to
    determine the quality of imported JPGs. In ActionScript 3.0
    ... are you
    talking about the Stage.quality property?
    > I'm experimenting with Sprites and I have something
    appearing
    > as the line is drawn but I can't crack the new way to
    express
    > coordinates.
    Not sure what might be tripping you up, actually. The
    coordinate grid
    is the same. Horizontally, higher numbers move toward the
    right;
    vertically, higher numbers move toward the bottom. That's the
    same as it's
    been.
    > I just want a blue hair line with a nice green dot at
    each end
    > that can be seen while the line is drawn. Once the
    mouseUp
    > happens the drawing guide should disappear and the black
    > line appear.
    Having heard what you're after, I just started a quick
    experiment from
    scratch. Here's my version, below. Note: I've made no effort
    to optimize
    my code. This is just a first draft to achieve a blue line
    segment with
    green dots on each end that becomes a black line segment when
    the mouse
    lifts.
    var startX:Number;
    var startY:Number;
    var canvas:Sprite = new Sprite();
    addChild(canvas);
    canvas.stage.addEventListener(MouseEvent.MOUSE_DOWN,
    mouseDownHandler);
    canvas.stage.addEventListener(MouseEvent.MOUSE_UP,
    mouseUpHandler);
    function mouseDownHandler(evt:MouseEvent):void {
    startX = mouseX;
    startY = mouseY;
    var dot:Sprite = new Sprite();
    dot.name = "dotStart";
    dot.graphics.beginFill(0x00FF00);
    dot.graphics.drawCircle(mouseX, mouseY, 5);
    dot.graphics.endFill();
    canvas.addChild(dot);
    dot = new Sprite();
    dot.name = "dotEnd";
    dot.graphics.beginFill(0x00FF00);
    dot.graphics.drawCircle(0, 0, 5);
    dot.graphics.endFill();
    canvas.addChild(dot);
    canvas.addEventListener(Event.ENTER_FRAME,
    enterFrameHandler);
    function enterFrameHandler(evt:Event):void {
    var dot:DisplayObject = canvas.getChildByName("dotEnd");
    dot.x = mouseX;
    dot.y = mouseY;
    canvas.graphics.clear();
    canvas.graphics.lineStyle(1, 0x0000FF);
    canvas.graphics.moveTo(startX, startY);
    canvas.graphics.lineTo(mouseX, mouseY);
    function mouseUpHandler(evt:MouseEvent):void {
    canvas.removeEventListener(Event.ENTER_FRAME,
    enterFrameHandler);
    canvas.removeChild(canvas.getChildByName("dotStart"));
    canvas.removeChild(canvas.getChildByName("dotEnd"));
    canvas.graphics.clear();
    canvas.graphics.lineStyle(2, 0x000000);
    canvas.graphics.moveTo(startX, startY);
    canvas.graphics.lineTo(mouseX, mouseY);
    There's a lot of repeated code there, and this isn't how I'd
    leave the
    above in an actual project, but by spilling out a rough cut
    like this, I'm
    hoping it gives you something to work with -- showing the
    mechanics of how
    this might be done.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

Maybe you are looking for

  • "Open other project" always fails

    Hello all, I have been trying to figure out how to get the project end option "Open other project" to work. I am using two small SWFS, linking one to the other, but at the end of the first project I get the "Page cannot be displayed" message despite

  • Using collection as a stored proc. parameter

    I have a requirement of a using a stored proc ('in') parameter as a collection and using it futher in the where clause of a sql query. What are my options here ? I am currently trying with a nested table, getting errors in using with sql query. What

  • Why should we use BRTOOLS for  oracle data backup?

    Hi there, Any one of you have any idea on specific advantages with using BRTOOLS for backup over using only Oracle RMAN? Are there any advantages using brbackup in databackups which we do not get with RMAN alone? thanks Arlin

  • XServe 10.6 SL Setup Assistant Fails

    Hello All, Been hacking at an XServer 2,1 (Early 2008) box for the past 18 hours or so straight attempting to do a clean reinstall from L to SL Server. Each round I have cleared (repartitioning to be certain) the system drive (raid) and performed the

  • Adding a column in advanced table using personalizations

    Is it possible to add a column in advanced table using personalizations. If Yes , then i am not able get "Create Item" Icon on Advanced table Level personalizations . Can some one give reason? or there is any other way to create Item in Adavnce table