Problems changing colour using Graphics class in java.awt

Hi,
The problem only happens when more than two images are on a panel. In this case, I have to strings that are drawn. The first drawn string is called "A" the second drawn string is called "B". However, when i change the colour of "B" to let's say Red, the panel erases the letter "B" and insteads changes "A" to red. How can I fix this so that when the user chooses the colour red it changes the colour of the latest drawn string and not the first one. please help!!!!
import java.awt.*;
public class StringPanel extends GBPanel
     private String shape = "clear", str;
     private int x, y;
     private Color color = Color.black;
     public void paintComponent(Graphics g)
          super.paintComponent(g);
          g.setColor (color);
          if(shape.equalsIgnoreCase("draw string"))
               g.setColor(color);
               g.drawString(str, x, y);
          else if (shape.equalsIgnoreCase("exit"))
               System.exit(0);
     public void drawCurve(Color color)
     this.color = color;
     repaint();
     public void drawString(String shape, String str, int x, int y)
          this.shape = shape;
          this.str = str;
          this.x = x;
          this.y = y;
          repaint();
     public void drawString1(String shape, String str, int x, int y)
          Graphics g = getGraphics();
          g.setColor(color);
          if (shape.equalsIgnoreCase("draw string"))
               g.setColor(color);
               g.drawString(str, x, y);
          else
               repaint();
}

well, as I said, I can't remember what the update method thing was for... I think it was related to not clearing the screen first.
Anyway, if you maintain a list of objects that should be drawn and then in the paintComponent method, loop thru the list of objects and redraw them, it will work. Then you change the state of an object and call repaint. When you are going to change color, you need to, in effect, redraw the entire affected area. Now this can be done partially with clipping, but it's complicated to deal with that. So the simplest way is just redraw everything on repaint.

