Painting on Canvas or Applet?

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

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

Similar Messages

  • How do I put a hyperlink button on the Canvas in Applet

    I am tried to put a hyperlink button on the Canvas in Applet.
    But Canvas is a componet that can't contain any component.
    I hope best way that is like hyperlink of HTML , I just clicked this hyperlink in Canvas,it's automation link to directed homepage.
    Can I have any way to do that?

    You can setup Restrictions...
    Tap Settings > General > Restrictions
    AFAIK, it's not possible to attach a password for access to the Settings.

  • Re: adding canvas to applet

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

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

  • Need to paint objects from one applet into another

    Maybe this question is more at home here; I have an applet test program which uses the timer class to make a car drive across the screen. The test works fine with the rectangle I used, but now I need to use the car created in this class:
       import java.applet.Applet;
       import java.awt.Graphics;
       import java.awt.Graphics2D;
       import java.awt.Rectangle;
       import java.awt.geom.Ellipse2D; 
       import java.awt.geom.Line2D;
       import java.awt.geom.Point2D;
         public class Car extends Applet
              public void paint(Graphics g)
                   Graphics2D g2 =(Graphics2D)g;
                   Rectangle body =new Rectangle(100, 110, 60, 10);
                   Ellipse2D.Double frontTire =new Ellipse2D.Double(110, 120, 10, 10);
                   Ellipse2D.Double rearTire =new Ellipse2D.Double(140, 120, 10, 10);
                   Point2D.Double r1 =new Point2D.Double(110, 110);
                   //the bottom of the front windshield
                   Point2D.Double r2 =new Point2D.Double(120, 100);
                   //the front of the roof
                   Point2D.Double r3 =new Point2D.Double(140, 100);
                   //the rear of the roof
                   Point2D.Double r4 =new Point2D.Double(150, 110);
                   //the bottom of the rear windshield
                   Line2D.Double frontWindshield =new Line2D.Double(r1, r2);
                   Line2D.Double roofTop =new Line2D.Double(r2, r3);
                   Line2D.Double rearWindshield =new Line2D.Double(r3, r4);
                   g2.draw(body);
                   g2.draw(frontTire);
                   g2.draw(rearTire);
                   g2.draw(frontWindshield);
                   g2.draw(roofTop);
                   g2.draw(rearWindshield);
         }The only thing I could think of was making an object of type Car in the test program and then doing something like this:
    Car c =new Car();
    g2.draw(c.paint(g));
    But it says in the test program void type not allowed here. Any tips as to what I'm doing wrong? My guess is that its a problem in the Car class and not the test program, but I didn't think I was supposed to alter Car. (Plus I tried already and couldn't get it to work.)

    what? I don't see what you are trying to do..
    You are trying to make an instance of a class which has no constructor?
    You are trying to move a Panel (an Applet is a subclass of Panel) in another Panel (in Test class?)
    Keep in mind that the Panel automatically has flow layout. In flow layout the components are sized to minimum size, and if the component is another Panel, the minimum size is 0 if there are no components in it.
    Do you need both applets open at once?
    Why not just copy this paint code into your test class?
    Also note that you CAN copy the Graphics from one component onto another, but the Graphics object cannot be null, or you will get a NullPointerException... which is what will happen if you try to copy it in the init() of your test class.
    Why not just make your car a Component (or a Panel even) and give it a constructor? (And make sure to set minimum size to something other than zero?)
    I think you have more than one problem..
    Jen

  • Painting on canvas in native cocoa

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

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

  • How to Achieve Oil Painting on Canvas Effect?

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

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

  • Paint()/repaint() problem w/applet

    Hi all. Here's my dilemma: I'm trying to create an applet that asks for simple multiplication answers, and draws a string giving feedback after the question is answered ("Very good!" or "No, try again."). The problem is that the book says to draw everything from paint(), and gives the impression that repaint() should magically refresh everything on the applet, which it does not. How can I make the strings I drew in paint() go away and give way to new strings based on user answer (whether correct or not), instead of piling up on top of each other, because they don't refresh? Also, my JButton and JTextField aren't showing up until the mouse is scrolled over them. Thanks for your time!
    code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Week5Class extends JApplet implements ActionListener
        static int int1 = (int)(Math.random()*10);
        static int int2 = (int)(Math.random()*10);
        JTextField answer = new JTextField(3);
        JButton verifyAnswer = new JButton("Click to see if correct");
        public void init()
            Container myContainer = getContentPane();
            myContainer.add(answer);
            myContainer.add(verifyAnswer);
            verifyAnswer.addActionListener(this);
            myContainer.setLayout(new FlowLayout());
        static int j = 0;
        static int i;
        public void paint(Graphics gr)
              gr.drawString("How much is " + int1 + " * " + int2 + "?", 10, 70);
              if(i == 1)
                  gr.drawString("VeryGood!", 300, 200);
              else if(i == 0 && j != 0)
                  gr.drawString("No. Please try again.", 300, 200);
              j++;
        public void actionPerformed(ActionEvent e)
            int x = 300;
            int y = 200;
            if(Integer.parseInt(answer.getText()) == (int1*int2))
                int1 = (int)(Math.random()*10);
                int2 = (int)(Math.random()*10);
                i = 1;
                repaint();
            else
                i = 0;
                repaint();
    }

    The problem is that you're mixing doing your own drawing and using child objects. The paint method you've overriden would be the one that draws the text field and button.
    A far easier approach would be to use a JLabel to display your response message, and insert that as another component into the container, as you've inserted the button and input field.
    Then use setText() on the label to change the message.
    If you really want to have an area that you draw arbitary shapes on it's best to create your own child component, add it to the container, and override it's paintComponent method. Alternatively create a class which implments the Icon interface and put it in a JLabel.
    FlowLayout isn't very clever, by the way, try a BorderLayout or maybe a BoxLayout.

  • Won't paint to canvas

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

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

  • Position of Canvas in Applet

    Hello, I am creating a simple shoot 'em up game where the player has to blast the meteors.
    The meteors are instances of Canvas's and the location of each is set by using the setLocation() method. When I press the refresh button on IE, the meteors sometimes dont appear in the correct place (i.e. overlap each other).
    The problem usually happens 1 in 200 refreshes of the browser. I know people might think an error as small as this is not worth bothering about, but the game needs to be completly error free.
    I have used setLayout(NULL) so that I can nullify the layout and use the setLocation() method.
    I hope somone can help me out here. I am using JDK 1.3.1_16 (so that it will work with MSJVM) and MSJVM Version 5 Release 5.0.0.3805
    Thanks
    Andrew

    Are you using absolute layout on your entier GUI? or just the container that you have your asteroids in? The reason I as is that if you have the Fit to Screen option on in IE, then it may be becoming confused and shrinking the rest of your interface and causing your asteroids to overlap from time to time.

  • Mysterious null pointers during Applet.paint(g)

    I'm working with the paint function of my applet, which uses double buffering, and I occassionally get an odd null pointer exception, which does not halt its excution, but I believe may be linked to some other unusual behavior regarding components not being painted correctly.
    I've been staring at this thing for a while now and I am completely out of ideas.
    For debugging purposes, I've expressly checked each object invovled in the painting to ensure that it isn't null, but the exception is still being thrown and java is telling me that the exception is being trown on line numbers that have only a closing brace (see code)
    Any help is much appreciated
    Here's the code... state is an extension of Container and loading is just a label to display when I'm changing different containers in and out of state
           public void paint(Graphics g) {
              if(offscreen == null) offscreen = createImage(500, 480);
              else {
                      Graphics g1 = offscreen.getGraphics();
                      if(!dontPaint) {
                        if(loading != null && loading.isVisible()) loading.setVisible(false);
                        if(state!=null) state.paint(g1);
                   else {
                        if(g1 != null) {
                             g1.setColor(Color.black);
                             g1.fillRect(0, 0, 500, 480);
                        if(!loading.isVisible() && loading!=null) loading.setVisible(true);
                      if(g != null) g.drawImage(offscreen, 0, 0, null);
            }here's an example of the errors:
    java.lang.NullPointerException
            at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:48)
            at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:715)
            at sun.java2d.pipe.ValidatePipe.copyImage(ValidatePipe.java:147)
            at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2782)
            at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2772)
            at StarDart.paint(StarDart.java:113)
            at StarDart.update(StarDart.java:96)
            at sun.awt.RepaintArea.paint(RepaintArea.java:172)
            at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:260)
            at java.awt.Component.dispatchEventImpl(Component.java:3586)
            at java.awt.Container.dispatchEventImpl(Container.java:1437)
            at java.awt.Component.dispatchEvent(Component.java:3367)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:190)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:144)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

    I do have a thread which is always running; I use the Runnable interface. Here is my run() function:
         public void run() {
              while(!stopRunning) {
                   for(; sessionInput(); state.handleInput(inBuf));
                           repaint();
                        try {
                                   Thread.sleep(100L);
                        } catch(InterruptedException interruptedexception) { System.out.println(interruptedexception); }
              }The for loop manages my networking code. Should I be putting the call to repaint() in a try block?
    Does this have something to do with synchronization?

  • Need help with paint() within applet

    Hi,
    I am having some problems in using the paint() method within an applet.
    I need to use drawString() in the paint() method.
    However, I discovered that when i used drawString() in paint() method.
    It clears the background which has other GUI components wipe out.
    Pls help, thanx
    Sample code:
    public class watever extends javax.swing.JApplet {
    //initialize some components and variables
    public void init() {
    //adding of components to contentPane
    public void paint(Graphics g) {
    g.drawString("The variable is " + sum, 80, 80);
    }

    super.paint(g) the paint method draws the components to, so if you override it and then never tell it to draw the components they don't get drawn.

  • My applet won't print properly

    I wrote an applet that draws a line graph based on parameters I feed it through <PARAM> tags. Those tages are written dynamically with Cold Fusion. It works perfectly, but what good is a graph if you can't have a copy of it? When I try to print the page with the applet running in it, nothing comes out. My computer is running Win98, IE 6.0 and proper printer drivers. The funny thing is I am able to print some of the demo applets that come with the JDK, but my own applet will not print. It can be printed from other computers around my office. I thought maybe it was IE 6 acting up so I tried Netscape 4.7, 6.0, and Opera 6.0 none of them can print my applet from my computer. I'm just worried that someone out there will have the same problem as me.
    The way I'm drawing the graphs is by overloading the default paint method of the applet. Like I said, it works fine on some computers, and a variety of web browsers, exept IE 6. I looked at the source code of the sample applets that WERE ABLE to print on my computer, I realized they extended the Canvas class, overloaded its paint method, then added the canvas to the applet's panel. I tried to mimic that with my applet and still no luck. I compile the sample applet and mimic the html sample page and then it won't print anymore. Any thoughts on what is going on?

    To print an applet in action make a
    SCREENSHOT!
    The online game players always do this to save screens.
    On WIN 98 it is: STRG+PAUSE I guess.
    Copy the screenshot to e.g. paint.exe and print.
    Hope this helps.

  • Shap drawn in applet couldn't see in Browser

    shap drawn in applet couldn't see in Browser but could see in applet-viewer
    why it happen?
    here is the code :
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import java.awt.geom.*;
    * GeneralPath shape rendered .
    public class ShowTest
        extends JApplet {
      ArrayList groupList, lineList;
      MapCanvas canvas;
      public void init() {
        Container cp = getContentPane();
        BorderLayout bord = new BorderLayout();
        cp.setLayout(bord);
        cp.add(canvas = new MapCanvas(this), "Center");
        JPanel commandPanel = new JPanel();
        JButton connectServlet = new JButton("connect-Servlet");
        commandPanel.add(connectServlet);
        cp.add(commandPanel, "North");
        File file = new File("c:\\Landlock.txt");
        groupList = new ArrayList();
        double p[] = new double[2];
        StringTokenizer st;
        try {
          int count;
          String s;
          FileInputStream fin = new FileInputStream(file);
          InputStreamReader isr = new InputStreamReader(fin);
          BufferedReader br = new BufferedReader(isr);
          for (; (s = br.readLine()) != null; ) {
            lineList = new ArrayList();
            st = new StringTokenizer(s);
            count = Integer.parseInt(st.nextToken());
            //System.out.println(count);
            for (int i = 0; i < count; i++) {
              s = br.readLine();
              st = new StringTokenizer(s);
              for (int j = 0; j <= st.countTokens() && st.hasMoreTokens(); j++) {
                p[j] = Double.parseDouble(st.nextToken());
              lineList.add(new Point2D.Double(p[0], p[1]));
            groupList.add(lineList);
        catch (Exception e) {
          e.printStackTrace();
    class MapCanvas
        extends Canvas {
      ShowTest applet;
      //change condition
      int m_nXLeft, m_nYTop;
      int m_nXRight, m_nYBottom;
      //change condition
      double m_nLXLeft = 0, m_nLYTop = 90;
      double m_nLXRight = 360, m_nLYBottom = -90;
      public MapCanvas(ShowTest app) {
        applet = app;
        setBackground(Color.yellow);
      BufferedImage img;
      public void update(Graphics g) {
        paint(g);
      public void paint(Graphics g) {
        m_nXLeft = getLocation().x;
        m_nYTop = getLocation().y;
        m_nXRight = m_nXLeft + getSize().width;
        m_nYBottom = m_nYTop + getSize().height;
        System.out.println("m_nXLeft " + m_nXLeft);
        System.out.println("m_nYTop " + m_nYTop);
        System.out.println("m_nXRight " + m_nXRight);
        System.out.println("m_nYBottom " + m_nYBottom);
        Graphics2D g2;
        int width = getSize().width;
        int height = getSize().height;
        img = (BufferedImage) createImage(width, height);
        g2 = img.createGraphics();
        g2.clearRect(0, 0, width, height);
        ArrayList lineList, group = applet.groupList;
        Point2D.Double pPoint;
        Point lpFirst = new Point(), lpSecond = new Point();
        GeneralPath p = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
        p.moveTo(33, 18.0f);
        p.lineTo(46.0f, 90.0f);
        p.lineTo(55.0f, 12.0f);
        p.lineTo(200.0f, 100.0f);
        p.lineTo(300.0f, 200.0f);
        p.closePath();
        g2.draw(p);
        g2.drawRect(101, 101, 100, 100);
        int size = group.size();
        GeneralPath coastPath;
        System.out.println("group.size()" + size);
        for (int i = 0; i < 1; i++) {
          coastPath = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
          lineList = (ArrayList) group.get(i);
          pPoint = (Point2D.Double) lineList.get(0);
          //System.out.println("pPoint.x"+pPoint.x+"pPoint.y"+pPoint.y);
          LoToPh(pPoint, lpFirst);
          coastPath.moveTo(lpFirst.x, lpFirst.y);
          //System.out.println("lpFirst.x " + lpFirst.x + " lpFirst.y" + lpFirst.y);
          //System.out.println("lineList.size() " + lineList.size() );
          for (int j = 0; j < lineList.size(); j++) {
            pPoint = (Point2D.Double) lineList.get(j);
            LoToPh(pPoint, lpSecond);
        coastPath.lineTo(lpSecond.x, lpSecond.y);
            System.out.println("lpSecond.x " + lpSecond.x + " lpSecond.y" + lpSecond.y);
          if (lpFirst.x == lpSecond.x && lpFirst.y == lpSecond.y) {
            coastPath.closePath();
          g2.draw(coastPath);
          g2.dispose();
        g.drawImage(img, 0, 0, null);
      public void LoToPh(Point2D.Double pp, Point lp) {
        //make some change
        double latitude = pp.x;
        int temp = (int) ( ( (latitude - m_nLXLeft) * (m_nXRight - m_nXLeft)) /
                          (m_nLXRight - m_nLXLeft));
        lp.x = temp + m_nXLeft;
        //System.out.println("lp.x"+lp.x);
        //make some change
        double longtitude = pp.y;
        temp = (int) ( ( (m_nLYTop - longtitude) * (m_nYBottom - m_nYTop)) /
                      (m_nLYTop - m_nLYBottom));
        lp.y = temp + m_nYTop;
    }

    Your IDE has an applet viewer that uses a JRE not available to the browser. If you're using MSIE, there's a built-in java 1.1 (yeah, one point one) runtime. You've just opened a real can of worms. See the article Launching Applets for an introduction.
    http://www.MartinRinehart.com

  • Errors running converted application (from applet)

    I've converted some codes (applet) into an application. When I run the application, I can see the GUI, but the application reports error as follows:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at swarmCanvas.paint(Swarm.java:192)
         at sun.awt.RepaintArea.paint(RepaintArea.java:298)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:196)
         at java.awt.Component.dispatchEventImpl(Component.java:2663)
         at java.awt.Component.dispatchEvent(Component.java:2497)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    What I see is only the GUI less the animation that occurs when it was an applet. Could anyone offer me any suggestions or help? Thanks a lot.

    Here's my codes, many thanks:
    * Swarm.class
    * This is the major class of the swarm animation. The Swarm class is
    * responsible for initialising and coordinating the Flock, swarmCanvas,
    * and swarmPanel classes.
    * @see Flock.class
    * @see Bird.class
    * @see Barrier.class
    * @author Duncan Crombie
    * @version 2.02, 20 September 1997
    import java.awt.*;
    public class Swarm extends java.applet.Applet implements Runnable {
    Thread animator; // animation thread
    swarmCanvas arena; // display canvas
    swarmPanel controls; // control panel
    static int NUMBLUE = 15, NUMRED = 5, MAXPOP = 20;
    static double SPEED = 5.0;
    static int TURN = 15, MINDIST = 30, MAXDIST = 60;
    boolean paused = false;
    public void init() { // initialise applet components
    arena = new swarmCanvas();
    controls = new swarmPanel(NUMBLUE, NUMRED, MAXPOP);
    setLayout(new BorderLayout());
    add("Center", arena); // add canvas to applet at 'Center'
    add("South", controls); // add panel to applet at 'South'
    arena.requestFocus();
    public void start() { // start thread when applet starts
    if (animator == null) {
    animator = new Thread(this);
    animator.start();
    public void stop() { // stop thread when applet stops
    if (animator != null) {
    animator.stop();
    animator = null;
    public void run() {
    boolean flocking = false;
    while (true) {
    if (!flocking && arena.unpacked) { // once canvas component is unpacked
    Bird.setBoundaries(arena.w, arena.h); // set swarm boundaries
    arena.flock = new Flock(NUMBLUE, NUMRED, SPEED, TURN, MINDIST, MAXDIST);
    flocking = true;
    } else if (flocking) {
    Bird.setBoundaries(arena.w, arena.h);
    if (!paused)
    arena.flock.move(); // animate the flock
    arena.repaint(); // update display
    try {
    Thread.sleep(20); // interval between steps
    } catch (InterruptedException e) {}
    public boolean handleEvent(Event ev) { // check for control panel actions
    if (ev.id == Event.ACTION_EVENT && ev.target == controls.reset) {
    resetApplet(); // reset button pressed in controls
    return true;
    if (ev.id == Event.ACTION_EVENT && ev.target == controls.pause) {
    paused = !paused; // toggle paused status
    controls.pause.setLabel((paused) ? "Continue" : "Pause");
    return true;
    if (ev.target == controls.sbRed) {
    if (ev.id == Event.SCROLL_LINE_UP)
    arena.flock.removeBird(Color.red); // remove a red Bird from flock
    else if (ev.id == Event.SCROLL_LINE_DOWN)
    arena.flock.addBird(new Bird(Color.red)); // add a red Bird
    return true;
    if (ev.target == controls.sbBlue) {
    if (ev.id == Event.SCROLL_LINE_UP)
    arena.flock.removeBird(Color.blue); // remove a blue Bird from flock
    else if (ev.id == Event.SCROLL_LINE_DOWN)
    arena.flock.addBird(new Bird(Color.blue)); // add a blue Bird
    return true;
    return super.handleEvent(ev); // pass on unprocessed events
    public boolean keyDown(Event e, int x) { // check for key press
    boolean shiftKeyDown = ((e.modifiers & Event.SHIFT_MASK) != 0);
    if (shiftKeyDown) {
    if (x == Event.DOWN) Flock.minDISTANCE -= 5; // less separation
    if (x == Event.UP) Flock.minDISTANCE += 5; // more separation
    if (x == Event.LEFT) Flock.maxDISTANCE -= 5; // lower detection
    if (x == Event.RIGHT) Flock.maxDISTANCE += 5; // higher detection
    Barrier.minRANGE = Flock.minDISTANCE;
    Barrier.maxRANGE = Flock.maxDISTANCE;
    } else {
    if (x == Event.DOWN) Bird.maxSPEED -= 1.0; // slower
    if (x == Event.UP) Bird.maxSPEED += 1.0; // faster
    if (x == Event.LEFT) Bird.maxTURN -= 5; // less turning
    if (x == Event.RIGHT) Bird.maxTURN += 5; // more turning
    return true; // all key events handled
    public void resetApplet() {
    arena.flock = new Flock(NUMBLUE, NUMRED, SPEED, TURN, MINDIST, MAXDIST);
    controls.sbBlue.setValue(NUMBLUE); // initialise scrollbars
    controls.sbRed.setValue(NUMRED);
    * swarmPanel.class
    * A Panel holding two scrollbars and two buttons for controlling the
    * Swarm applet.
    * @see Swarm.class
    * @author Duncan Crombie
    * @version 2.01, 20 September 1997
    class swarmPanel extends Panel { // class defines applet control panel
    Button reset, pause;
    Scrollbar sbBlue = new Scrollbar(Scrollbar.HORIZONTAL);
    Scrollbar sbRed = new Scrollbar(Scrollbar.HORIZONTAL);
    Label label1, label2;
    * The construction method creates and adds control panel components
    swarmPanel(int numRed, int numBlue, int maxBoid) {
    setLayout(new GridLayout(2, 3)); // define 2 x 3 grid layout for controls
    label1 = new Label("Blue #");
    label1.setFont(new Font("Dialog", Font.PLAIN, 12)); add(label1);
    label2 = new Label("Red #");
    label2.setFont(new Font("Dialog", Font.PLAIN, 12)); add(label2);
    reset = new Button("Reset"); add(reset);
    sbBlue.setValues(numRed, 1, 0, maxBoid);
    add(sbBlue);
    sbRed.setValues(numBlue, 1, 0, maxBoid);
    add(sbRed);
    pause = new Button("Pause");
    add(pause);
    * swarmCanvas.class
    * A Canvas for displaying the Flock and Swarm parameters.
    * @see Swarm.class
    * @author Duncan Crombie
    * @version 2.01, 20 September 1997
    class swarmCanvas extends Canvas {
    Flock flock;
    Image offScrImg;
    boolean unpacked = false;
    int w, h;
    /* Double buffered graphics */
    public void update(Graphics g) {
    if (offScrImg == null || offScrImg.getWidth(this) != w || offScrImg.getHeight(this) != h)
    offScrImg = createImage(w, h);
    Graphics og = offScrImg.getGraphics();
    paint(og);
    g.drawImage(offScrImg, 0, 0, this);
    og.dispose();
    public void paint(Graphics g) {
    Dimension d = this.preferredSize();
    if (!unpacked) {
    this.w = d.width;
    this.h = d.height;
    unpacked = true;
    g.setColor(Color.white);
    g.fillRect(0, 0, w, h); // draw white background
    g.setColor(Color.black); // set font and write applet parameters
    g.setFont(new Font("Dialog", Font.PLAIN, 10));
    g.drawString("Bird Speed: " + Bird.maxSPEED, 10, 15);
    g.drawString("Bird Turning: " + Bird.maxTURN, 10, 30);
    g.drawString("Minimum Distance: " + Flock.minDISTANCE, 10, 45);
    g.drawString("Maximum Distance: " + Flock.maxDISTANCE, 10, 60);
    flock.display(g); // draw Flock members
    if (this.w != d.width || this.h != d.height)
    unpacked = false;
    public boolean mouseDown(Event ev, int x, int y) {
    int radius = Barrier.maxRANGE;
    boolean top, bottom;
    flock.addBird(new Barrier(x, y)); // place Barrier at click coordinates
    top = (y < radius);
    bottom = (y > h-radius);
    if (x < radius) { // if left
    flock.addBird(new Barrier(w + x, y));
    if (top) flock.addBird(new Barrier(w + x, h + y));
    else if (bottom) flock.addBird(new Barrier(w + x, y - h));
    } else if (x > w-radius) { // if right
    flock.addBird(new Barrier(x - w, y));
    if (top) flock.addBird(new Barrier(x - w, h + y));
    else if (bottom) flock.addBird(new Barrier(x - w, y - h));
    if (top) flock.addBird(new Barrier(x, h + y));
    else if (bottom) flock.addBird(new Barrier(x, y - h));
    return true;
    ===================================================================
    * Bird.class
    * This class defines the appearance and behaviour of a Bird object.
    * @see Swarm.class
    * @see Flock.class
    * @see Barrier.class
    * @author Duncan Crombie
    * @version 2.02, 21 September 1997
    import java.awt.*;
    class Bird {
    int iX, iY, iTheta;
    Color cFeathers;
    static int arenaWIDTH, arenaHEIGHT; // canvas dimensions
    static double maxSPEED; // speed of Bird
    static int maxTURN; // maximum turn in degrees
    Bird(int x, int y, int theta, Color feath) {
    iX = x;
    iY = y;
    iTheta = theta;
    cFeathers = feath;
    Bird(Color feath) {
    this((int)(Math.random() * arenaWIDTH),
    (int)(Math.random() * arenaHEIGHT),
    (int)(Math.random() * 360),
    feath);
    public void move(int iHeading) {
    int iChange = 0;
    int left = (iHeading - iTheta + 360) % 360;
    int right = (iTheta - iHeading + 360) % 360;
    if (left < right)
    iChange = Math.min(maxTURN, left);
    else
    iChange = -Math.min(maxTURN, right);
    iTheta = (iTheta + iChange + 360) % 360;
    iX += (int)(maxSPEED * Math.cos(iTheta * Math.PI/180)) + arenaWIDTH;
    iX %= arenaWIDTH;
    iY -= (int)(maxSPEED * Math.sin(iTheta * Math.PI/180)) - arenaHEIGHT;
    iY %= arenaHEIGHT;
    public void display(Graphics g) { // draw Bird as a filled arc
    g.setColor(this.cFeathers);
    g.fillArc(iX - 12, iY - 12, 24, 24, iTheta + 180 - 15, 30);
    public int getDistance(Bird bOther) {
    int dX = bOther.getPosition().x-iX;
    int dY = bOther.getPosition().y-iY;
    return (int)Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
    static void setBoundaries(int w, int h) {
    arenaWIDTH = w;
    arenaHEIGHT = h;
    public int getTheta() {
    return iTheta;
    public Point getPosition() {
    return new Point(iX, iY);
    public Color getFeathers() {
    return cFeathers;
    =================================================================
    * Flock.class
    * This class creates and coordinates the movement of a flock of Birds.
    * @see Swarm.class
    * @see Bird.class
    * @see Barrier.class
    * @author Duncan Crombie
    * @version 2.02, 21 September 1997
    import java.util.Vector;
    import java.awt.*;
    class Flock { // implement swarming algorithm on flock of birds
    private Vector vBirds;
    static int minDISTANCE, maxDISTANCE;
    Flock(int nBlue, int nRed, double speed, int turn, int minDist, int maxDist) {
    vBirds = new Vector(5, 5);
    for (int i=0; i < nBlue + nRed; i++)
    addBird(new Bird((i < nBlue) ? Color.blue : Color.red));
    Bird.maxSPEED = speed;
    Bird.maxTURN = turn;
    Barrier.minRANGE = minDISTANCE = minDist;
    Barrier.maxRANGE = maxDISTANCE = maxDist;
    public void addBird(Bird bird) { // add Bird to vector
    vBirds.addElement(bird);
    synchronized void removeBird(Color col) { // remove Bird from vector
    for (int i=0; i < vBirds.size(); i++) { // loop through vector of Birds
    Bird bTemp = (Bird)vBirds.elementAt(i);
    if (bTemp.getFeathers() == col) { // search for Bird of given colour
    vBirds.removeElementAt(i); // if found, remove Bird..
    break; // ..and stop searching
    * The move function simply tells each Bird in the Vector vBirds to move
    * according to the resultant Point of generalHeading.
    synchronized public void move() {
    for (int i=0; i < vBirds.size(); i++) {
    Bird bTemp = (Bird)vBirds.elementAt(i);
    bTemp.move(generalHeading(bTemp));
    * The display function simply draws each Bird in the Vector vBirds at its
    * current position.
    public void display(Graphics g) { // display each Bird in flock
    for (int i=0; i < vBirds.size(); i++) {
    Bird bTemp = (Bird)vBirds.elementAt(i);
    bTemp.display(g);
    public Point sumPoints(Point p1, double w1, Point p2, double w2) {
    return new Point((int)(w1*p1.x + w2*p2.x), (int)(w1*p1.y + w2*p2.y));
    public double sizeOfPoint(Point p) {
    return Math.sqrt(Math.pow(p.x, 2) + Math.pow(p.y, 2));
    public Point normalisePoint(Point p, double n) {
    if (sizeOfPoint(p) == 0.0) return p;
    else {
    double weight = n / sizeOfPoint(p);
    return new Point((int)(p.x * weight), (int)(p.y * weight));
    * The generalHeading function determines the point a Bird will turn towards
    * in the next timestep. The Bird b checks for all Birds (other than self)
    * that fall within the detection range. If the Bird is of a different colour
    * or closer than the separation distance then they are repulsed else the
    * Birds are attracted according to the flocking algorithm.
    private int generalHeading(Bird b) {
    if (b instanceof Barrier) return 0;
    Point pTarget = new Point(0, 0);
    int numBirds = 0; // total of Birds to average
    for (int i=0; i < vBirds.size(); i++) { // for each Bird in array
    Bird bTemp = (Bird)vBirds.elementAt(i); // retrieve element i
    int distance = b.getDistance(bTemp); // get distance to Bird
    if (!b.equals(bTemp) && distance > 0 && distance <= maxDISTANCE) {
    * If the neighbour is a sibling the algorithm tells the boid to align its
    * direction with the other Bird. If the distance between them differs from
    * minDISTANCE then a weighted forces is applied to move it towards that
    * distance. This force is stronger when the boids are very close or towards
    * the limit of detection.
    if (b.getFeathers().equals(bTemp.getFeathers())) { // if same colour
    Point pAlign = new Point((int)(100 * Math.cos(bTemp.getTheta() * Math.PI/180)), (int)(-100 * Math.sin(bTemp.getTheta() * Math.PI/180)));
    pAlign = normalisePoint(pAlign, 100); // alignment weight is 100
    boolean tooClose = (distance < minDISTANCE);
    double weight = 200.0;
    if (tooClose) weight *= Math.pow(1 - (double)distance/minDISTANCE, 2);
    else weight *= - Math.pow((double)(distance-minDISTANCE) / (maxDISTANCE-minDISTANCE), 2);
    Point pAttract = sumPoints(bTemp.getPosition(), -1.0, b.getPosition(), 1.0);
    pAttract = normalisePoint(pAttract, weight); // weight is variable
    Point pDist = sumPoints(pAlign, 1.0, pAttract, 1.0);
    pDist = normalisePoint(pDist, 100); // final weight is 100
    pTarget = sumPoints(pTarget, 1.0, pDist, 1.0);
    * In repulsion the target point moves away from the other Bird with a force
    * that is weighted according to a distance squared rule.
    else { // repulsion
    Point pDist = sumPoints(b.getPosition(), 1.0, bTemp.getPosition(), -1.0);
    pDist = normalisePoint(pDist, 1000);
    double weight = Math.pow((1 - (double)distance/maxDISTANCE), 2);
    pTarget = sumPoints(pTarget, 1.0, pDist, weight); // weight is variable
    numBirds++;
    if (numBirds == 0) return b.getTheta();
    else // average target points and add to position
    pTarget = sumPoints(b.getPosition(), 1.0, pTarget, 1/(double)numBirds);
    int targetTheta = (int)(180/Math.PI * Math.atan2(b.getPosition().y - pTarget.y, pTarget.x - b.getPosition().x));
    return (targetTheta + 360) % 360; // angle for Bird to steer towards
    ======================================================================
    * Barrier.class
    * This class creates and coordinates the movement of a flock of Birds.
    * @see Swarm.class
    * @see Flock.class
    * @see Bird.class
    * @author Duncan Crombie
    * @version 2.01, 21 September 1997
    import java.awt.*;
    class Barrier extends Bird {
    static int minRANGE, maxRANGE;
    Barrier(int x, int y) {
    super(x, y, 0, Color.black); // position Barrier and define color as black
    public void move(int dummy) {
    // do nothing
    public void display(Graphics g) { // paint Barrier
    g.setColor(Color.black);
    g.fillOval(this.iX-5, this.iY-5, 10, 10);
    g.setColor(Color.gray); // paint separation circle
    g.drawOval(this.iX-minRANGE, this.iY-minRANGE, 2*minRANGE, 2*minRANGE);
    g.setColor(Color.lightGray); // paint detection circle
    g.drawOval(this.iX-maxRANGE, this.iY-maxRANGE, 2*maxRANGE, 2*maxRANGE);
    =====================================================================
    import java.awt.*;
    import java.awt.event.*;
    public class SwarmFrame extends Frame implements ActionListener {
    public SwarmFrame() {
    super("Flocking Bird");
    MenuBar mb = new MenuBar();
    setMenuBar(mb);
    Menu fileMenu = new Menu("File");
    mb.add(fileMenu);
    MenuItem exitMenuItem = new MenuItem("Exit");
    fileMenu.add(exitMenuItem);
    exitMenuItem.addActionListener(this);
    Swarm swarmApplet = new Swarm();
    add(swarmApplet, BorderLayout.CENTER);
    swarmApplet.init();
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() instanceof MenuItem) {
    String menuLabel = ((MenuItem) evt.getSource()).getLabel();
    if(menuLabel.equals("Exit")) {
    dispose();
    System.exit(0);
    =====================================================================
    import java.awt.*;
    public class SwarmApplication {
    public static void main(String[] args) {
    Frame frame = new SwarmFrame();
    frame.setBounds(10, 10, 600, 400);
    frame.setVisible(true);

  • How do i add a frame to an applet?

    This is the code i was doing during my java class ( skiping ahead a bit):
    package September;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Banner extends JApplet
      implements ActionListener
      private int xPos, yPos,xPos2, yPos2, xPos3, yPos3;
      public JButton b1;
      public JLabel label;
      public BannerFrame frame = new BannerFrame();
       *  Called automatically when the applet is initialized
      public void init()
        Container c = getContentPane();
        c.setBackground(Color.white);
        xPos = c.getWidth();
        yPos = c.getHeight() / 2;
        xPos2 = c.getWidth();
        yPos2 = c.getHeight();
        xPos3 = 0;
        yPos3 = 0;
        JLabel label = new JLabel("This is a label");
        b1 = new JButton("Stop String");  // haven't gotten to get the button to do stuff yet but will in future
        b1.addActionListener(this); // again will do something in the future
        c.add(b1,BorderLayout.SOUTH);
        c.add(label,BorderLayout.NORTH);
        Timer clock = new Timer(30, this);  // Fires every 30 milliseconds
        clock.start();
       *  Called automatically after a repaint request
      public void paint(Graphics g)
        super.paint(g);
        Container c = getContentPane();
    //    g.setColor(Color.green);
    //    g.fillRect(0,0,c.getWidth(),c.getHeight()); // i put this in BannerFrame
        c.add(frame);
        g.setColor(Color.BLACK);
        g.fillRect(xPos3,yPos3,10,10);
        g.drawString("This String goes up and down", 0,yPos2 + 10);
        g.drawString("String:"+ yPos2,0,10);
        g.drawString("PaneHeight: "+c.getHeight(),60,10);
        g.drawString("PaneWidth:" + c.getWidth(), 60, 25);
       *  Called automatically when the timer fires
      public void actionPerformed(ActionEvent e)
    //       JButton button = (JButton)e.getSource();
    //       if(button == b1){
        Container c = getContentPane();
        xPos--;
        yPos2++;
        xPos3++;
        yPos3++;
        if (xPos < -100) // if off screen
          xPos = c.getWidth();
        if (yPos2 > 200){
         // if off screen
          yPos2 = 0;
        if(yPos3 > 200 && yPos3 > 100){
         // if off screen
             yPos3=0;
             xPos3=0;
        yPos = c.getHeight() / 2;
        //xPos2 = c.getWidth();
        repaint();
    }I tried to put the "g.drawRect()" function in the paint method of the applet but it looks really messy (repaints to fast -> looks like its blinking on the screen). I tried to put it in a diffrent class so it wouldn't look this way but the class that i made doesn't work in the applet
    BTW, here the code for BannerFrame:
    package September;
    import javax.swing.*;
    import java.awt.*;
    * @author student
    public class BannerFrame extends JFrame{
         public int height = this.getContentPane().getHeight(), width = this.getContentPane().getWidth();
         public BannerFrame(){
              Container c = getContentPane();
              c.setBackground(Color.green);
         public void paint(Graphics g){
              g.drawRect(0,0,width,height);
    }

    Some might want to figure out from your code what you want to do and what the problem is, but I would prefer an explaination to go along with the code, if you would please.

Maybe you are looking for

  • Not able to Send HTML Content in Apex Mail

    Hi, I am using Oracle Apex 4.2 and Oracle 11g XE I am trying to add HTML content in the apex_send mail procedure. But it give me the below error. >>•ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275 Below is the code

  • Java 7

    iMac 21.5 inch, Mid 2011 Software: Mac OSX Lion 10.7.5 (11G63) Safari: Version 6.1.6 (7537.78.2) Processor: 2.5 GHz Intel Core i5 Memory: 4GB 1333 MHz DDR3 Graphics: AMD Radeon HD 6750M 512 MB Should I keep the following plug-ins on my Mac? Are they

  • I purchased an upgrade to my one note app.  How can I get that to transfer to my new iPad?

    I purchased an upgrade for my OneNote app, how do I get that to transfer to my new iPad?   I downloaded the app but the upgrade is not loaded on this new iPad.

  • Remote SCCM Console

    Hi, I have my SCCM console the other side of a firewall (hardware). I can telnet to port 135 from the server to the SCCM server (single server with provider, SQL and site) and yes the console and WBEMTEST will not connect. Are there opther port or ot

  • Validate profit center in complete Project Structure

    Hi PS gurus, I want to validate profit center in (complete Project Structure) Project definition, WBS elements, N/W Header and N/W Activities. •     Presently in the WBS Element there is a possibility to check (Project definition and WBS elements) PR