Paint, buffer,update

What are the paint, buffer and update needed for? When Should I use them. I have the following code and am trying to paint to an applet but cannot see anything in my applet please help me understand what I should be using and why.
first file:
package Exercise4.Exercise4a;
import java.awt.*;
public class Exercise4a extends java.applet.Applet {
    Graphics b;
    public void init()
        b = this.getGraphics();
        Point a = new Point(0,0);
        Door door1 = new Door(a);
        door1.paint (b);
        Point c = new Point(20,0);
        Door door2 = new Door(c);
        door2.paint(b);
        //System.out.println(door2.x);
        //System.out.println(door2.y);
}secondfile:
public class Door extends java.applet.Applet {
/** Creates a new instance of Door */
    int x;
    int y;
    public void init()
    public Door()
    x = 0;
    y = 0;
    public Door(Point aPoint)
    this.x = (int)aPoint.getX();
    this.y = (int)aPoint.getY();
    public void paint(Graphics graphics)
    graphics.drawRect(0 + this.x ,0 + y, 20,30);
    graphics.setColor(Color.black);
    graphics.fillOval(15 + x,15 + y ,5,5);
}If i just use my door.class file my applet loads fine but if I use my Exercise4a.class to load the graphics it will not how come?
Thanks for your help,
Paul