Similar Messages

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Most commenly used abstract class in java.

    hi all,
    can anyone please tell me, what is most commonly used abstract class in java. this question was asked in interview.

    I hate interviewers when they ask about specifics of some classes.The fact that you hate it doesn't automatically follow that it's a bad question from the perspective of the person conducting the interviewer. You don't know what the real question is.
    Bad "real" question: Do you know the statistics of Java usage off the top of your head?
    Good "real" question: Do you know that Object isn't Abstract and can you name a few Abstract classes off the cuff?
    Even then Programmers are so literal minded - the real question may be "Talk about what you know a bit."

  • Changes to using graphic settings in Bridge CS6 scripts

    The "CS6 Tools Guide" document shows no changes in how graphical settings should be used for Foreground Colour, Background Colour, Fonts and Font Size, as well as the use of Images in panels.  All these work as before with scripts used in Photoshop CS6.  But with Bridge CS6 the use of an image will crash Bridge, whereas the settings for Colours and Fonts are just ignored.  Does Bridge CS6 now have customised settings for graphical changes to panels?  Or is this a bug?

    I'd much rather have 32 bits that do what they ought to… sounds like CS6 has 48 that don't…

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

  • Help!!! JavaFX problem changing video using MediaPlayer Object

    Hello,
    I hope you can help me. I'm creating a player that constantly displays a playlist of videos. After some time the system seems to go in deadlock changing video. The problem I have encountered is with the release of JavaFX 1.2, JavaFX 1.3 and JavaFX 1.3.1. The code I used is as follows:
    package fx.classes;
    import javafx.scene.Scene;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaView;
    import javafx.scene.media.MediaError;
    import javafx.stage.Stage;
    import java.lang.System;
    import java.lang.Thread;
    import javafx.scene.control.Button;
    import javafx.scene.control.Tooltip;
    var source = "C:/Progetti/OBA/workspaces/apps/Dove6FXVideo/res/video/content/cartoon.mp4";
    var source2 = "C:/Progetti/OBA/workspaces/apps/Dove6FXVideo/res/video/content/spot30.mp4";
    //var source = "C:/Movie/test/test1.avi";
    //var source2 = "C:/Movie/test/test2.avi";
    var i = 0;
    public class MP extends Scene {
    var md: Media = Media {
    source: source
    onError:
    function (e: MediaError) {
    println("got a MediaPlayer error : {e.cause} {e}");
    mediaPlayer.media = null;
    var mediaPlayer: MediaPlayer = MediaPlayer {
    //autoPlay: true
    //repeatCount: MediaPlayer.REPEAT_FOREVER;
    startTime: 100s
    onEndOfMedia: function() {
    changeMovie()
    onError: function(me : MediaError) {
    if (mediaPlayer.status == MediaPlayer.PAUSED) {
    println("Stato: pausa");
    mediaPlayer.stop();
    else {
    print(mediaPlayer.status);
    println("Stato: ");
    onStalled: function(du : Duration) {
    print( mediaPlayer.status );
    media: md
    override var content = [
    MediaView {
    //x: 10
    //y: 10
    //fitWidth: 400
    //fitHeight: 300
    //fitHeight: bind height
    //fitWidth: bind width
    preserveRatio: true
    mediaPlayer: bind mediaPlayer
    function play() {
    mediaPlayer.play();
    function stop() {
    mediaPlayer.stop();
    function pause() {
    mediaPlayer.pause();
    function printStatus() {
    print( mediaPlayer.status );
    protected function changeMovie() : Void {
    mediaPlayer.stop();
    var ss = source;
    if ((i mod 2) != 0) {
    ss = source2;
    md = Media {
    source: ss
    onError:
    function (e: MediaError) {
    println("got a MediaPlayer error : {e.cause} {e}");
    mediaPlayer.media = null;
    mediaPlayer.media = md;
    mediaPlayer.play();
    i = i + 1;
    var sample: MP = MP {
    public function run( args: String[] ) {
    var stage:Stage = Stage {
    //title: bind "CutePlayer 3: {cutePlayer.myPlayer.media.source}"
    title: bind "Media Player: Big Back Bunny"
    width: 1024
    height: 600
    scene: bind sample
    sample.printStatus();
    sample.play();
    The same problem seems to be also using the project Mediabox (between JavaFX demo). Does anyone know how you can solve the problem?
    Thank you in advanced,
    Domenico

    Hello,
    I hope you can help me. I'm creating a player that constantly displays a playlist of videos. After some time the system seems to go in deadlock changing video. The problem I have encountered is with the release of JavaFX 1.2, JavaFX 1.3 and JavaFX 1.3.1. The code I used is as follows:
    package fx.classes;
    import javafx.scene.Scene;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaView;
    import javafx.scene.media.MediaError;
    import javafx.stage.Stage;
    import java.lang.System;
    import java.lang.Thread;
    import javafx.scene.control.Button;
    import javafx.scene.control.Tooltip;
    var source = "C:/Progetti/OBA/workspaces/apps/Dove6FXVideo/res/video/content/cartoon.mp4";
    var source2 = "C:/Progetti/OBA/workspaces/apps/Dove6FXVideo/res/video/content/spot30.mp4";
    //var source = "C:/Movie/test/test1.avi";
    //var source2 = "C:/Movie/test/test2.avi";
    var i = 0;
    public class MP extends Scene {
    var md: Media = Media {
    source: source
    onError:
    function (e: MediaError) {
    println("got a MediaPlayer error : {e.cause} {e}");
    mediaPlayer.media = null;
    var mediaPlayer: MediaPlayer = MediaPlayer {
    //autoPlay: true
    //repeatCount: MediaPlayer.REPEAT_FOREVER;
    startTime: 100s
    onEndOfMedia: function() {
    changeMovie()
    onError: function(me : MediaError) {
    if (mediaPlayer.status == MediaPlayer.PAUSED) {
    println("Stato: pausa");
    mediaPlayer.stop();
    else {
    print(mediaPlayer.status);
    println("Stato: ");
    onStalled: function(du : Duration) {
    print( mediaPlayer.status );
    media: md
    override var content = [
    MediaView {
    //x: 10
    //y: 10
    //fitWidth: 400
    //fitHeight: 300
    //fitHeight: bind height
    //fitWidth: bind width
    preserveRatio: true
    mediaPlayer: bind mediaPlayer
    function play() {
    mediaPlayer.play();
    function stop() {
    mediaPlayer.stop();
    function pause() {
    mediaPlayer.pause();
    function printStatus() {
    print( mediaPlayer.status );
    protected function changeMovie() : Void {
    mediaPlayer.stop();
    var ss = source;
    if ((i mod 2) != 0) {
    ss = source2;
    md = Media {
    source: ss
    onError:
    function (e: MediaError) {
    println("got a MediaPlayer error : {e.cause} {e}");
    mediaPlayer.media = null;
    mediaPlayer.media = md;
    mediaPlayer.play();
    i = i + 1;
    var sample: MP = MP {
    public function run( args: String[] ) {
    var stage:Stage = Stage {
    //title: bind "CutePlayer 3: {cutePlayer.myPlayer.media.source}"
    title: bind "Media Player: Big Back Bunny"
    width: 1024
    height: 600
    scene: bind sample
    sample.printStatus();
    sample.play();
    The same problem seems to be also using the project Mediabox (between JavaFX demo). Does anyone know how you can solve the problem?
    Thank you in advanced,
    Domenico

  • Problem with colour used in plot legend

    Hi I have problem setting the colour for lines at Plot 0 and 15
    Here's attached. I am using LV 7.1 Not sure if it carries bug
    regards
    Clement
    Attachments:
    plotlegend.vi ‏27 KB

    Hi Clement,
    Did this occur after you had been using the plot and changing properties programatically?  Do you have ideas on how you arrived at this?  It looks like all the plot properties are set up the same.
    Regards,
    Clint M
    National Instruments

  • Problem changing permission using EAC (time-consuming error)

    Hello,
    i tried to change the PF permission tree using EAC and selecting "Apply changes to this public folder and all its subfolders." The process stuck at around 80%, and now if i try to change permission on every PF i have the following error:
    The operation can't be performed because you're running another time-consuming operation. Try again when it completes.
    I can manage the permission using EMS, but i'd like to solve that problem.
    Thanks for help!

    At the end i recycled the iis worker process related to EAC.
    Now i can change again PF permissions, but just one by one...

  • Using C++ classes in Java

    I need links, ebooks or other resources of using C++ in Java using JNI.
    regards!

    Yes! I have understand it.
    Now I am reached to this link http://www.javaworld.com/javaworld/javatips/jw-javatip17.html?page=2
    void NumberListProxy_initCppSide(struct HNumberListProxy* Obj);
    the method signature is different from the one that is generated here at my machine by java which is:
    JNIEXPORT void JNICALL Java_NumberListProxy_initCppSide
    (JNIEnv *, jobject);
    Also when I run the command ' javah stubs NumberListProxy '
    Error: JNI does not require stubs, please refer to the JNI documentation.
    I think u ( bschauwejava ) can tell me about this problem.

  • Problem changing colour on standard template

    I'm really new to Motion, so please don't get to advanced!
    I'm using the satin template for titles, the standard colour is blue, but I want it to be red/dark red. How do I do this as easy as possible?
    Thanks!

    It's actually a photographed bit of media, so there's no "color" box. However, you can add an HSV filter and adjust the hue...
    post back,
    Patrick

  • If Statement in java.awt paint

    import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
    if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
    And then if wt is greater than max then it will say "Your overweight".
    But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
    Help much appreciated,
    Simon

    Thanks very much that works well.
    Simon
    My code now looks like this: import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void you(Graphics g)
      String statement;
      if(wt > max) statement="You are very fat";
      else if(wt < min) statement="You are very thin";
      else statement="You are in the recommended weight range for your height";
      g.drawString(statement, 20,210);
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        you(g);
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of BmiThanks again,
    Simon

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Return an Image from a subclass to a graphics class

    Hello
    I'm wondering how to return an Image generated by one class to a class which works as a graphics class. The graphics class is run from a main class. Let me make up a schedule:
    Image-generator return Image -> graphics class paint
    I have tried just making an Image and using the getGraphics to connect a graphics object to it, but it doesn't seem to work.
    Thanks in advance

    Okay, here are the pieces of code we use. (Comments are in Swedish but they are barely relevant, and explain merely basically what is happening in the program)
    The applet is compilable, but there is a nullpointerexception in Elefanträknaren, at getGraphics(). Believe me, I have tried finding the solution to this already.
    Spelet (main method)
    import java.applet.*;
    import java.awt.*;
    public class Spelet extends Applet
         /*Elefanträknaren testerna;*/
         Ritaren ritarN;
         Graphics g;
         public void init()
              /*testerna = new Elefanträknaren();*/
              ritarN = new Ritaren(g, getSize().width, getSize().height);
              setLayout(new GridLayout(1, 1));
              add(ritarN);
         public void start()
              ritarN.startaTråd();
         public void stop()
              ritarN.stoppaTråd();
         public void update(Graphics g)
              paint(g);
    }Ritaren (graphics object)
    import java.awt.*;
    public class Ritaren extends Panel implements Runnable
         Elefanträknaren e;
         Graphics g;
         int bredd, höjd;
         //Trådobjekt
         Thread tråd;
         public Ritaren(Graphics g, int bredd, int höjd)
              this.bredd = bredd;
              this.höjd = höjd;
              e = new Elefanträknaren(bredd, höjd);
         public void startaTråd()
              if( tråd == null )
                   tråd = new Thread(this); //Skapa tråden
                   tråd.start(); //Kör igång
                   e.startaTråd();
         public void stoppaTråd()
              if( tråd != null )
                   tråd.interrupt();
                   tråd = null;
         public void paint(Graphics g)
              g.drawImage(e.getSpökbilden(), 0, 0, this);
         public void update(Graphics g)
              paint(g);
         public void run()
              while( tråd != null )
                   repaint();
                   try
                        Thread.sleep(33);
                   catch(Exception e){}
    }Elefanträknaren (class generating the Image)
    import java.awt.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    public class Elefanträknaren extends Panel implements Runnable
         //Vektorn som innehåller alla Elefant-klasser
         private Vector elefanterna;
         //Ritobjektet för den dubbelbuffrade bilden
         private Graphics gx;
         //Bildobjektet för dubbelbuffringen
         private Image spökbilden;
         private int bredd, höjd;
         //Trådvariabeln
         private Thread tråd;
         //Rörelsen uppdateras 30 ggr/s. RÄKNARE håller koll på när en elefant ska läggas till (efter 30 st 30-delar = 1 ggr/s)
         int RÄKNARE = 30;
         int ÄNDRING = RÄKNARE;
         //DELAY betecknar delayen mellan två bilder/frames. 33 ms delay = 30 FPS
         int DELAY = 33;
         //Konstruktor
         public Elefanträknaren(int bredd, int höjd)
              elefanterna = new Vector();
              this.bredd = bredd;
              this.höjd = höjd;
         //Kör igång tråden/ge elefanterna liv
         public void startaTråd()
              if( tråd == null )
                   tråd = new Thread(this); //Skapa tråden
                   tråd.start(); //Kör igång
                   //Dubbelbuffringen initieras - detta måste ligga i startaTråd()
                   //spökbilden = new BufferedImage(bredd, höjd, BufferedImage.TYPE_INT_ARGB);
                   spökbilden = createImage(bredd, höjd);
                   gx = spökbilden.getGraphics();
         //Stoppa tråden/döda elefanterna
         public void stoppaTråd()
              if( tråd != null )
                   tråd.interrupt();
                   tråd = null;
         //Lägg till en elefant i vektorn
         private void läggTillElefant(Elefant e)
              elefanterna.add(e); //Lägg till en Elefant som objekt i vektorn
              Elefant temp = (Elefant)     elefanterna.get(elefanterna.size()-1);
              temp.startaTråd(); //Starta Elefantens tråd - ge Elefanten liv
         //Sätter ihop bilden som ska sickas till Ritaren
         public void uppdaterarN()
              //Rensa skärmen från den förra bilden
              gx.fillRect(0, 0, bredd, höjd);
              for( int i = 0; i < elefanterna.size(); i++ )
                   Elefant temp = (Elefant) elefanterna.get(i);
                   gx.drawImage(temp.getBild(), temp.getX(), temp.getY(), null);
         public Image getSpökbilden()
              return spökbilden;
         //Tråd-loopen
         public void run()
              while( tråd != null )
                   RÄKNARE++;
                   if( RÄKNARE >= ÄNDRING )
                        läggTillElefant(new Elefant(11, 50, 900));
                        RÄKNARE = 0;
                   uppdaterarN();
                   //repaint();
                   try
                        Thread.sleep(DELAY);
                   catch(Exception e){}
    }Elefant (a class which Elefanträknaren turns into an Image:
    import java.awt.*;
    import java.util.*;
    import javax.swing.ImageIcon;
    public class Elefant extends Panel implements Runnable
         private int x, y; //Elefantens koordinater
         private int hälsa; //Elefantens hälsa
         private int RÖRELSESTEG = 10;//Antal pixlar elefanten ska röra sig i sidled
         private int DELAY;
         //Animation
         private Vector bilderna = new Vector();
         private Vector bilderna2 = new Vector();
         private int fas; //Delen av animationen som ska visas
         private boolean framåt;
         //Tråddelen
         private Thread tråd;
         public Elefant(int x, int y, int hastighet)
              this.x = x;
              this.y = y;
              DELAY = 1000 - hastighet;
              hälsa = 100;
              framåt = true;
              fas = 0; //Nollställ fasen
              //Få fram bildernas namn
              for( int i = 0; i <= 5; i++ )
                   Image temp = new ImageIcon("Z:\\Projektet\\gamal\\Projektet\\Mappen\\mediat\\png\\jumbo" + i + ".png").getImage();
                   bilderna.add(temp);
                   Image temp2 = new ImageIcon("Z:\\Projektet\\gamal\\Projektet\\Mappen\\mediat\\png\\jumbo" + i + "r.png").getImage();
                   bilderna2.add(temp2);
         //get-variabler
         public int getX() { return x; }
         public int getY() { return y; }
         //Kör igång tråden/ge elefanten liv
         public void startaTråd()
              if( tråd == null )
                   tråd = new Thread(this); //Skapa tråden
                   tråd.start(); //Kör igång
         //Rör elefanten i sidled
         private void rörelse()
              //Animering
              if( fas < 5 ) fas++;
              else     fas = 0;
              //Flytta ner elefanten när den når en av spelets kanter
              if( x >= 800 || x <= 10 ) y += 85;
              //Kontrollera riktning
              if( x >= 800 ) framåt = false;
              else if( x <= 10 ) framåt = true;
              //Positionering
              if( framåt ) x += RÖRELSESTEG;
              else x -= RÖRELSESTEG;
         //Hämtar den aktuella bilden, och returnerar den
         public Image getBild()
              Image temp;
              if( framåt ) temp = (Image) bilderna.get(fas);
              else temp = (Image) bilderna2.get(fas);
              return temp;
         /* Tråd-hantering */
         //Stoppa tråden/döda elefanten
         public void stoppaTråd()
              if( tråd != null )
                   tråd.interrupt();
                   tråd = null;
         //Körs när elefanten är vid liv
         public void run()
              while( tråd != null )
                   rörelse();
                   try
                        Thread.sleep(DELAY);
                   catch(Exception e){}
    }

  • Problem with running the midlet class (Error with Installation suite )

    hi everyone...
    i have problem with running the midlet class(BluetoothChatMIDlet.java)
    it keep showing me the same kind of error in the output pane of netbeans...
    which is:
    Installing suite from: http://127.0.0.1:49296/Chat.jad
    [WARN] [rms     ] javacall_file_open: wopen failed for: C:\Users\user\javame-sdk\3.0\work\0\appdb\delete_notify.dat
    i also did some research on this but due to lack of forum that discussing about this,im end up no where..
    from my research i also find out that some of the developer make a changes in class properties..
    where they check the SIGN DISTRIBUTION...and also change the ALIAS to UNTRUSTED..after that,click the EXPORT KEY INTO JAVA ME SDK,PLATFORM,EMULATOR...
    i did that but also didnt work out..
    could any1 teach me how to fix it...
    thanx in advance... :)

    actually, i do my FYP on bluetooth chatting...
    and there will be more than two emulators running at the same time..
    one of my frens said that if u want to run more than one emulator u just simply click on run button..
    and it will appear on the screen..

  • Graphics class questions

    Hey,
    I have two questions about drawing shapes in action script 3.0, using graphics class (flash.display.Graphics):
    Question 1.
    When I draw some more complicated shape consisted of a few simpler shapes (i.e. two circles), and the shapes overlaps, the overlapped region is inverted (is rendered as a "hole"). Is there any way to avoid that?
    This is simple example of this behaviour:
    var oClip : MovieClip = new MovieClip();
    oClip.graphics.beginFill( 0x000000, 0.5 );
    oClip.graphics.drawCircle( 150, 200, 70 );
    oClip.graphics.drawCircle( 250, 200, 100 );
    oClip.graphics.endFill();
    this.addChild( oClip );
    I know,I can do it using separate beginFill/endFill sections for each circle:
    var oClip : MovieClip = new MovieClip();
    oClip.graphics.beginFill( 0x000000, 0.5 );
    oClip.graphics.drawCircle( 150, 200, 70 );
    oClip.graphics.endFill();
    oClip.graphics.beginFill( 0x000000, 0.5 );
    oClip.graphics.drawCircle( 250, 200, 100 );
    oClip.graphics.endFill();
    this.addChild( oClip );
    but then when I use alpha blending, the shapes are blended separatelly. Unfortunatelly, this is not correct for that what I want to do.
    I need to draw one beginFill/endFill session but without "holes" in the final shape, is it possible?
    Question 2.
    Is there an action script counterpart of the Flash menu option: Modify->Break Apart ?
    Many thanks for any help.

    I don't think there is going to be any easy way to do this. But you might want to look at the drawPath command. It allows you to set the winding-rule for the drawn shape and may help.
    Notice the star in the example code goes from filled to not filled and it doesn't show overlap either....

Maybe you are looking for