Probably becuase your graphics context is not get created until after init() is done and paint() is called for the first time. Try using that getGraphics() thing to draw something, I bet you get a null pointer, if not then just remember: Applets are wierd (free hint: don't use them!)

Similar Messages

  • Graphics question. paint(), repaint(), update()

    Hi
    I have a GUI which consists of swing components and I want to paint onto them. For example if somebody select a component I want to paint a rectangle around it.
    The select event stores the component in a variable and calls repaint(). This shoul call paint() which looks like this:
    public void paint( graphics g){
    draw the rectangle
    super.paint(g);
    The rectangle is actually painted for half a second. Then it is gone again. I want to have it painted permanentely. Why is the rectangle erased after that? Is it because of the update() method?
    I tried to overwrite the update method with a plain method:
    public void update(graphics g) { }
    it didnt do anything.
    Another question. I have to paint differnt stuff regarding what events are thrown. Is it a good programming style to put all the draw stuff into the paint method and look what happend like:
    if(event a)
    else if(event b)
    ...

    Have you tried putting super.paint(g) before the code to draw the rectangle? I think what's happening is that the super's paint is drawing the component, thus erasing your rectangle.
    You may want to check the API for other options. There may be a property that indicates the size and color of a border. It would be easier and probably look better to adjust that, if it exists.
    I believe that update() draws a background (just a square of background color) and then calls paint(). If you override it with an empty method, I'd expect that nothing would be drawn.

  • Border / paint and update problem

    Hi,
    I have written a simple GUI and have two problems:
    first, a white border is being displayed a the right, left and bottom side.
    Second: for testing purposes I am drawing a simple rectangle; I am starting at (1, 1) but it's actually being drawn maybe at (-5, -5). Sometimes it's not being drawn at all.
    Here is my code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.WindowConstants;
    public class MainWindow extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jPanel1;
         final static BasicStroke stroke = new BasicStroke(2.0f);
         public MainWindow() {
              initComponents();
         private void initComponents() {
              jPanel1 = new JPanel();
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              jPanel1.setBackground(new Color(153, 204, 255));
              jPanel1.setPreferredSize(new Dimension(1024, 768));
              getContentPane().add(jPanel1);
              pack();
         public void paint(Graphics g){
              update(g);
         public void update(Graphics g){
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(stroke);
              g2.draw(new Rectangle2D.Double(1, 1, 50, 50));
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainWindow().setVisible(true);
    }I am not sure about the paint / update method. I read the Swing tutorial and found examples where the drawing is being done in the update method... Does this have certain advantages?
    Thanks for your help!

    I still don't have it... where is my mistake?
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MainWindow extends JPanel {
         private static final long serialVersionUID = 1L;
         public MainWindow() {
              initComponents();
         private void initComponents() {
              JComponent face = new InitMainWindow();
              face.setPreferredSize( new Dimension(250, 250) );
              JFrame frame = new JFrame();
                    frame.setTitle("Test");
              frame.setBackground(new Color(153, 204, 255));
              frame.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent evt) {
                        mouseClick(evt);
              frame.pack();
              frame.setVisible( true );
         private void mouseClick(MouseEvent evt) {
              System.out.println("Click!");
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(Color.BLACK);
              g.drawLine(100, 100, 150, 150);
         public static void main(String args[]) {
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new MainWindow().setVisible(true);
    }

  • Paint(), repaint(), update() question

    I have an applet window which paints text,
    then a request may be made to the applet to add more text,
    my problem is that i seem to be repainting evertything.
    please help :o|

    i have altered it slightly so that now my program uses a vector which is a list of names, if the list is updated the paint method will need recalling and the new list displayed
    //i havent used a canvas but i think it may be more useful is that right?
      public void init()
        this.setSize(250,350);
        this.addWindowListener(new java.awt.event.WindowAdapter()
          public void windowClosing(WindowEvent e)
            chatOnlineListClosing_windowClosing(e);
        this.setBackground(new Color(13, 79, 158));
      } //end init()
      public void paint(Graphics g)
        positionX = 80;
        positionY= 85;
        g.setColor(Color.white);
        g.fillRect(40,40,150,250);
        g.setColor(Color.black);
        g.setFont(new java.awt.Font("Dialog", 1, 11));
        g.drawString("GroupNames", 60, 70);
        if(! nameVec.elementAt(0).equals("")) //checks there is a value in the vector
          for(int i = 0; i < nameVec.size(); i++)
            String name = (String)nameVec.elementAt(i);
            g.drawString(name, positionX, positionY);
            positionY = positionY + 15;
      }//end paint()

  • Update SEM/BPS buffer   --- update Master data

    Hi all,
    in a planning layout I had the need to modify the master data (attributes of a IO). Therefore I use a planning function type exit and call sm30 to modify the p and x table.
    After returning to the planning layout still the old attributes of the InfoObjekt are shown.
    Is there a function to modify the data in the buffer or to force the BPS to reload the data from BW?
    If you are in a Layout and change/load the master data in BW you have the same problem. You have to exit the transaction (upspm) before the changes of the Master data take effect in BPS.
    Thanks for your help!

    Hello Pierre,
    If you are using the web the you could call the function module API_SEMBPS_REFRESH to refresh the buffer. Before that I would save the data (using API_SEMBPS_POST) to make sure the data is not lost.
    You cannot use this refresh when in the GUI as the refresh destroys the BPS buffer etc on the server and the GUI does not automatically restart the necessary buffer instance etc.
    Best regards,
    Gerd Schoeffl
    SAPNetWeaver RIG BI EMEA

  • CG02BD - Buffer Error, updating non existent record - Need your attention

    Hi Gurus,
    This is regarding transaction code CG02BD buffer error which I am getting while updating Identifier info.
    CG02BD - Edit Specification
    I am getting error "Error in Buffer: update of non existing record" for Num ID category only in case of Customer and Vendor.
    Could any one guide me to correct/rectify this one please.
    << removed >>
    Thanks !
    Madan
    Edited by: Rob Burbank on Sep 22, 2010 11:35 AM

    Can you please let us know the solution for the same.? We are facing the similer issue for one of the user and getting the same error.

  • Decoupled Infotype - Correct Buffer Access for PA30 and from BAPI?

    Weu2019ve created a custom decoupled infotype and read/delete/update/insert work just fine with PA30, but the same methods supplied with the corresponding Check class do not work when called from a program.  The Check class inherits from CL_HRPA_INFOTYPE_NNNN.  After going through some documentation, we made the Check class inherit from CL_HRPA_INFTY_NNNN and now the modify method works if we redefine the modify method to use the direct buffer update methods from IF_HRPA_MASTERDATA_BUFFER (implementation in CL_HRPA_MASTERDATA_BUFFER). But then, PA30 stops working and throws an exception - u201CInfotype does not support legacy accessu201D.
    Anyone know why the SAP generated infotype check class methods not work when called as it is? There are no error messages thrown and no messages returned in the message handler too. Just that the database does not get updated. The Read method always works for all cases though. Help documentation is clear about the risks and differences between the two buffer access methods but issues exist when using PA30 and when trying to access/update the buffer from a program or BAPI.

    Since you are adopting an approach per [SAP help|http://help.sap.com/saphelp_erp2005/helpdata/en/43/21d2254bba2bebe10000000a1553f7/frameset.htm], I guess only SAP can help. May be you should try your luck by opening a Customer message (i.e. if you haven't already done so).
    ~Suresh

  • Differences between various update modes

    Hi,
          I am using function module RH_INSERT_INFTY to create some entries in an Infotype table.In this FM, there are for options for the update
    1.D - Dialogue update
    2. S - Synchronous update
    3. A - asynchronous update
    4. B - Buffer update
    I am not able to decide which mode I have to use and what are the results of each.Can someone expalin me what each one is or provide some study materials to me?

    Hi,
        There are 3 type of Update modes , A , S and L
    A - Asynchronous update. Updates of called programs are executed in the same way as if in the COMMIT WORK statement the AND WAIT addition was not specified.
    S - Synchronous processing. Updates of the called programs are executed in the same way as if in the COMMIT WORK statement the AND WAIT addition had been specified.
    L Local update. Updates of the called program are executed in such a way as if the SET UPDATE TASK LOCAL statement had been executed in it.
    Regards
    Kiran Sure

  • UI updating and Busy tasks

    Hi, I'm writing a swing program and I want a JTextfield to display something like "Please wait" after a user clicks a button (and starts a task). But I guess since the task takes awhile, the UI doesn't get updated ("Please wait" doesn't show up) until after the task is complete. Previously I used the Timer class in javax.swing to delay the busy task a few miliseconds to allow for the UI to update, but in my new program I must do this multiple times, which gets annoying creating ActionListeners everywhere. It also makes the program hard to follow. I've tried using different Threads (a new thread seperate from the main thread that sets the JTextfield's text) but it still doesn't update the UI until after the busy task is complete. Can anyone help? Thanks.

    When you click on a JButton the thread that Handel your code is called the EventDispatchThread this thread is responsible for dispatching all events including painting and updating your GUI. When a task is handed to the event dispatch thread it is placed on a queue if you submit a large task the UI will not be updated until the task is finished. A good example is trying to run a infinite loop
    on a button click your GUI will never paint it self and if you try to take your window back and bring back in front you will see a blank area. The standard solution is to perform large tasks in a different Thread as an example.
         public void actionPerformed(ActionEevent ae){
                //action performed for button click
              Thread t = new Thread(){
                   public void run(){
                          //tell your UI to wait untill task is finished
                         startTask();
                         //tell your UI everything is ok
               t.start();
         }

  • Changeing Paint's Graphics outside paint

    I have this code:
    public void Paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setTransform (t);
    how can I access g2 from outside Paint?

    You should not access g2d outside of paint. Let me explain. First of all, references to Graphics that are passed to methods, such as paint() and update(), are only valid during the execution of the method that they are passed to. That is, they are a copy of the original Graphics object. Once the method returns, the reference is no longer valid because its caller is responsible for disposing of it. Each Graphics represents a graphics context supplied by the native windowing system and there are usually only a limited number of them. Is this making sense. The important thing to remember is that the paint() method only has a copy of the Graphics object and that it is usually a bad idea to store it in an instance variable. The way that you get a reference to the Graphics of an image or a component (when you are outside of the paint() method) is to call the image.getGraphics(), component.getGraphics() or any of the Graphics.create() methods. Each returns a copy of the original Graphics object and you will be responsible for disposing of this copy when you are done using it. A very good example of this can be found when Double Buffering. Double Buffering is where you clear and draw an image off screen first, and then "blit" it straight onto your component. Here is an excerpt of code that is not from a paint() method://use double buffering to avoid flicker (paint image off screen then blit to screen)
    if (offScreenImage == null) offScreenImage = createImage(getWidth(),getHeight());
    Graphics offScreenGraphics = offScreoffScreenImage.getGraphics();
    Graphics g = getGraphics();
    //get graphics can return null if invoked before component's peer is created
    if (offScreenGraphics!=null && g!=null) {
       try {
          //clear the offscreen image
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getWidth(),getHeight());
          //blit to screen
          offScreenGraphics.drawImage(image,0,0,this);
          g.drawImage(offScreenImage,0,0,this);
       } finally {
          //must dispose of all graphics
          offScreenGraphics.dispose();
          g.dispose();
       }//end try
    }//end ifIt demonstrates the getting of the Graphics object when your current method it is in wasn't passed a reference to the Graphics object. In the code above, image and offScreenImage are instance variables. If you still want to use the Java2D version of the Graphics object, you will have to cast it once you get a reference to it. I hope this helps.
    Also, about repaint(). When you want to do application-triggered painting, you will want to call the repaint() method and should never call the paint() method directly. repaint() calls update(), update() clears the screen on heavyweight components, and finally paint() is called. For a very good article involving painting into components please read the following (it is a must read):
    http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    tajenkins

  • Component painted three times

    Hello
    I have an AWT application containing a frame F1. This frame contains combos and buttons,
    and another frame F2. Inside this frame F2, I have a TableBean component (GNU table for
    AWT). When I show (only first time) frame F1, table component is painted three times. How can I
    to dectect this component is already painted?. I don�t know how to use paint() or update().
    Many thanks for your help.
    tablaDatosListadoComercio = new tstuder.java.lib.component.table.Table(colDefs,linesComercio);
    tablaDatosListadoComercio.getTitlebar().setBackground(java.awt.Color.blue);
    tablaDatosListadoComercio.getTitlebar().setForeground(java.awt.Color.white);
    tablaDatosListadoComercio.setSelectionMode(tstuder.java.lib.component.table.DataArea.SELECT_ONE);
    tablaDatosListadoComercio.setHorizontalScrollMode(tstuder.java.lib.component.table.Table.HORIZONTAL_SCROLLBAR_OFF);
    panelTablaLstComercio.add(tablaDatosListadoComercio);
    ((java.awt.CardLayout)getLayout()).show(this,"panelDatosListadoComercio");

    I was talking with a co-worker about this kind of issue just yesterday - this isn't a simple problem at all.
    Basically, you (the application programmer) don't have a lot of control over how many times your paint method is called. The Toolkit (AWT) is responsible for deciding when a component's paint method is called. You, as the application programmer, can hint to AWT that a component needs repainting by calling repaint.
    Do not call paint yourself - AWT will call your paint method whenever it decides it wants to. It has in its own mind the state of everything, and which component needs to be repainted when. Controlling multiple repaints is a difficult problem for any GUI toolkit.
    So here's a bit of theory which will hopefully enlighten, rather than confuse, you.
    What you're doing when building an application is creating a bunch of objects that are meant to play together. The rules of the object behaviors are defined by the AWT (and Swing) Component classes. GUI applications are driven by the dispatch of events to them by the underlying system (in this case, Java, AWT and Swing). The bulk of the code being executed to do a GUI application is the underlying system (Java, AWT and Swing) since it's that underlying system that provides the basic framework for the application to exist in the first place.
    - David

  • Mouse clicking amd Dragging

    Hi, I have the following code so far, and when run in conjunction with other classes it creates a carousel feature.
    When you click and hold on the carousel and drag up or down, the carousel moves in the relevant direction.
    I am trying to change this click and drag, so instead when you click one of the polygons (which represent up and down arrows), the carousel moves up or down depending on which you click.
    Can anyone help with this?!
    Thanks very much!
    class ScheduleBarCanvas extends Canvas implements MouseListener,
    MouseMotionListener, ActionListener
    * CONSTANTS *
    /** Width of a slot, in pixels. */
    static final int SLOT_WIDTH = 2;
    /** Width of an entire day schedule bar, in pixels. */
    static final int BAR_WIDTH = Slot.SLOTS_PER_DAY * SLOT_WIDTH;
    /** Half of the height of a day schedule bar, in pixels. */
    static final int BAR_HALF_HEIGHT = 20;
    /** The width of an hour within a day schedule bar, in pixels. */
    static final double HOUR_WIDTH = BAR_WIDTH / 24;
    * The schedule day bars are represented as a rotatable 'wheel'. This value
    * defines the 'angle' allocated to a single day bar.
    private static final float DEGREES_PER_DAY_BAR = 10;
    * For convenience, this value represents the number of day bars that occupy
    * a 90-degree 'slice' of the schedule wheel.
    private static final int DAY_BARS_PER_90_DEGREES = (int) 9;
    * The maximum number of day bars that can be represented in the wheel.
    private static final int MAX_BARS = 9*2-1;
    * FIELDS *
    * Popup menu to use for right click menu. The right click menu allows users
    * to perform actions such as changing the climate for a selected period of
    * time.
    private final JPopupMenu rightClickMenu = new JPopupMenu();
    * Determines whether 'paste day schedule' is an available option in the
    * right click menu. 'Paste day schedule' should remain unavailable until
    * the user has copied a day schedule bar.
    private boolean allowPaste = false;
    * When the user has chosen to copy a day schedule, it will be stored here.
    private DaySchedule copiedDaySchedule;
    * A day schedule with the default period allocations.
    private final DaySchedule defaultDaySchedule;
    /** X coordinate of the left end of the schedule bars. */
    private int barLeftX;
    /** Y coordinate of centre of schedule bar display. */
    private int centreY;
    /** Width of canvas, pixels. */
    private int width;
    /** Height of canvas, pixels. */
    private int height;
    /** X coordinate of last mouse click. */
    private int lastMouseClickPositionX = 0;
    /** Y coordinate of last mouse click. */
    private int lastMouseClickPositionY = 0;
    /** X coordinate of last right mouse button click. */
    private int lastRightClickPositionX = 0;
    /** Y coordinate of last right mouse button click. */
    private int lastRightClickPositionY = 0;
    /** Start time of last selected period. */
    private Slot periodStartTime = new Slot(0);
    /** End time of last selected period. */
    private Slot periodEndTime = new Slot(0);
    /** Last-pressed mouse button. */
    private int pressedButton;
    * While clicking and dragging to modify the end time of a period, this
    * field stores the 'old' end time of the period.
    private int currentPeriodEnd;
    * While clicking and dragging to modify the end time of a period, this
    * field stores the width of the current period. At other times, this field
    * has the value 0.
    private int currentPeriodWidth = 0;
    * Rather than directly manipulating the window's canvas, a buffer is used.
    * All updates to the display are computed 'out of sight', by writing to
    * this buffer's Graphics object (see 'graphicsBuffer') and then copied to
    * the canvas in one go.
    private Image imageBuffer;
    private Image imageBuffer2;
    /** Graphics object buffer to use when updating the display. */
    private Graphics graphicsBuffer;
    private double animationSpeed = 0;
    private double simTimeInc;
    private double simTime = 0; // simulated time, HOURS from start
    /** Collection of days */
    private Schedule schedule;
    * The set of day schedule bars visible on screen at present. As the user
    * scrolls through different days, schedule bars will come in and out of
    * sight, and hence will enter and leave this array.
    private DayBar[] visibleScheduleBars;
    /** Stores the available schedulables */
    private List<Schedulable> palette;
    private int barZeroDay;
    /** Currently highlighted period - not currently used */
    private Period selection;
    /** Previously highlighted selection - not currently used */
    private Period oldSelection; // button 3 selections
    private Period dayDrag; // button 1 drag region
    private DaySchedule daySched; // schedule affected by drag
    * When clicking and dragging to change the duration of a Period, this value
    * is used to store the number of the slot being dragged.
    * If this is a new Period, and hence no prior boundary existed, this value
    * will be -1.
    private int draggedSlotBoundary;
    * When you right click on a Period, the system fills this value with the
    * number of the first slot in that Period. For instance, if 13:00 to 16:00
    * is set to 'away', and you right click at 14:40 (or any other slot inside
    * the 'away' Period), then this value will be set to the index of the slot
    * 13:00.
    private int firstSlotNumber;
    * When you right click on a Period, the system fills this value with the
    * number of the last slot in that Period. For instance, if 13:00 to 16:00
    * is set to 'away', and you right click at 14:40 (or any other slot inside
    * the 'away' Period), then this value will be set to the index of the slot
    * 16:00.
    private int lastSlotNumber;
    private DaySchedule selectedDaySchedule;
    private boolean createPeriods = true;
    * CONSTRUCTORS *
    * Setting various schedules that can be displayed
    * Initialises the display of the scheduler
    * Setting right click menu
    ScheduleBarCanvas()
    int delay = 0; // milliseconds
    int period = 40; // milliseconds
    final double updateFreq = 1000.0 / period; // H
    visibleScheduleBars = new DayBar[20];
    palette = new ArrayList<Schedulable>();
    palette.add(new Schedulable(new Color(50, 50, 220))); // away
    palette.add(new Schedulable(new Color(100, 180, 160))); // sleep
    palette.add(new Schedulable(new Color(150, 150, 120))); // busy
    palette.add(new Schedulable(new Color(200, 100, 20))); // relax
    defaultDaySchedule = new DaySchedule(palette);
    schedule = new Schedule(palette);
    Timer timer = new Timer();
    // Inner class construction for a java.util.Timer object with a
    // defined TimerTask to run processes. See the java.util library
    // in the Java API for details. Also refer to other java utility
    // assistance classes which may be useful to you in the future.
    timer.schedule(new TimerTask()
    public void run()
    simTimeInc = getAnimationSpeed() / (updateFreq * 200.0);
    if (simTimeInc > 0.0)
    { // Advance simulation time at
    simTime += simTimeInc; // current rate
    repaint(); // then update the display ASAP.
    }, delay, period); // schedule's init delay & repeat-call period
    JMenuItem menuItem1 = new JMenuItem(
    "Set climate to 'Away'", new ImageIcon("away.png")),
    menuItem2 = new JMenuItem(
    "Set climate to 'Sleeping'", new ImageIcon("sleep.png")),
    menuItem3 = new JMenuItem(
    "Set climate to 'Relaxing'", new ImageIcon("relax.png")),
    menuItem4 = new JMenuItem(
    "Set climate to 'Busy'", new ImageIcon("busy.png")),
    menuItem5 = new JMenuItem(
    "Reset day schedule", new ImageIcon("refresh.png")),
    menuItem6 = new JMenuItem(
    "Copy day schedule", new ImageIcon("copy.png"));
    menuItem1.addActionListener(this);
    menuItem2.addActionListener(this);
    menuItem3.addActionListener(this);
    menuItem4.addActionListener(this);
    menuItem5.addActionListener(this);
    menuItem6.addActionListener(this);
    rightClickMenu.add(menuItem2);
    rightClickMenu.add(menuItem4);
    rightClickMenu.add(menuItem1);
    rightClickMenu.add(menuItem3);
    rightClickMenu.add(menuItem5);
    rightClickMenu.add(menuItem6);
    addMouseListener(this);
    addMouseMotionListener(this);
    * GRAPHICS METHODS *
    * Updates the GUI.
    * @param g graphics object to draw to.
    public void update(Graphics g)
    // NB: repaint() above automatically calls update(Graphics g) ASAP.
    paint(g);
    * Updates the display.
    * @param g canvas to draw on.
    public void paint(Graphics g)
    float carouselRadius = 100; // Carousel radius in pixels
    float degreesPerPixel = (float) (57.29 / carouselRadius);
    if (currentPeriodWidth != 0)
    simTime += currentPeriodWidth * (degreesPerPixel / DEGREES_PER_DAY_BAR) * 24;
    currentPeriodEnd += currentPeriodWidth;
    currentPeriodWidth = 0;
    barZeroDay = (int) simTime / 24; // treat 1 sim sec as 1 hour
    int maxDayNo = barZeroDay + MAX_BARS;
    if (barZeroDay < 0 || maxDayNo >= Schedule.N_SCHEDULES)
    return; // invalid day number; do nothing
    Dimension dim = getSize();
    int maxX = dim.width - 1, maxY = dim.height - 1;
    barLeftX = maxX / 7;
    centreY = maxY / 2;
    if (width != dim.width || height != dim.height)
    width = dim.width;
    height = dim.height;
    imageBuffer = createImage(width, height);
    graphicsBuffer = imageBuffer.getGraphics();
    graphicsBuffer.clearRect(0, 0, width, height);
    graphicsBuffer.setColor(new Color(0, 0, 0));
    int hour = (int) simTime - barZeroDay * 24;
    float dayZeroOffsetAngle = (float) (((hour - 12) / 24.0) * DEGREES_PER_DAY_BAR);
    for (int barNo = 0; barNo <= MAX_BARS; barNo++)
    int dayNo = barZeroDay + barNo;
    int daysEarlier = DAY_BARS_PER_90_DEGREES - barNo;
    float dayAngle = daysEarlier * DEGREES_PER_DAY_BAR
    + dayZeroOffsetAngle;
    float z = carouselRadius * (float) Math.cos(0);
    float y = carouselRadius * (float) Math.sin(dayAngle / 57.3);
    float x = z / 20;
    DayBar dayBar = new DayBar(dayNo, schedule.getDaySchedule(dayNo),
    graphicsBuffer, barLeftX, centreY, x, y);
    visibleScheduleBars[barNo] = dayBar;
    for (int barNo = 0; barNo <= MAX_BARS; barNo++)
    visibleScheduleBars[barNo].paintBar(oldSelection, selection);
    g.drawImage(imageBuffer, 20, 0, null);
    g.setColor(Color.WHITE);
    g.drawRect(40,25,375,50);
    g.fillRect(40,25,375,50);
    g.drawRect(40,205,375,65);
    g.fillRect(40,205,375,65);
    Point bigArrowPoint1 = new Point(0,0);
    Point bigArrowPoint2 = new Point(0,0);
    Point bigArrowPoint3 = new Point(0,0);
    Point smallArrowPoint1 = new Point(0,0);
    Point smallArrowPoint2 = new Point(0,0);
    Point smallArrowPoint3 = new Point(0,0);
    bigArrowPoint1 = new Point(100,100); //top left
    bigArrowPoint2 = new Point(100,100); //middle right
    bigArrowPoint3 = new Point(100,100); //bottom left
    smallArrowPoint1 = new Point(100,100); //top left
    smallArrowPoint2 = new Point(100,100); //middle right
    smallArrowPoint3 = new Point(100,100); //bottom left
    Polygon bigArrow = new Polygon();
    bigArrow.addPoint(bigArrowPoint1.x+310,bigArrowPoint1.y-25);
    bigArrow.addPoint(bigArrowPoint2.x+320,bigArrowPoint2.y-25);
    bigArrow.addPoint(bigArrowPoint3.x+315,bigArrowPoint3.y-30);
    Polygon smallArrow = new Polygon();
    smallArrow.addPoint(smallArrowPoint1.x+310,smallArrowPoint1.y+105);
    smallArrow.addPoint(smallArrowPoint2.x+320,smallArrowPoint2.y+105);
    smallArrow.addPoint(smallArrowPoint3.x+315,smallArrowPoint3.y+110);
    g.setColor(Color.black);
    g.fillPolygon(bigArrow);
    g.drawPolygon(bigArrow);
    g.setColor(Color.black);
    g.fillPolygon(smallArrow);
    g.drawPolygon(smallArrow);
    addMouseListener(this);
    addMouseMotionListener(this);
    * Sets a new percentage value for the animation speed of the application.
    * @param animationSpeed desired animation speed.
    void setAnimationSpeed(double animationSpeed)
    this.animationSpeed = animationSpeed;
    * Returns the current speed of the animation, as a percentage.
    * @return the current speed of the animation, as a percentage.
    private double getAnimationSpeed()
    return animationSpeed;
    * Finds and returns a slot based upon the specified mouse position
    * coordinates.
    * @param x x coordinate of selection, relative to centre-left of schedule
    * bar display.
    * @param y y coordinate of selection, relative to centre-left of schedule
    * bar display.
    * @return a Slot value corresponding to the selected slot if available. If
    * no slot was selected, null is returned.
    private Slot findSlot(int x, int y)
    int barNumber = findDayBarNumber(x, y);
    if (barNumber == -1)
    return null;
    int foo = (x - (int) visibleScheduleBars[barNumber].getLeftAngleX());
    int bar = (barNumber * Slot.SLOTS_PER_DAY + foo / SLOT_WIDTH);
    return new Slot(bar + barZeroDay * Slot.SLOTS_PER_DAY);
    * Finds the day bar specified by the provided mouse coordinates, and then
    * returns its number.
    * @param x x coordinate of mouse position.
    * @param y y coordinate of mouse position.
    * @return the number of the day bar, or -1 if no day bar was found at the
    * specified mouse coordinates.
    private int findDayBarNumber(int x, int y)
    for (int barNo = MAX_BARS - 1; barNo >= 0; barNo--)
    DayBar dayBar = visibleScheduleBars[barNo];
    if (x >= dayBar.getLeftAngleX() && x <= dayBar.getBarRightAngleX()
    && y >= dayBar.getBarBottomAngleY()
    && y <= dayBar.getBarTopAngleY())
    return barNo;
    return -1;
    * EVENT HANDLER METHODS *
    * This event handler is unused.
    * @param evt ignored.
    public void mouseClicked(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseExited(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseEntered(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseMoved(MouseEvent evt)
    * Called when the mouse button is released.
    * 1. Displays the right click menu if the right mouse button was clicked 2.
    * Updates 'last click position' fields 3. Modifies end time of current
    * selection
    * @param evt mouse event information.
    public void mouseReleased(MouseEvent evt)
    if (evt.isPopupTrigger()) // was the menu requested?
    displayRightClickMenu(evt);
    // Update 'last click position' fields
    lastMouseClickPositionX = evt.getX();
    lastMouseClickPositionY = evt.getY();
    if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    int barPositionX = lastMouseClickPositionX - barLeftX;
    int barPositionY = centreY - lastMouseClickPositionY;
    periodEndTime = findSlot(barPositionX, barPositionY);
    selection.setEnd(periodEndTime);
    * Called when mouse button is pressed. Updates slot with schedulable.
    * @param evt mouse event information.
    public void mousePressed(MouseEvent evt)
    if (evt.isPopupTrigger()) // was the menu requested?
    displayRightClickMenu(evt);
    lastMouseClickPositionX = evt.getX();
    int barPositionX = lastMouseClickPositionX - barLeftX;
    lastMouseClickPositionY = evt.getY();
    int barPositionY = centreY - lastMouseClickPositionY;
    periodStartTime = findSlot(barPositionX, barPositionY);
    if (periodStartTime == null)
    return;
    if (periodStartTime.getDayNumber() < 0
    || periodStartTime.getDayNumber() >= Schedule.N_SCHEDULES)
    return; // boundary case.
    pressedButton = evt.getButton(); // 1=left, 2=mid or wheel 3= right
    if (pressedButton == MouseEvent.BUTTON1)
    { // dragging
    // but maybe creating new selection too so...
    oldSelection = selection;
    currentPeriodEnd = barPositionY;
    currentPeriodWidth = 0;
    dayDrag = new Period(periodStartTime, periodStartTime);
    int s = periodStartTime.getSlotNumber();
    if (!createPeriods)
    return;
    daySched = schedule.getDaySchedule(periodStartTime.getDayNumber());
    draggedSlotBoundary = daySched.findNearBoundary(s, 3);
    if (draggedSlotBoundary < 0)
    if (s < 0 || s >= Slot.SLOTS_PER_DAY)
    return; // boundary case
    // Not near a boundary, so create seed slot for new
    // period
    if (daySched.getSlot(s) == palette.get(0))
    daySched.setSlot(s, palette.get(1));
    else
    daySched.setSlot(s, palette.get(0));
    draggedSlotBoundary = s;
    } else
    Schedulable SS = daySched.getSlot(draggedSlotBoundary);
    if (draggedSlotBoundary < s)
    daySched.insert(SS, draggedSlotBoundary, s);
    else
    daySched.insert(SS, s, draggedSlotBoundary);
    else if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    oldSelection = selection;
    periodStartTime = findSlot(barPositionX, barPositionY);
    selection = new Period(periodStartTime, periodStartTime);
    * Called when the mouse is moved while a button on it is held down.
    * Changes the end time of the selected Period.
    * @param evt information about the current mouse cursor state, e.g.
    * position.
    public void mouseDragged(MouseEvent evt)
    lastMouseClickPositionX = evt.getX();
    int barPositionX = lastMouseClickPositionX - barLeftX;
    lastMouseClickPositionY = evt.getY();
    int barPositionY = centreY - lastMouseClickPositionY;
    if (pressedButton == MouseEvent.BUTTON1)
    { // dragging
    Slot selectedSlot = findSlot(barPositionX, barPositionY);
    currentPeriodWidth = barPositionY - currentPeriodEnd;
    if (draggedSlotBoundary < 0 || selectedSlot == null)
    return; // out of bounds
    if (!createPeriods)
    return;
    for (int s = draggedSlotBoundary + 1; s < selectedSlot.getSlotNumber(); s++)
    daySched.setSlot(s, daySched.getSlot(draggedSlotBoundary));
    dayDrag.setEnd(selectedSlot); // or could use Selection instead
    if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    Slot selectedSlot = findSlot(barPositionX, barPositionY);
    selection.setEnd(selectedSlot);
    * Displays the right click menu.
    * @param evt information about the current mouse cursor state, e.g.
    * position.
    private void displayRightClickMenu(MouseEvent evt)
    // Calculate positions of mouse click relative to centre-left of
    // schedule bars display.
    lastRightClickPositionX = evt.getX() - barLeftX;
    lastRightClickPositionY = centreY - evt.getY();
    // identify bar to modify
    DayBar db = null;
    for (int barNo = MAX_BARS - 1; barNo >= 0; barNo--)
    DayBar currentBar = visibleScheduleBars[barNo];
    if (lastRightClickPositionX >= currentBar.getLeftAngleX()
    && lastRightClickPositionX <= currentBar.getBarRightAngleX()
    && lastRightClickPositionY >= currentBar.getBarBottomAngleY()
    && lastRightClickPositionY <= currentBar.getBarTopAngleY())
    db = currentBar;
    break;
    if (db == null)
    return;
    // identify 'selected' section/setting
    Slot t = findSlot(lastRightClickPositionX, lastRightClickPositionY);
    int slot = t.getSlotNumber();
    if (slot < 0)
    return; // out of bounds
    // find out colour of selected section
    selectedDaySchedule = db.getDaySchedule();
    Color colour = selectedDaySchedule.getSlot(slot).colour;
    // go left/back; find earliest section with this colour
    firstSlotNumber = slot;
    while (true)
    Color currentSlotColour = selectedDaySchedule
    .getSlot(firstSlotNumber).colour;
    if (!currentSlotColour.equals(colour))
    firstSlotNumber++;
    break;
    if (firstSlotNumber > 0) // lower boundary case
    firstSlotNumber--;
    else
    break;
    // go right/forwards; find latest section with this colour
    lastSlotNumber = slot;
    while (true)
    Color currentSlotColour = selectedDaySchedule
    .getSlot(lastSlotNumber).colour;
    if (!currentSlotColour.equals(colour))
    break;
    if (lastSlotNumber < Slot.SLOTS_PER_DAY - 1) // upper bound case
    lastSlotNumber++;
    else
    break;
    rightClickMenu.show(evt.getComponent(), evt.getX(), evt.getY());
    * Called when the user selects an item from the right click menu. Changes
    * the Schedulable for the selected Period to the requested value.
    * @param evt an ActionEvent, providing information about the command that
    * was selected from the menu.
    public void actionPerformed(ActionEvent evt)
    String command = evt.getActionCommand();
    if (command.equals("Copy day schedule"))
    if (!allowPaste) {
    * If the user copies a day schedule, we must enable
    * the paste option in the menu.
    JMenuItem menuItem7 = new JMenuItem("Paste day schedule",
    new ImageIcon("paste.png"));
    menuItem7.addActionListener(this);
    rightClickMenu.add(menuItem7);
    allowPaste = true; // only do this once
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    /* It's important that we copy the day schedule by value, not by
    * reference. If we just copy a reference, then if we 'copy' a bar,
    * changing the source bar after the copy operation will change what
    * is ultimately 'pasted'.
    copiedDaySchedule = db.getDaySchedule().clone();
    else if (command.equals("Paste day schedule"))
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    db.getDaySchedule().insert(
    copiedDaySchedule, 0, Slot.SLOTS_PER_DAY-1);
    else if (command.equals("Reset day schedule"))
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    db.getDaySchedule().insert(
    defaultDaySchedule, 0, Slot.SLOTS_PER_DAY-1);
    else
    * Identifies which new Schedulable was requested. This Schedulable
    * will replace the selected Period's Schedulable value.
    * For instance, if "Away" was selected from the menu, then we must
    * fetch the "Away" Schedulable.
    Schedulable schedulable;
    if (evt.getActionCommand().equals("Set climate to 'Away'"))
    schedulable = palette.get(2); // the 'away' Schedulable
    else if (evt.getActionCommand().equals("Set climate to 'Sleeping'"))
    schedulable = palette.get(0); // the 'sleeping' Schedulable
    else if (evt.getActionCommand().equals("Set climate to 'Busy'"))
    schedulable = palette.get(1);
    else if (evt.getActionCommand().equals("Set climate to 'Relaxing'"))
    schedulable = palette.get(3);
    else
    // Should never occur
    throw new Error("Unrecognised command.");
    // Now fill the selected Period with the requested Schedulable.
    selectedDaySchedule.insert(
    schedulable, firstSlotNumber, lastSlotNumber);
    * User is able to edit schedule when boolean is set to true
    * @param createPeriods sets state of interaction with day schedules
    void setCreatePeriods(boolean createPeriods) {
    this.createPeriods = createPeriods;
    }

    Here is the Apple document covering Magic Mouse faults.  Symptom number 6 seems the one to check out.  Is this a longstanding or a recently developed fault?
    And, of course, is it still under the 12 month warranty.
    One thing to pay particular attention to is the proximity of electronic items such as cradles for phones and the like which if active, can interfere with the signal.
    Troubleshooting wireless mouse and keyboard issues

  • Rather complicated (possibly!) threading/event handling problem...

    OK, so here's a good question to ask for my first post to this site!
    My current "project" is a GUI applet that does real-time interactions on a set of objects and user input. I'm using double buffering, event handling (from the keyboard) and multiple threads to handle the categories of "user input and graphics" and "world state updating." Here is a rough overview of how the program is layed out:
    // keyboard input status class
    class Keyboard extends KeyListener {
       static int[] code = new int[7];            // contains keycodes of interesting keys
       static boolean[] status = new boolean[7];     // status of keys (true=pressed)
       static boolean getStatus(int key) {
          return status[key];
       void keyPressed(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = true;
       void keyReleased(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = false;
    // main program applet
    class Program extends Applet implements Runnable {
       static Thread thread;      // main thread of applet
       static Image buffer;         // double buffer for offscreen rendering
       static boolean running;  // flag to indicate status of applet
       void init() {
          buffer = createImage(500, 500);
          // other initializations
       void destroy() {
          // other disposes
       void start() {
          running = true;
          thread = new Thread(this);
          thread.start();
          addKeyListener(new Keyboard());   // begin receiving input
       void stop() {
          running = false;
          if(thread != Thread.currentThread())
             thread.join();    // wait for thread to die before continuing
       void run() {
          double paintTimer = 0;   // timer to suspend painting to buffer until necessary
          double dt = 0;       // difference in time between loops
          while(running) {
             // update timing stuff (dt and paintTimer)
             // update world status
             paintTimer -= dt;      // to decrement painting timer
             if(paintTimer <= 0) {
                paintTimer = 1.0 / fps;    // reset paint timer based on current fps setting
                synchronized(syncObject) {
                   // paint world to buffer
                   repaint();
             Thread.yield();  // to yield time to painting and user input thread
       // this method is only called by the internal thread within the applet
       //  that is responsible for painting and event handling
       void paint(Graphics g) {
          // make sure painting to screen won't conflict with thread that's drawing on buffer!
          synchronized(syncObject) {
             g.drawImage(buffer, 0, 0, null);  // do double buffering...paint buffer to screen
    }So the end result is that it works fine some of the time, but every once in awhile I'll get these strange results where it'll seem as if the internal thread that handles graphics and input will get bogged down or stop responding normally, even with the Thread.yield() call from the main applet thread. I'll get results where the world will continue to be updated correctly, but the user input and onscreen rendering freeze in a particular state for a matter of seconds, and then it seems to regain control for a brief few milliseconds (hence I'll get a quick screen refresh and keyboard state change), and then it'll freeze again. Once this starts happening somewhere in the middle of execution, it continues to happen throughout that runtime session. Sometimes when I force-close the appletviewer I'll get weird native runtime exceptions that seem to occur within Sun's keyboard input manager.
    Almost always it'll run perfectly for many minutes, and then all of a sudden it'll start to freeze up. Every once in awhile it freezes almost immediately after startup. I've run some testcases on it and am pretty confident it has nothing to do with the synchronization or the fact that I create a new applet thread every time the applet is restarted dynamically. Is it something happening within the event thread of the applet that I'm not aware of? Or is it something wrong with the flow of my code? Thanks for any input or help you can give! I'll be happy to send more details if needed.
    Zach

    right before your repaint, putSystem.out.println("Is EDT? "+SwingUtilities.isEventDispatcherThread());if its printing false, then you need to do SwingUtilities.invokeLater( ... );
    and put GUI updating code in the invoke later.

  • Can any one debug this code????

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.*;
    public class AppletTest2 extends JApplet implements ActionListener,MouseMotionListener,WindowListener{
    JFrame fr = new JFrame("Visual Tool -- Work Flow Editor");
         JPanel panel1 = new JPanel();
         JPanel panel2 = new JPanel();
         JButton sButton = new JButton("Source");
         JButton rButton = new JButton("Redirection");
         JButton dButton = new JButton("Destination");
         JButton connect = new JButton("Connect");
         BasicStroke stroke = new BasicStroke(2.0f);
         int flag = 1 ;
         Vector lines = new Vector();
         JButton sBut,rBut,dBut;
    int x1 = 0 ;
         int y1 = 0 ;
         int x2 = 0 ;
         int y2 = 0;
         int x3 = 0;
         int y3 = 0;
         int i=0;
         int j=0;
         int k=0;
         int l = 100;
    int b = 50;
    public void init(){
              /*********Frame ******************/
    fr.getContentPane().setLayout(new BorderLayout());
         fr.setSize(700,500);
              fr.getContentPane().add(panel1,BorderLayout.CENTER);
              fr.getContentPane().add(panel2,BorderLayout.SOUTH);
              fr.addWindowListener(this);
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,105,205));
    /************************PANEL 2 *************/
              panel2.setLayout(new FlowLayout());
              panel2.setBackground(new Color(105,205,159));
              panel2.add(sButton);
              panel2.add(rButton);
              panel2.add(dButton);
              panel2.add(connect);
              connect.setToolTipText("Use this button after selecting From and To position to connect");
              /***************************LISTENER********************/
    sButton.addActionListener(this);
              rButton.addActionListener(this);
              dButton.addActionListener(this);
              connect.addActionListener(this);
              fr.setVisible(true);     
              fr.setResizable(false);
         } // init clse
    /************************** START METHOD **********************************************/
              public void start(){                                 
                   System.out.println("inside start");
                   paint(panel1.getGraphics());
    /*******************************APPLET METHODS **************************************************/
              public void stop(){}
              public void destroy(){}
    /******************************MOUSE MOTION LISTENERS METHOD*************************************/
              public void mouseMoved(MouseEvent e){System.out.println("moved");}
              public void mouseDragged(MouseEvent e){System.out.println("dragged");}
    /***************************************ACTION EVENT IMPLEMENTAION *******************************/
         public void actionPerformed(ActionEvent e){
              if (e.getSource().equals(sButton)){          
              sourceObject("Source Object");          
              else if (e.getSource().equals(rButton)){          
              redirectionObject("Redirection");
              i = i+1;
              else if (e.getSource().equals(dButton)){
              destinationObject("Destination");
                   j= j+1;
              else if (e.getSource().equals(connect)){
                   System.out.println("am inside connect");                
                   paint(panel1.getGraphics());               
    else if(e.getSource().equals(sBut)){
                   System.out.println("am s button");                
                   x1 = sBut.getX() + l;
                   y1 = sBut.getY() + (b/2);
              else if(e.getSource().equals(rBut)){
                   System.out.println("am r button");               
                   x2 = rBut.getX() ;
                   y2 = rBut.getY()+ b/2;
                   System.out.println("x2 : " + x2 + "y2 :" +y2 );
              else if(e.getSource().equals(dBut)){
                   System.out.println("am d button");                
                   x3 = dBut.getX();
    y3 = dBut.getY()+ b/2;
    } // action close
    /**********************Main **********************************/     
         public static void main(String args[]){
         JApplet at = new AppletTest2();
              at.init();
              at.start();
    /********************my methods starts here *******************/
         public void sourceObject(String name){     
    sBut = new JButton(name);
         panel1.add(sBut);
         sBut.setBounds(new Rectangle(20,208,l,b));     
         sBut.addActionListener(this);
    System.out.println("am inside the source object") ;
         public void redirectionObject(String name){     
         rBut = new JButton(name);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(290,208,l,b));     
    rBut.addActionListener(this);
    System.out.println("am inside the redirection :" + j) ;
    public void destinationObject(String name){     
         dBut = new JButton(name);
         panel1.add(dBut);     
    System.out.println("am inside the destination object") ;
    if (j == 0)
                   dBut.setBounds(new Rectangle(566,60,l,b));                    
                   System.out.println("am inside the destination:" + j) ;
                   } else if (j == 2)
                        dBut.setBounds(new Rectangle(566,208,l,b));     
                        System.out.println("am inside the destination :" + j) ;
                   } else if (j == 1)
    dBut.setBounds(new Rectangle(566,350,l,b));     
                        System.out.println("am inside the destination :" + j) ;
    dBut.addActionListener(this);
    /* public void connectObject(Object obj1,Object obj2){
    System.out.println("nothing");
    /************************************* PAINT **************************/
    public void paint(Graphics g){
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
         g2.setStroke(stroke);
    if(flag == 1){
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println(np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                             g2.drawLine(p.x,p.y,p.width,p.height);
                             System.out.println(p.x +"" +""+ p.y + ""+ ""+ p.width+ "" + ""+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    // Graphics2D g2 = (Graphics2D) g;
         // g2.setStroke(stroke);
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);
         lines.addElement(new Rectangle(x1,y1,x2,y2));     
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    //     g2.drawLine(100,100,200,200);
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              // Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
              g2.setColor(Color.green);
                        g2.drawLine(x2,y2,x3,y3);
                        lines.addElement(new Rectangle(x2,y2,x3,y3));
                        x2 = 0; y2 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   //     Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);
                        lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    // repaint();
    /********************************WINDOW LISTENER IMPLEMENTATION *****************************/
    public void windowActivated(WindowEvent we) { 
              flag = 1;
              paint(panel1.getGraphics());
    System.out.println("windowActivated -- event 1");
         //start();               
         public void windowClosed(WindowEvent we) {
                                                                System.out.println("windowClosed -- 2");
         public void windowClosing(WindowEvent we){
                                                                System.out.println("windowClosing -- 3");
    public void windowDeactivated(WindowEvent we) {
                                                                     System.out.println("windowDeactivated -- 4");
    public void windowDeiconified(WindowEvent we) {
                                                                     flag = 1;
                                                                     System.out.println("windowDeiconified -- 5");          
                                                                     paint(panel1.getGraphics());           
    public void windowIconified(WindowEvent we) {           
                                                           System.out.println("windowIconified -- 6");
                                                           //paint(panel1.getGraphics());
    public void windowOpened(WindowEvent we) {             
                                                      //     flag = 1;
                                                      //     paint(panel1.getGraphics());
                                                           System.out.println("windowopened -- 7");     
    The problem am facing here is that when i minimize the frame and maximize , my old lines are getting disappared.
    For avoiding that i am storing the old coordinates and
    try to redraw , when maximize.
    but the lines are coming for flash of second and disappearing once again ?
    can any one help?
    thanks all

    You are probably seeing both a window un-iconify AND a window resize.
    Your best bet is to create an off screen buffer update that and then copy it to the screen. Just as you use the appropriate Java2d gc.createCompatibleImage(...) you should be ok. You will never have to worry about loosing your on-screen image again. Using an off screen buffer would also simplify your code as your paint would not have to be so crazy with all of those if(..) else if ... statements.

  • Graphic2D and buffers

    I need to overload the paint(Graphics g) method in a component and draw something using a Graphic2D onto the Graphics g. It all works, but when I draw something multiple times within the paint(), it creates a flicker. Is there any way to do all the drawing onto a buffer, then load the finished picture to the Graphics g?
    ... paint(Graphics g)
        Graphics2D g2 = g;
        for(...)  //no good
        { g2.draw something }
    }

    hi,
    What you should do is use a double-buffering strategy to overcome the flicker.. for eg
       Image          imageOffScreen;              
       Image          drawnImage;
       Graphics2D     bufferGraphics ;
       Dimension    d;
       /// Constructor ///
       public MyTest()
             d = getSize();
       // other code to come here
       public void paint(Graphics g)
             super.paint(g);
             // do ur painting routine here
    public void update(Graphics g)
           Dimension dimension = getSize();
           if(bufferGraphics == null || dimension.width != d.width || dimension.height != d.height)
                d = dimension;
                imageOffScreen = (BufferedImage)createImage(dimension.width, dimension.height);
                bufferGraphics = (Graphics2D)imageOffScreen.getGraphics();
           bufferGraphics.fillRect(0, 0, dimension.width, dimension.height);
           paint(bufferGraphics);
           g.drawImage(imageOffScreen, 0, 0, null);
       }The above code overrides both paint and update and from the update method makes a call to paint, also notice that first all the intermediate painting is done onto a temporary buffer (imageOffScreen) and then at the end of the update method the buffer image is drawn onto the screen, this will help in reducing the flicker...
    hope this helpz..
    cheerz
    ynkrish

Maybe you are looking for

  • How to add URL links to list of titles from db

    I'm trying create page that has the titles of articles from a blog, and which also links back to the page where the entire article is listed. So far I have the first part done. I created a DIV and then inserted from the DATA tab of DreamWeaver - a dy

  • Integration engine problem

    Dear All , I am facing one problem related to file generation and pickup . In file to IDOC AND IDOC TO FIle SCENARIO PROCEESING IS NOT BEING DONE BY INTEGRATION ENGINE . When I am checking the status of message in SXMB_MONI IT IS SHOWING <b>"RECORDED

  • Mac Mini unusable with external camera

    I have a mac mini and using FaceTime and Skype. After en undermined period (may be 1 minute) the camera starts to flicker between 2 different pictures. The same thing also happened before i exchanged my mini with a newer machine. I have tried 4 diffe

  • How to make components' size constant?

    I have a newbie question for you. How to make the size of components (button, combobox, etc...) constant? I mean they keep the same size as the users change window's size. Thanks. Sraiper

  • Prevent marketing document entry if BP has past due invoices

    Does anyone know a way to prevent users from entering a marketing document if the BP has past due invoices? Only solution I can come up with is to create code in the Transactions Notifications stored procedure. But is there a way to do this in B1? Th