Painting in applets

I ran into a problem using AWT in applets. Sometimes in IE the animated applets repaints in a random place. Sometimes it's taskbar area, sometimes browsers toolbar. I don't know if it's JRE 1.3.1_08's bug or it may be code's fault.
Anyone ran into similar issue?

Thanx Foxy Lady ;), but he problem occurs more often in an applet like this. Simple ticker with double buffering. I think the problem is in refreshing the applet more often than one second. Here's the code:
import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Image;
public class Ticker extends Applet implements Runnable {
     * Whole text to draw.
    String text = new String();
     * Single line from the script.
    String line;
     * Speed of moving text.
    int delay;
     * Background color.
    int bgColor;
     * Foreground color.
    int color;
     * Flag indicating if this applet is still active.
    boolean flag = true;
    int i = 0;
     * Offscreen image for doublebuffering.
    Image offscreenImage;
     * Width of the whole text.
    int textWidth;
     * Width of the applet.
    int wdth;
     *  The initialization method - getting parameters from the script.
    public void init() {
        line = new String(getParameter("text"));
        bgColor = Integer.parseInt(getParameter("bgColor"), 16);
        color = Integer.parseInt(getParameter("color"), 16);
        delay = Integer.parseInt(getParameter("delay"));
        wdth = Integer.parseInt(getParameter("width"));
        setBackground(new Color(bgColor));
        setSize(wdth, 20);
        offscreenImage = createImage(wdth, 20);
    public void paint(Graphics g) {
        drawText(i, g);
     * Draws the text in the <code>iks</code> position.
     * @param iks position of the text.
     * @param gr graphics context.
    public void drawText(int iks, Graphics gr) {
        gr.setColor(new Color(color));
        gr.setFont(new Font("SansSerif", Font.BOLD, 15));
        if (iks < -(textWidth - wdth)) {
            //if the whole text went away to the left
            //we should draw it from the beginning
            gr.drawString(text, iks + textWidth, 15);
        gr.drawString(text, iks, 15);
    public void update(Graphics g) {
        //getting the offscreen graphics context
        Graphics offscreenG = offscreenImage.getGraphics();
        //clearing the offscreen
        offscreenG.clearRect(0, 0, wdth, 20);
        //drawing the text in the offscreen
        paint(offscreenG);
        //replacing the screen with a ready offscreen image
        g.drawImage(offscreenImage, 0, 0, this);
    public void run() {
        Graphics g = getGraphics();
        FontMetrics metrics;
        //preparing the text to show
        g.setFont(new Font("SansSerif", Font.BOLD, 15));
        metrics = g.getFontMetrics();
        textWidth = metrics.stringWidth(text);
        while (textWidth <= wdth) {
            //if the text is shorter than the applet width
            //we shoul repeat it after a "+" sign.
            text += "+" + line;
            textWidth = metrics.stringWidth(text);
        text = text + "+";
        text = "++" + text;
        textWidth = metrics.stringWidth(text);
        //repainting the applet
        while (flag) {
            if (i < -textWidth) i = 0;
            i--;
            repaint();
            try {
                Thread.sleep(delay * 20);
            } catch (InterruptedException e) {
     * Start the thread.
    public void start() {
        new Thread(this).start();
     * Stop the thread.
    public void stop() {
        flag = false;
    public void destroy() {
}

Similar Messages

  • Need help with paint() within applet

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

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

  • Painting in Applets using another class

    hi all
    I am trying the simplest of codes, using another class which paints something on the client area.
    when I run it it does draw it on the screen but then disappears or is covered. ne suggestions or reasons why this might be happening...
    the code is as follows
    package test;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics2D.*;
    import java.awt.geom.*;
    public class TestApp1 extends JApplet {
    private Container container;
    public Rectangle rect;
    public CTest test1;
    public Graphics g;
    public void init()
    container=getContentPane();
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    test1=new CTest(false,g2);
    public void run()
    container.add(test1);
    public void stop()
    public void destroy()
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.*;
    public class CTest extends JPanel {
    protected
    Graphics2D m_graphics;
    Rectangle m_PlotRect;          
    public
    CTest(boolean resizable,Graphics2D g)
    m_graphics =g;
    m_PlotRect=new Rectangle(150,50,50,50);          
    void DrawAxis()
    m_graphics.setBackground(Color.white);
    m_graphics.setColor(Color.black);
    m_graphics.drawRect(
    (int)m_PlotRect.getMinX(),
    (int)m_PlotRect.getMinY(),
    (int)m_PlotRect.getWidth(),
    (int)m_PlotRect.getHeight()
    public void paint(Graphics g)
    super.paint(g);
    DrawAxis();
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    DrawAxis();

    thanx guys
    i could solve the problem. thought its good to share it with every one in case some one else falls for the same trap.
    what i did was tried to pass the Graphics object to my CTest class and then painted everything on the basis of that.
    this is where the code gets freaky.
    the correct way of doing it is not passing the graphics object to the CTest class but use the graphics object passed by the system to the paintcomponent function to do all the painting in the class.
    I did that and it works well.
    cheers
    Deepak

  • Help needed in optimizing painting logic

    Hi,
    I am working on a Applet where i have to do a lot of painting, the applet is kind of microsoft project, where u can define a activity as a rectangle and then u can select the rectangle and drag it to some other date,
    i am posting a code below, which i am using to draw all the rectangles,
    but some times when there is a lot of data scrolling is really very slow
    Can any one look at the code, and let help me optimize it,
    U can copy the code, compile and run it to see what i mean by slow,
    just in class data , change the value 600 to some thing less like 50 and it works very fast
    //start code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    public class TestDisplaySize extends JFrame
         private     JScrollPane scrollPane ;
         private MyPanel panel ;
         public TestDisplaySize()
              super("layered pane");
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              panel = new MyPanel();
              scrollPane = new JScrollPane(panel);
              Container contentPane = this.getContentPane();
              contentPane.add(scrollPane, BorderLayout.CENTER);
              setSize(new Dimension(800,600));
              this.setVisible(true);
              JViewport viewPort = scrollPane.getViewport();
         class MyPanel extends JPanel
              private int height;
              private int last;
              private Data data;
              public MyPanel()
         this.setBackground(Color.white);
         this.setOpaque(true);
         data = new Data();
         int size = data.getSize();
         height = size * 50;     
         last = data.getDataSize(0);
         int last1 = last -1;
         int length = data.getX(0, last1) + 100;
         System.out.println ("Lenght " + length + " height " + height);
         setPreferredSize(new Dimension(length, height) );     
         public void paintComponent(Graphics g)
    super.paintComponent(g);
    setBackground(Color.white);
    Rectangle r = scrollPane.getViewport().getViewRect();
    g.setClip((Shape)r);
    g.setColor(Color.blue);
    int x = 0;
    for(int i = 0; i < last ; i++)
         x +=60;
         g.drawLine(x, 0, x, height);
         g.drawString(String.valueOf(i), x, 10);
    int size = data.getSize();
    int width = 30;
    int height = 20;
    int yAxis = 20;
    g.setColor(Color.cyan);
    for(int i = 0; i < size; i++)
         int dataSize = data.getDataSize(i);
         for(int k = 0; k < dataSize; k++)
              int xAxis = data.getX(i, k);
              g.fill3DRect(xAxis, yAxis, width, height, true);
         yAxis = yAxis + 50;
    private class Data
              private ArrayList totalData = new ArrayList();
              public Data()
                        for(int i = 0; i < 600; i++)
                        ArrayList data = new ArrayList();
                        int l = 50;
                        for(int k = 0; k < 600; k++)
                             data.add(new Integer(l));
                             l = l + 50;
                        totalData.add(data);
              public int getSize()
                   return totalData.size();     
              public int getDataSize(int i)
                   return ((ArrayList)totalData.get(i)).size();     
              public int getX(int x, int y)
                   ArrayList data = (ArrayList)totalData.get(x);
                   Integer i = (Integer)data.get(y);
                   return i.intValue();
         public static void main(String args[])
         new TestDisplaySize();

    You should only paint what is visible. For example if you are presenting a grid of 100 x 100 boxes. And each box is 20 pixels wide and 20 pixels high, then that would create an <image> the size of 2000 x 2000. That is big ;-)
    What you want to do, is calculate what portion of the <image> that is viewable in your scrollpane and then only perform the paint operations on those boxes. For example, if the viewports width is 200 and its hieght is 80, then you should only paint 10 x 4 boxes (40 boxes total, each 20x20 pixels in size) -- The trick is figuring out what boxes need to be painted.!! I'll leave that up to you, but should be able to find code examples on the net doing something of this sort.
    Hope this helps, and makes sense.
    Cory

  • Java.lang.StackOverflowError problem, drawing images in applet :(

         * Paints the applet
        @Override
        public void paint(Graphics g)
            if(running && levelOne)
            g.setColor(Color.MAGENTA);
            g.drawString("HP Left: " + player.getHP(), 100, 10);
    //      g.drawString("Time Left: " + timer.getTime(), 170, 10);
            g.drawString("Score: " + player.getScore(), 30, 10);
            g.drawString("Required Score To Next Level: " + player.getScore() + "/3000", 100, 190);
            g.drawString("Level: 1", 30, 190);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
            if(start && storyStarted)
                try
                    update(g);
                    paintStory();
                catch(java.lang.StackOverflowError sofe)
                    System.exit(0);
            else if(start)
                g.drawImage(image, 0, 0, this);
                g.drawImage(gun, 200, 400, this);
         * Updates the paint() method and the applet
        @Override
        public void update(Graphics g)
            if(dbImage == null)
                dbImage = createImage(this.getWidth(), this.getHeight());
                dbG = dbImage.getGraphics();
            dbG.setColor(getBackground());
            dbG.fillRect(0, 0, this.getWidth(), this.getHeight());
            dbG.setColor(getForeground());
            paint(dbG);
            g.drawImage(dbImage, 0, 0, this);
        public void paintStory()
            getGraphics().drawImage(story1, 0, 0, this);
        }I know that my problem appears somewhere in the above written code, so if you would take a look, and try to help me fixing my problem! :D

    Vimsie wrote:
    I get a StackOverflowError, but the image isn't flickering!Err, the image is not flickering because there are no repaints happening anymore due to the StackOverflowError. This is hardly an argument for your approach.
    However, I have to admit I don't know how to solve your flickering problem. I've never used AWT but always SWING (but then I don't do applets).
    Maybe google can help?

  • Can U help me change "Paint.java" to MVC model

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollBar;
    import javax.swing.JTextField;
    import javax.swing.ImageIcon;
    public class Paint extends Applet implements ActionListener, AdjustmentListener, MouseListener, MouseMotionListener
    private static final long serialVersionUID = 1L;
    private final int NO_OP = 0;
    private final int PEN_OP = 1;
    private final int LINE_OP = 2;
    private final int ERASER_OP = 3;
    private final int CLEAR_OP = 4;
    private final int RECT_OP = 5;
    private final int OVAL_OP = 6;
    private final int FRECT_OP = 7;
    private final int FOVAL_OP = 8;
    private final int SPLINE_OP = 9;
    private final int POLY_OP = 10;
    private int mousex = 0;
    private int mousey = 0;
    private int prevx = 0;
    private int prevy = 0;
    private boolean initialPen = true;
    private boolean initialLine = true;
    private boolean initialEraser = true;
    private boolean initialRect = true;
    private boolean initialOval = true;
    private boolean initialFRect = true;
    private boolean initialFOval = true;
    private boolean initialPolygon = true;
    private boolean initialSpline = true;
    private int Orx = 0;
    private int Ory = 0;
    private int OrWidth = 0;
    private int OrHeight = 0;
    private int drawX = 0;
    private int drawY = 0;
    private int eraserLength = 5;
    private int udefRedValue = 255;
    private int udefGreenValue = 255;
    private int udefBlueValue = 255;
    private int opStatus = PEN_OP;
    private int colorStatus = 1;
    private Color mainColor = new Color(0,0,0);
    private Color xorColor = new Color(255,255,255);
    private Color statusBarColor = new Color(166,166,255);
    private Color userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    private JButton penButton           = new JButton(new ImageIcon(getClass().getResource("pen.gif")));
    private JButton lineButton           = new JButton(new ImageIcon(getClass().getResource("line.gif")));
    private JButton eraserButton           = new JButton(new ImageIcon(getClass().getResource("eraser.gif")));
    private JButton clearButton = new JButton("Clear");
    private JButton rectButton           = new JButton(new ImageIcon(getClass().getResource("rec.gif")));
    private JButton ovalButton           = new JButton(new ImageIcon(getClass().getResource("oval.gif")));
    private JButton fillRectButton      = new JButton(new ImageIcon(getClass().getResource("fillrec.gif")));
    private JButton fillOvalButton      = new JButton(new ImageIcon(getClass().getResource("filloval.gif")));
    private JButton splineButton = new JButton("Spline");
    private JButton polygonButton = new JButton("Polygon");
    private JButton blackButton = new JButton("Black");
    private JButton blueButton = new JButton("Blue");
    private JButton redButton = new JButton("Red");
    private JButton greenButton = new JButton("Green");
    private JButton purpleButton = new JButton("Purple");
    private JButton orangeButton = new JButton("Orange");
    private JButton pinkButton = new JButton("Pink");
    private JButton grayButton = new JButton("Gray");
    private JButton yellowButton = new JButton("Yellow");
    private JButton userDefButton = new JButton("User-Def");
    private JScrollBar redSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar blueSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar greenSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JTextField colorStatusBar = new JTextField(20);
    private JTextField opStatusBar = new JTextField(20);
    private JTextField mouseStatusBar = new JTextField(10);
    private JTextField redValue = new JTextField(3);
    private JTextField greenValue = new JTextField(3);
    private JTextField blueValue = new JTextField(3);
    private JLabel operationLabel = new JLabel(" Tool mode:");
    private JLabel colorLabel = new JLabel(" Color mode:");
    private JLabel cursorLabel = new JLabel(" Cursor:");
    private JPanel ToolbarPanel = new JPanel(new GridLayout(11,2,0,0));
    private JPanel drawPanel = new JPanel();
    private JPanel statusPanel = new JPanel();
    private JPanel udefcolPanel = new JPanel(new GridLayout(3,3,0,0));
    private JPanel udefdemcolPanel = new JPanel();
    private JPanel PicPanel               = new JPanel();
    public void init()
    setLayout(new BorderLayout());
    ToolbarPanel.add(blackButton);
    ToolbarPanel.add(blueButton);
    ToolbarPanel.add(redButton);
    ToolbarPanel.add(greenButton);
    ToolbarPanel.add(purpleButton);
    ToolbarPanel.add(orangeButton);
    ToolbarPanel.add(pinkButton);
    ToolbarPanel.add(grayButton);
    ToolbarPanel.add(yellowButton);
    ToolbarPanel.add(userDefButton);
    blueButton.setBackground(Color.blue);
    redButton.setBackground(Color.red);
    greenButton.setBackground(Color.green);
    purpleButton.setBackground(Color.magenta);
    orangeButton.setBackground(Color.orange);
    pinkButton.setBackground(Color.pink);
    grayButton.setBackground(Color.gray);
    yellowButton.setBackground(Color.yellow);
    userDefButton.setBackground(userDefinedColor);
    ToolbarPanel.add(penButton);
    ToolbarPanel.add(lineButton);
    ToolbarPanel.add(eraserButton);
    ToolbarPanel.add(clearButton);
    ToolbarPanel.add(rectButton);
    ToolbarPanel.add(ovalButton);
    ToolbarPanel.add(fillRectButton);
    ToolbarPanel.add(fillOvalButton);
    ToolbarPanel.add(splineButton);
    ToolbarPanel.add(polygonButton);
    ToolbarPanel.setBounds(0,0,100,300);
    ToolbarPanel.add(udefcolPanel);
    ToolbarPanel.add(udefdemcolPanel);
    udefcolPanel.add(redValue);
    udefcolPanel.add(redSlider);
    udefcolPanel.add(greenValue);
    udefcolPanel.add(greenSlider);
    udefcolPanel.add(blueValue);
    udefcolPanel.add(blueSlider);
    statusPanel.add(colorLabel);
    statusPanel.add(colorStatusBar);
    statusPanel.add(operationLabel);
    statusPanel.add(opStatusBar);
    statusPanel.add(cursorLabel);
    statusPanel.add(mouseStatusBar);
    colorStatusBar.setEditable(false);
    opStatusBar.setEditable(false);
    mouseStatusBar.setEditable(false);
    statusPanel.setBackground(statusBarColor);
    ToolbarPanel.setBackground(Color.white);
    drawPanel.setBackground(Color.white);
    add(statusPanel, "North");
    add(ToolbarPanel, "West");
    add(drawPanel, "Center");
    penButton.addActionListener(this);
    lineButton.addActionListener(this);
    eraserButton.addActionListener(this);
    clearButton.addActionListener(this);
    rectButton.addActionListener(this);
    ovalButton.addActionListener(this);
    fillRectButton.addActionListener(this);
    fillOvalButton.addActionListener(this);
    splineButton.addActionListener(this);
    polygonButton.addActionListener(this);
    blackButton.addActionListener(this);
    blueButton.addActionListener(this);
    redButton.addActionListener(this);
    greenButton.addActionListener(this);
    purpleButton.addActionListener(this);
    orangeButton.addActionListener(this);
    pinkButton.addActionListener(this);
    grayButton.addActionListener(this);
    yellowButton.addActionListener(this);
    userDefButton.addActionListener(this);
    redSlider.addAdjustmentListener(this);
    blueSlider.addAdjustmentListener(this);
    greenSlider.addAdjustmentListener(this);
    drawPanel.addMouseMotionListener(this);
    drawPanel.addMouseListener(this);
    // this.addMouseListener(this);
    // this.addMouseMotionListener(this);
    updateRGBValues();
    opStatusBar.setText("Pen");
    colorStatusBar.setText("Black");
    public void actionPerformed(ActionEvent e)
         penButton.setActionCommand("Pen");
         lineButton.setActionCommand("Line");
         eraserButton.setActionCommand("Eraser");
         rectButton.setActionCommand("Rectangle");
         ovalButton.setActionCommand("Oval");
         fillRectButton.setActionCommand("Filled Rectangle");
         fillOvalButton.setActionCommand("Filled Oval");
         if (e.getActionCommand() == "Pen")
         opStatus = PEN_OP;
         else if (e.getActionCommand() == "Line")
         opStatus = LINE_OP;
         else if (e.getActionCommand() == "Eraser")
         opStatus = ERASER_OP;
         else if (e.getActionCommand() == "Clear")
         opStatus = CLEAR_OP;
         else if (e.getActionCommand() == "Rectangle")
         opStatus = RECT_OP;
         else if (e.getActionCommand() == "Oval")
         opStatus = OVAL_OP;
         else if (e.getActionCommand() == "Filled Rectangle")
         opStatus = FRECT_OP;
         else if (e.getActionCommand() == "Filled Oval")
         opStatus = FOVAL_OP;
         else if (e.getActionCommand() == "Polygon")
         opStatus = POLY_OP;
         else if (e.getActionCommand() == "Spline")
         opStatus = SPLINE_OP;
         else if (e.getActionCommand() == "Black")
         colorStatus = 1;
         else if (e.getActionCommand() == "Blue")
         colorStatus = 2;
         else if (e.getActionCommand() == "Green")
         colorStatus = 3;
         else if (e.getActionCommand() == "Red")
         colorStatus = 4;
         else if (e.getActionCommand() == "Purple")
         colorStatus = 5;
         else if (e.getActionCommand() == "Orange")
         colorStatus = 6;
         else if (e.getActionCommand() == "Pink")
         colorStatus = 7;
         else if (e.getActionCommand() == "Gray")
         colorStatus = 8;
         else if (e.getActionCommand() == "Yellow")
         colorStatus = 9;
         else if (e.getActionCommand() == "User-Def")
         colorStatus = 10;
    initialPolygon = true;
    initialSpline = true;
    switch (opStatus)
    case PEN_OP : opStatusBar.setText("Pen");
    break;
    case LINE_OP : opStatusBar.setText("Line");
    break;
    case ERASER_OP: opStatusBar.setText("Eraser");
    break;
    case CLEAR_OP : clearPanel(drawPanel);
    break;
    case RECT_OP : opStatusBar.setText("Rectangle");
    break;
    case OVAL_OP : opStatusBar.setText("Oval");
    break;
    case FRECT_OP : opStatusBar.setText("Fill-Rectangle");
    break;
    case FOVAL_OP : opStatusBar.setText("Fill-Oval");
    break;
    case POLY_OP : opStatusBar.setText("Polygon");
    break;
    case SPLINE_OP: opStatusBar.setText("Spline");
    break;
    switch (colorStatus)
    case 1: colorStatusBar.setText("Black");
    break;
    case 2: colorStatusBar.setText("Blue");
    break;
    case 3: colorStatusBar.setText("Green");
    break;
    case 4: colorStatusBar.setText("Red");
    break;
    case 5: colorStatusBar.setText("Purple");
    break;
    case 6: colorStatusBar.setText("Orange");
    break;
    case 7: colorStatusBar.setText("Pink");
    break;
    case 8: colorStatusBar.setText("Gray");
    break;
    case 9: colorStatusBar.setText("Yellow");
    break;
    case 10: colorStatusBar.setText("User Defined Color");
    break;
    setMainColor();
    updateRGBValues();
    public void adjustmentValueChanged(AdjustmentEvent e)
    updateRGBValues();
    public void clearPanel(JPanel drawPanel2)
    opStatusBar.setText("Clear");
    Graphics g = drawPanel2.getGraphics();
    g.setColor(drawPanel2.getBackground());
    g.fillRect(0,0,drawPanel2.getBounds().width,drawPanel2.getBounds().height);
    public void penOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialPen)
    setGraphicalDefaults(e);
    initialPen = false;
    g.drawLine(prevx,prevy,mousex,mousey);
    if (mouseHasMoved(e))
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void lineOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialLine)
    setGraphicalDefaults(e);
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    initialLine=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(Orx,Ory,mousex,mousey);
    public void rectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialRect)
    setGraphicalDefaults(e);
    initialRect = false;
    if (mouseHasMoved(e))
    g.setXORMode(drawPanel.getBackground());
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void ovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialOval)
    setGraphicalDefaults(e);
    initialOval=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void frectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFRect)
    setGraphicalDefaults(e);
    initialFRect=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    public void fovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFOval)
    setGraphicalDefaults(e);
    initialFOval = false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void eraserOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    if (initialEraser)
    setGraphicalDefaults(e);
    initialEraser = false;
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    if (mouseHasMoved(e))
    g.setColor(mainColor.white);
    g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);
    mousex = e.getX();
    mousey = e.getY();
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    public void polygonOperation(MouseEvent e)
    if (initialPolygon)
    prevx = e.getX();
    prevy = e.getY();
    initialPolygon = false;
    else
    mousex = e.getX();
    mousey = e.getY();
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void splineOperation(MouseEvent e)
    if(initialSpline)
    initialSpline = false;
    public boolean mouseHasMoved(MouseEvent e)
    return (mousex != e.getX() || mousey != e.getY());
    public void setActualBoundry()
    if (mousex < Orx || mousey < Ory)
    if (mousex < Orx)
    OrWidth = Orx - mousex;
    drawX = Orx - OrWidth;
    else
    drawX = Orx;
    OrWidth = mousex - Orx;
    if (mousey < Ory)
    OrHeight = Ory - mousey;
    drawY = Ory - OrHeight;
    else
    drawY = Ory;
    OrHeight = mousey - Ory;
    else
    drawX = Orx;
    drawY = Ory;
    OrWidth = mousex - Orx;
    OrHeight = mousey - Ory;
    public void setGraphicalDefaults(MouseEvent e)
    mousex = e.getX();
    mousey = e.getY();
    prevx = e.getX();
    prevy = e.getY();
    Orx = e.getX();
    Ory = e.getY();
    drawX = e.getX();
    drawY = e.getY();
    OrWidth = 0;
    OrHeight = 0;
    public void mouseDragged(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : penOperation(e);
    break;
    case LINE_OP : lineOperation(e);
    break;
    case RECT_OP : rectOperation(e);
    break;
    case OVAL_OP : ovalOperation(e);
    break;
    case FRECT_OP : frectOperation(e);
    break;
    case FOVAL_OP : fovalOperation(e);
    break;
    case ERASER_OP: eraserOperation(e);
    break;
    public void mouseReleased(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : releasedPen();
    break;
    case LINE_OP : releasedLine();
    break;
    case RECT_OP : releasedRect();
    break;
    case OVAL_OP : releasedOval();
    break;
    case FRECT_OP : releasedFRect();
    break;
    case FOVAL_OP : releasedFOval();
    break;
    case ERASER_OP : releasedEraser();
    break;
    public void mouseEntered(MouseEvent e)
    updateMouseCoordinates(e);
    public void setMainColor()
    switch (colorStatus)
    case 1 : mainColor = Color.black;
    break;
    case 2: mainColor = Color.blue;
    break;
    case 3: mainColor = Color.green;
    break;
    case 4: mainColor = Color.red;
    break;
    case 5: mainColor = Color.magenta;
    break;
    case 6: mainColor = Color.orange;
    break;
    case 7: mainColor = Color.pink;
    break;
    case 8: mainColor = Color.gray;
    break;
    case 9: mainColor = Color.yellow;
    break;
    case 10: mainColor = userDefinedColor;
    break;
    public void releasedPen()
    initialPen = true;
    public void releasedLine()
    if ((Math.abs(Orx-mousex)+Math.abs(Ory-mousey)) != 0)
    // System.out.println("Line has been released....");
    initialLine = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    public void releasedEraser()
    initialEraser = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor.white);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    public void releasedRect()
    initialRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedOval()
    initialOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void releasedFRect()
    initialFRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedFOval()
    initialFOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillOval(drawX,drawY,OrWidth,OrHeight);
    public void updateMouseCoordinates(MouseEvent e)
    String xCoor ="";
    String yCoor ="";
    if (e.getX() < 0) xCoor = "0";
    else
    xCoor = String.valueOf(e.getX());
    if (e.getY() < 0) xCoor = "0";
    else
    yCoor = String.valueOf(e.getY());
    mouseStatusBar.setText("x:"+xCoor+" y:"+yCoor);
    public void updateRGBValues()
    udefRedValue = redSlider.getValue();
    udefGreenValue = greenSlider.getValue();
    udefBlueValue = blueSlider.getValue();
    if (udefRedValue > 255)
    udefRedValue = 255;
    if (udefRedValue < 0 )
    udefRedValue =0;
    if (udefGreenValue > 255)
    udefGreenValue = 255;
    if (udefGreenValue < 0 )
    udefGreenValue =0;
    if (udefBlueValue > 255)
    udefBlueValue = 255;
    if (udefBlueValue < 0 )
    udefBlueValue =0;
    redValue.setText(String.valueOf(udefRedValue));
    greenValue.setText(String.valueOf(udefGreenValue));
    blueValue.setText(String.valueOf(udefBlueValue));
    userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    userDefButton.setBackground(userDefinedColor);
    Graphics g = udefdemcolPanel.getGraphics();
    g.setColor(userDefinedColor);
    g.fillRect(0,0,800,800);
    public void mouseClicked(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case 9 : splineOperation(e);
    break;
    case 10 : polygonOperation(e);
    break;
    public void mouseExited(MouseEvent e)
    updateMouseCoordinates(e);
    public void mouseMoved(MouseEvent e)
    updateMouseCoordinates(e);
    public void mousePressed(MouseEvent e)
    updateMouseCoordinates(e);
    Edited by: eclipse on Feb 19, 2008 6:29 AM

    If you can't divide the class then you can't implement an MVC design methodology.
    This class is a giant mess and can be EASILY broken down into smaller classes. Seperate the visual components into their own classes. Create Model objects that contain the data behind your visual components.
    Split up your giant ActionListener into several smaller more specialized actionlisteners and create a Controller object that you can assign these listeners and models to. Allow the event handling to be done by the controller so it can propogate necessary data changes to the models, thus altering the Views.
    Thats it in a nutshell. It is not an easy answer.

  • There is anyone can convert applet code to application code?

    i got this applet code and would like to convert it to application code but don't know how.Anybody convert this please?
    thanks in advance.
    [email protected]
    //This program was completely written by Peter Wetsel.
    //If there are any questions about this code you
    //can email me at [email protected]
    //To get it to compile using jdk type "javac -nowarn battle.java".
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    import java.lang.*;
    public class battle extends java.applet.Applet implements Runnable {
         Color col;
         String message= new String("");//holds the message placed in the upper left
         String Status = new String("");
         String message2[]= new String[5];//holds the destroyed messages in order for repainting.
         int hits=0;//the total number of hits by the player
         int numDestroyed=0;//the number of ships destroyed by the player
         int battlepos[]=new int[4];//the 4 positions of the battleship
    int carrierpos[]=new int[5];//the 5 positions of the carrier
         int subpos[]=new int[3];//the 3 positions of the submarine
         int patrolpos[]=new int[2];//the 2 positions of the patrol boat
         int destroyerpos[]=new int[3]; //the 3 positions of the destroyer
         int guesses=0;// the number of guesses by the player
         int player[][]=new int[10][10]; //to hold the positions of the player.(not until version 2)
         int guessed[][]=new int[10][10]; //hold the places that have been guessed by the player
         int computer[][]=new int[10][10]; //holds where the computers ships are
         int battleshipHitCt, destroyerHitCt, subHitCt, patrolHitCt, carrierHitCt;//keeps the hit count for each of the ships
         boolean init=false;//false until play is pushed.
         boolean ok=false;//boolean that is true if current boat position chosen by random is ok(getcarrier(), etc.)
         boolean battleOK=true;//false when the type of ship is destroyed
         boolean patrolOK=true;//...
         boolean subOK=true;//...
         boolean destroyerOK=true;//...
         boolean carrierOK=true;//...
         boolean won=false;//true when the player has won
         int o;
    public static void main (String args [])
    Frame frame = new Frame () ;
    battle applet = new battle () ;
    frame.add (applet) ;
    applet.init () ;
    applet.paint(g);
    applet.start () ;
         public void getCarrier(){
              int x, y, dir; //will hold a random x & y coordinate(0-9), and a random direction(0-1)(N,E,S,W)
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              if(dir==0)
                   while(y<4){
                        y=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x][y-i]=1;
                        carrierpos=x*10+y-i;
              if (dir==1)
                   while(x>5){
                        x=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x+i][y]=1;
                        carrierpos[i]=(x+i)*10+y;
              if (dir==2)
                   while(y>5){
                        y=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x][y+i]=1;
                        carrierpos[i]=x*10+y+i;
              if (dir==3)
                   while(x<4){
                        x=(int)(10*Math.random());
                   for (int i=0; i<5; i++){
                        computer[x-i][y]=1;
                        carrierpos[i]=(x-i)*10+y;
         public void getBattle(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<3){
                             y=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>6){
                             x=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>6){
                             y=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<3){
                             x=(int)(10*Math.random());
                        for (int i=0; i<4; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<4; i++){
                        computer[x][y-i]=1;
                        battlepos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<4; i++){
                        computer[x+i][y]=1;
                        battlepos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<4; i++){
                        computer[x][y+i]=1;
                        battlepos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<4; i++){
                        computer[x-i][y]=1;
                        battlepos[i]=(x-i)*10+y;
         public void getSub(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<2){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>7){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>7){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<2){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<3; i++){
                        computer[x][y-i]=1;
                        subpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<3; i++){
                        computer[x+i][y]=1;
                        subpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<3; i++){
                        computer[x][y+i]=1;
                        subpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<3; i++){
                        computer[x-i][y]=1;
                        subpos[i]=(x-i)*10+y;
         public void getDestroyer(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<2){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>7){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>7){
                             y=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<2){
                             x=(int)(10*Math.random());
                        for (int i=0; i<3; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<3; i++){
                        computer[x][y-i]=1;
                        destroyerpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<3; i++){
                        computer[x+i][y]=1;
                        destroyerpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<3; i++){
                        computer[x][y+i]=1;
                        destroyerpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<3; i++){
                        computer[x-i][y]=1;
                        destroyerpos[i]=(x-i)*10+y;
         public void getPatrol(){
              int x, y, dir;
              x=(int)(10*Math.random());
              y=(int)(10*Math.random());
              dir=(int)(100*Math.random()/25);
              while(!ok){
                   ok=true;
                   x=(int)(10*Math.random());
                   y=(int)(10*Math.random());
                   dir=(int)(100*Math.random()/25);
                   if(dir==0)
                        while(y<1){
                             y=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x][y-i];
                             if (o==1){
                                  ok=false;
                   if (dir==1)
                        while(x>8){
                             x=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x+i][y];
                             if (o==1){
                                  ok=false;
                   if (dir==2)
                        while(y>8){
                             y=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x][y+i];
                             if (o==1){
                                  ok=false;
                   if (dir==3)
                        while(x<1){
                             x=(int)(10*Math.random());
                        for (int i=0; i<2; i++){
                             o=computer[x-i][y];
                             if (o==1){
                                  ok=false;
              if(dir==0)
                   for (int i=0; i<2; i++){
                        computer[x][y-i]=1;
                        patrolpos[i]=x*10+y-i;
              if (dir==1)
                   for (int i=0; i<2; i++){
                        computer[x+i][y]=1;
                        patrolpos[i]=(x+i)*10+y;
              if (dir==2)
                   for (int i=0; i<2; i++){
                        computer[x][y+i]=1;
                        patrolpos[i]=x*10+y+i;
              if (dir==3)
                   for (int i=0; i<2; i++){
                        computer[x-i][y]=1;
                        patrolpos[i]=(x-i)*10+y;
         public void run(){// to be in here so can compile
         public void init() {
              for (int i=0; i<10; i++){//initializes the guessed matrix to be all 2's(not been guessed)
                   for (int j=0;j<10; j++){
                        guessed[i][j]=2;
              for (int i=0; i<2; i++){//initializes array to be all zeros
                   patrolpos[i]=0;
              for (int i=0; i<2; i++){
                   destroyerpos[i]=0;
              for (int i=0; i<2; i++){
                   subpos[i]=0;
              for (int i=0; i<2; i++){
                   carrierpos[i]=0;
              for (int i=0; i<2; i++){
                   battlepos[i]=0;
              battleshipHitCt=0;//initialize all hit counts
              destroyerHitCt=0;
              subHitCt=0;
              patrolHitCt=0;
              carrierHitCt=0;
         //get all boat positions
              getCarrier();
              ok=false;
              getBattle();
              ok=false;
              getDestroyer();
              ok=false;
              getSub();
              ok=false;
              getPatrol();
         public void paint(Graphics g) { //this is the shots paint method... draws a line from its last position to its current position, basically
         if (!init && !won){//draws screen before play is pushed
                   g.setColor(col.white);
                   g.fillRect(0,0,600,320);
                   g.setColor(col.black);
                   g.fillRect(20,20,30,25);
                   g.setColor(col.white);
                   g.drawString("PLAY", 23,30);
                   g.setColor(col.black);
                   g.drawString("This is different that usual battleship, here the goal is",23,65);
                   g.drawString("to find all of the computers ships in the least number of guesses.",23,85);
                   g.drawString("<30 turns --- You have too much luck!", 23, 105);
                   g.drawString("31-50 turns --- Excellent!", 23, 125);
                   g.drawString(">=51 turns --- You have no skills!", 23, 145);
                   g.drawString("PRESS PLAY TO BEGIN", 23, 165);
              if (init && !won){//draws grid and messages
                   g.setColor(col.black);
                   g.fillRect(0,0,600,320); //makes big, black rectangle washover
                   g.setColor(col.white);
                   g.drawString("# of Guesses = " + guesses,500, 280);
                   for (int i=0; i<11; i++)
                        g.drawLine(20,20+i*28, 300, 20+i*28);
                   for (int i=0; i<11; i++)
                        g.drawLine(20+i*28,20,20+i*28,300);
                   char ch='A';
                   for (int i=0; i<10; i++){//draws letter accross the top
                        g.drawString(ch+" ",30+28*i,13);
                        ch++;
                   ch='1';
                   for (int i=0; i<9; i++){//draws numbers down the side
                        g.drawString(ch+" ",10,40+28*i);
                        ch++;
                   g.drawString("10", 6,290);
                   g.drawString(message,420,40);
                   for (int i=0; i<numDestroyed; i++){
                        g.drawString(message2[i], 305, 40+(i+1)*20);
                   g.setColor(col.black);
                   //next puts in any circles already guessed
                   for (int i=0; i<10; i++)
                        for (int j=0; j<10;j++){
                             if (guessed[i][j]==1)     {
                                  g.setColor(col.red);
                                  g.fillOval(i*28+30, j*28+30, 10,10);
                             if (guessed[i][j]==0)     {
                                  g.setColor(col.white);
                                  g.fillOval(i*28+30, j*28+30, 10,10);
         public boolean seeifahit(int x, int y){//sees if the shot was a hit or not
              if(computer[x][y]==1)
                   return true;
              return false;
         public String getshiptype(int x, int y){//returns the name of the ship that was hit
              for (int i=0;i<4; i++)
                   if (battlepos[i]==x*10+y){
                        battleshipHitCt++;
                        return "Battleship";
              for (int i=0;i<3; i++)
                   if (subpos[i]==x*10+y){
                        subHitCt++;
                        return "Submarine";
              for (int i=0;i<2; i++)
                   if (patrolpos[i]==x*10+y){
                        patrolHitCt++;
                        return "Patrol Boat";
              for (int i=0;i<5; i++)
                   if (carrierpos[i]==x*10+y){
                        carrierHitCt++;
                        return "Carrier";
              for (int i=0;i<3; i++)
                   if (destroyerpos[i]==x*10+y){
                        destroyerHitCt++;
                        return "Destroyer";
              return " ";
         public void gameOver(){//displays guesses and ends
              if (!won){
                   Graphics g = getGraphics() ;
                   g.setColor(col.black);
                   g.fillRect(0,0,600,320); //makes big, black rectangle washover
                   g.setColor(col.white);
                   g.drawString("YOU WIN!!", 200,100);
                   String out=new String("It took you "+guesses+" tries!");
                   g.drawString(out, 200,120);
                   g.drawString("Press refresh on your browser to play again", 200, 150);
                   won=true;
         public boolean destroyed(){
              if(battleshipHitCt==4 && battleOK)
                   battleOK=false;
                   return true;
              if(carrierHitCt==5 && carrierOK)
                   carrierOK=false;
                   return true;
              if(subHitCt==3 && subOK)
                   subOK=false;
                   return true;
              if(patrolHitCt==2 && patrolOK)
                   patrolOK=false;
                   return true;
              if(destroyerHitCt==3 && destroyerOK)
                   destroyerOK=false;
                   return true;
              return false;
         public boolean mouseDown(Event e, int x, int y) {//handles when a mouse key is pressed(either key)
              String type= new String("");
              if (!won){
                   message="";
                   Graphics g = getGraphics() ;
                   g.setColor(col.white);
                   int xindex, yindex, val;
                   if (x>20 && y>20 && y<300 && x<300 && init){
                        guesses++;
                        g.setColor(col.black);
                        g.fillRect(490,260, 550, 285);
                        g.setColor(col.white);
                        g.drawString("# of Guesses = " + guesses,500, 280);
                        g.setColor(col.black);
                        g.fillRect(419,30,580,95);
                        g.setColor(col.white);
                        xindex=(x-20)/28;//converts x coordinate into index(A-J) in form of (0-9)
                        yindex=(y-20)/28;//converst y coordinate into index(0-9)
                        val=guessed[xindex][yindex];
                        if (val==2){
                             if (seeifahit(xindex,yindex)){
                                  type=getshiptype(xindex, yindex);
                                  hits++;
                                  g.setColor(col.white);
                                  guessed[xindex][yindex]=1;
                                  if (!destroyed()){
                                       message=type + " Hit";
                                       g.drawString(message, 420, 40);
                                  else{
                                       g.setColor(col.white);
                                       message2[numDestroyed]=new String("");
                                       message2[numDestroyed]=type + "Destroyed";
                                       numDestroyed++;
                                       g.drawString(message2[numDestroyed-1] , 305, 40+(numDestroyed)*20);
                                  g.setColor(col.red);
                             else guessed[xindex][yindex]=0;
                             g.fillOval(xindex*28+30, yindex*28+30, 10,10);
    else {
                             g.setColor(col.white);
                             message="That has already been guessed";
                             g.drawString(message,420,40);
                   if (x>20 && x<40 && y>20 && y<40 && !init){
                        init=true;
                        paint(g);
                   if (hits>=17){
                        gameOver();
                        System.exit(0);
              return true;

    replace following in main method
    applet.paint(g); by
    repaint(); and
    applet.start() by
    // applet.start() at least compile your source code and if all runs the normal way it shoul be an application
    PS: i think there is a way in javac to tell it your source is an applicat. and not an applet

  • Imitating the add() function without actually adding a Applet object

    Okay, I have an instance of an object that ultimately extends Applet (not JApplet). I want this applet to paint itself onto another instance of JFrame without adding (performing the add(component) method) the applet instance.
    Note though that if I do add the applet to the JFrame, the object is painted correctly and everything works fine. But for some reasons specific to me (that I don't want to go into details with), I do not want to add the applet.
    I would want to do something like this:
    Applet instance = /* my instance */
    JFrame frame = /* my frame */
    JPanel pane = new JPanel(new BorderLayout()) {
      public void paint(Graphics g) { instance.paint(g) }
      public void update(Graphics g) { instance.update(g) }
    frame.add(pane);Using the above concept, the frame doesn't get any painting. Exactly what does the add method do that I'm not imitating here? I've tried looking through the source and I don't see much changing of the actual instance. I also tried setting the parent of the applet (using reflect) to my JPanel (above example), but that did nothing. I tried doing that since I thought the applet may have uses the getGraphics() method for getting a graphics to draw with. BTW, I do not have source code to the Applet instance: I'm trying to make this dynamic.
    Thanks in advance for any support
    Message was edited by:
    khaoz
    null

    There are 2 problems I can think of:
    1. Calling paint on heavyweight components does no drawing to the graphics object. You can see this if you try to use the java print API to print a heavyweight button or something
    2. I'm not sure that calling paint on Applet causes the applets children to get drawn.
    Your best bet might be to use the java.awt.Robot, do a screen scrape of your applet and then draw that in your frame.

  • How to add checkboxes to frame

    So I have two classes in my package. I am having trouble adding the checkbox group to my frame. I got it to add to my applet but I can not figure out how to add it to my frame. Here is what I have so far. When I run this program it puts the checkboxes in my applet and not in my frame.
    this is my painter class:
    package pt;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2006</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class painter extends Applet {
    private int xValue=-10, yValue=-10;
    MyFrame x;
    Checkbox Red, Black, Magenta, Blue, Green, Yellow;
    CheckboxGroup cbg;
    public void init()
    x= new MyFrame("Christie's Window");
    x.show();
    x.resize(250,100);
    cbg = new CheckboxGroup();
           Red = new Checkbox("Red", cbg,true);
           Black = new Checkbox("Black", cbg,false);
           Magenta = new Checkbox("Magenta",cbg,false);
           Blue = new Checkbox("Blue", cbg, false);
           Green = new Checkbox("Green", cbg, false);
           Yellow = new Checkbox("Yellow", cbg, false);
           add(Red);
           add(Black);
           add(Magenta);
           add(Blue);
           add(Green);
           add(Yellow);
         addMouseMotionListener(new MotionHandler(this));
    public void paint(Graphics g)
    g.drawString("Drag the mouse to draw", 10, 20);
    g.fillOval(xValue, yValue, 4,4);
    //Override Component class update method to allow all ovals
    // to remain on the screen by not clearing the background
    public void update(Graphics g)   { paint(g); }
    // set the drawing coordinates and repaint
    public void setCoordinates(int x, int y)
      xValue = x;
      yValue = y;
      repaint();
    // Class to handle only mouse drag events for the Drag applet
    class MotionHandler extends MouseMotionAdapter {
      private painter dragger;
      public MotionHandler(painter d)  { dragger = d; }
      public void mouseDragged( MouseEvent e)
        { dragger.setCoordinates( e.getX(), e.getY() );   }
        } and here is MyFrame class:
    package pt;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2006</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class MyFrame extends Frame {
    MyFrame(String x){
       super(x);
        public boolean handleEvent(Event evtObj) {
          if(evtObj.id==Event.WINDOW_DESTROY) {
            hide();
            return true;
          return super.handleEvent(evtObj);
    }

    here's your conversion, with listeners to change the color
    //import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    //public class painter extends Applet {
    class painter extends Frame {
    Color color = Color.RED;
    private int xValue=-10, yValue=-10;
    //MyFrame x;
    Checkbox Red, Black, Magenta, Blue, Green, Yellow;
    CheckboxGroup cbg;
    //public void init()
    public painter()
    //x= new MyFrame("Christie's Window");
    setTitle("Christie's Window");
    //x.show();
    //x.resize(250,100);
    setSize(600,400);
    setLocation(200,100);
    cbg = new CheckboxGroup();
           Red = new Checkbox("Red", cbg,true);
           Red.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Red.getState()) color = Color.RED;}});
           Black = new Checkbox("Black", cbg,false);
           Black.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Black.getState()) color = Color.BLACK;}});
           Magenta = new Checkbox("Magenta",cbg,false);
           Magenta.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Magenta.getState()) color = Color.MAGENTA;}});
           Blue = new Checkbox("Blue", cbg, false);
           Blue.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Blue.getState()) color = Color.BLUE;}});
           Green = new Checkbox("Green", cbg, false);
           Green.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Green.getState()) color = Color.GREEN;}});
           Yellow = new Checkbox("Yellow", cbg, false);
           Yellow.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Yellow.getState()) color = Color.YELLOW;}});
    Panel p = new Panel();
           p.add(Red);
           p.add(Black);
           p.add(Magenta);
           p.add(Blue);
           p.add(Green);
           p.add(Yellow);
    add(p,BorderLayout.NORTH);
         addMouseMotionListener(new MotionHandler(this));
    addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent we) { System.exit(0); }});
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(color);
    g.drawString("Drag the mouse to draw", 10, 75);
    g.fillOval(xValue, yValue, 4,4);
    //Override Component class update method to allow all ovals
    // to remain on the screen by not clearing the background
    public void update(Graphics g)   { paint(g); }
    // set the drawing coordinates and repaint
    public void setCoordinates(int x, int y)
      xValue = x;
      yValue = y;
      repaint();
    // Class to handle only mouse drag events for the Drag applet
    class MotionHandler extends MouseMotionAdapter {
      private painter dragger;
      public MotionHandler(painter d)  { dragger = d; }
      public void mouseDragged( MouseEvent e)
        { dragger.setCoordinates( e.getX(), e.getY() );   }
      public static void main(String[] args){new painter().setVisible(true);}
    }

  • Connection timed out, when server is present in  far-off place

    We have a web application on JBoss-3.2.3. It makes use of Applets. To paint the applet, a request is sent to a server using a HttpURLConnection. Evertyhing works fine when the browser(client) and the server are on the same network. However, if the client(browser) is in Australia and the server in India(i.e. long distance between server and client), then the Applet crashes with a Connection timed out exception. Any solution for this?
    The code looks something like:
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.connect();

    So I am facing the weirdest network/server problem ever!I have a customer which had a Supermicro server (Was there before me!). It was never used and they didn't know the password so i decided to format and re-install Windows Server 2012 R2 on it. I promoted it to a new domain and setup Windows Essentials so I could setup RDWeb for them quickly. They were up and running great. I also installed Trend Micro on the server and pushed it out to the client PC's. A little more info about my network before i get into the gritty. I have Brighthouse cable 35Mbps as an ISP with an ARRIS modem, a Ubiquiti Edgerouter Lite as my firewall and a cisco sg200-26 as my core switch. It's not a big location. We randomly started getting request timed out at the gateway level and the firewall level from outside and internet was dropping. We worked for weeks...
    This topic first appeared in the Spiceworks Community

  • Jsp:params help urgent

    hi all,
    i need to pass a lot of values to a applet from a JSP program and i came accross a method for it like Param in Applet Tag : example :
    <PARAM NAME="data" VALUE="
    3624 41.3
    6315 66.7
    4530 58.1
    3378 39.9
    5114 62.6
    4884 63.9
    5348 56.0
    4809 54.6
    4815 52.6
    4091 40.6
    4963 61.9
    4119 59.5
    5107 52.6
    4458 52.9
    4628 59.0
    4669 59.9
    3712 38.5
    3545 42.2
    3694 54.7
    5299 52.3
    4755 58.5
    4751 52.8
    4675 57.6
    3098 41.0
    4254 48.8
    4347 59.2
    4508 59.3
    5149 65.2
    4281 57.6
    5237 52.5
    3601 55.2
    4903 52.7
    3875 38.5
    5087 50.3
    4561 53.2
    3983 51.6
    4660 60.0
    4449 50.2
    4558 46.4
    3635 37.8
    4167 53.3
    3821 41.8
    4188 47.4
    4022 67.3
    3907 57.1
    4701 47.8
    4864 63.5
    3617 41.6
    4468 54.5
    4566 62.9
    ">But i do not have any idea of how do i retrive them in the applet . The number of values will differ each time the applet id loaded .Please help me with this ..Very Urgent. Thanks in advance .
    Chandooo

    hi , i am able to pass the data to the applet through the StringBuffer Object .Here is the JSP code which does the same :
    [ code ]
    <%
    int len =0;
    StringBuffer data = new StringBuffer();
    String ginfo = new String();
    if (r1>r2)
    loop:
    while(sub2.next()){
    while( sub1.next()){
    if(sub1.getString(1).equals(sub2.getString(1))){
    ginfo = sub1.getString(1)+"@"+ sub1.getString(2)+"@"+sub1.getString(3)+"@"+ sub2.getString(3)+"@"+sub1.getString(4);
    data.append(ginfo);
    data.append("\n");
    len++;
    sub1.beforeFirst();
    continue loop;
    sub1.beforeFirst();
    else
    loop1:
    while(sub1.next()){
    while( sub2.next()){
    if(sub2.getString(1).equals(sub1.getString(1))){
    ginfo = sub1.getString(1)+"@"+ sub1.getString(2)+"@"+sub1.getString(3)+"@"+ sub2.getString(3)+"@"+sub1.getString(4);
    data.append(ginfo);
    data.append("\n");
    len++;
    sub2.beforeFirst();
    continue loop1;
    sub2.beforeFirst();
    sub1.close();
    sub2.close();
    %>
    <jsp:plugin type="applet" code="Dot.class" width="500" height="500" align="center">
    <jsp:params>
    <jsp:param name="sub1" value="<%=s1%>" />
    <jsp:param name="sub2" value="<%=s2%>" />
    <jsp:param name="max" value="<%=max%>"/>
    <jsp:param name="len" value="<%=len%>"/>
    <jsp:param name="data" value="<%=data%>"/>
    </jsp:params>
    <jsp:fallback>
    Plugin tag OBJECT or EMBED not supported by browser, So please Download and Install the Plugin
    </jsp:fallback>
    </jsp:plugin>
    But the problem is ..the applet doesn't paint. the applet code is :
    double interval,xinterval1,yinterval1;
    double max;
    int len ;
    private String message = "Initializing";
    int x =0,i=0;
    String sub1,sub2,data;
    public void init() {
    sub1=getParameter("sub1");
    sub2=getParameter("sub2");
    max = Double.valueOf(getParameter("max")).doubleValue();
    data = getParameter("data");
    len = Integer.parseInt(getParameter("len"));
    interval = max/5;
    public void paint (Graphics g){
    String [][]xyf = new String [len][5];
    StringTokenizer tokenizer = new StringTokenizer(data);
    while(tokenizer.hasMoreTokens()){
    String valueOne = tokenizer.nextToken();
    StringTokenizer singleginfo = new StringTokenizer(valueOne,"@");
    x=0;
    while (singleginfo.hasMoreTokens()) {
    xyf[x++]=singleginfo.nextToken();
    i++;
    [/ code ]
    Can please tell me whats wrong with this ...

  • Coloring pixels

    I'm trying to create a basic paint program and my first question is what kind of GUI should i use to draw on, JPanel?
    The second question i have is how do i color an individual pixel?
    my idea for drawing:
    public void mouseClicked()
    if(isPenUp())
    penDown();
    else
    penUp();
    public void mouseMoved()
    if(isPenDown())
    colorPixel(color, getX(), getY());
    }thanks

    it depends on what kind of GUI you want. If you want a nice looking GUI you should go ahead and use JPanel to draw on, and some other Swing components for toolbars etc. If you want a simple GUI (and 1.1 compatability) you can just use Applet and paint your own interface.
    You color each pixel by simply taking an Image, getting it's graphics, and calling a few draw calls (drawRect, drawOval, etc..).
    I've written a simple applet that should get you started. It's just a simple painted-on interface that doesn't use any layout managers, but it isn't 1.1 compatible because I used Graphics2D and java.awt.event. Anyway, it should give you a boost:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    /* <applet code="Paint.class" width=400 height=400></applet> */
    public class Paint extends Applet implements MouseListener, MouseMotionListener {
         Rectangle canvas,color,colors[];
         Color c[];
         int w,h,sel,stroke,csize;
         Image buffer,drawing;
         public void init() {
              w = getSize().width;
              h = getSize().height;
              buffer = createImage(w,h);
              csize = 30;
              stroke = 10;
              canvas = new Rectangle(0,0,w,h-csize);
              color = new Rectangle(0,h-csize,w,csize);
              drawing = createImage(w,h-csize);
              c = new Color[] {
                   Color.black,Color.white,Color.red,
                   Color.orange,Color.yellow,Color.green,
                   Color.cyan,Color.blue,Color.magenta,Color.pink
              colors = new Rectangle[c.length];
              int x = 0;
              for (int j = 0;j < colors.length;j++) {
                   colors[j] = new Rectangle(x,h-csize,csize,csize);
                   x += csize;
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paint(Graphics g) {
              Graphics2D gfx = (Graphics2D)buffer.getGraphics();
              gfx.setColor(Color.white);
              gfx.fillRect(0,0,w,h);
              gfx.drawImage(drawing,0,0,null);
              gfx.setColor(Color.black);
              gfx.draw(canvas);
              int j;
              for (j = 0;j < c.length;j++) {
                   gfx.setColor(c[j]);
                   gfx.fill(colors[j]);
              gfx.setColor(Color.black);
              for (j = 0;j < colors.length;j++) {
                   gfx.draw(colors[j]);
              gfx.draw(color);
              gfx.drawRect(0,0,w-1,h-1);
              g.drawImage(buffer,0,0,null);
         public void update(Graphics g) {
              paint(g);
         public void mouseDragged(MouseEvent e) {
              if (canvas.contains(e.getX(),e.getY())) {
                   Graphics2D g = (Graphics2D)drawing.getGraphics();
                   g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                   g.setColor(c[sel]);
                   g.fillOval(e.getX()-(stroke/2),e.getY()-(stroke/2),stroke,stroke);
                   repaint();
         public void mousePressed(MouseEvent e) {
              mouseDragged(e);
              if (color.contains(e.getX(),e.getY())) {
                   for (int j = 0;j < colors.length;j++) {
                        if (colors[j].contains(e.getX(),e.getY())) {
                             sel = j;
                             break;
         public void mouseReleased(MouseEvent e) {}
         public void mouseClicked(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mouseMoved(MouseEvent e) {}
    }

  • Please enhance my code so that it can rotate text at the given angle

    public class ShapeDrawD extends JApplet
    Image img,imgback;
    static Image someimg2;
    ShapeCanvas canvas;
    ShapeCanvas backcanvas;
    public static int txtimgflag = -1,size,angle;
    public static String stringToDraw = "";
    public static int fontSize;
    public static String fontName;
    public static String fontStyle;
    public static String imgName;
    public static ImageObserver io;
    public static Shape shapeBeingDraggedtemp = null;
    public static Shape shapeBeingEdited = null;
    static Font fontmain;
    static Color colormain;
    static Color frocolor;
    public static String color;
    static Shape s = null;
    static JLabel l1 = new JLabel("");
    static String msg="";
    static JSObject js;
    public static URL url;
    public static URLConnection conn;
    public static String hostname;
    public static int port;
    static int addnew = 0;
    public static String str1;
    public static int str2;
    public static int zx, zy, oldy, zwidth,zheight;
    public static float scalingfactor;
    //Method which is called from Java Script taking parameters related to string and used for drawing strings
    public void printSomething(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    try
    addnew = 1;
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    angle=Integer.parseInt(ang);
    msg=lmsg;
    str1=lname;
    str2=Integer.parseInt(lstyle);
    txtimgflag=0;
    drawIt();
    repaint();
    catch(NumberFormatException nfe)
    System.out.println("Please Enter Proper Numeric values");
    public void strdelete()
    if(canvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("3inggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    canvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    else if(backcanvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("Deletinggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    backcanvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    //Method which is called from Java Script taking parameters related to Editing string and used for drawing Edited strings
    public void editText(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    addnew=0;
    //System.out.println("addnew "+ addnew);
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    msg=lmsg;
    angle=Integer.parseInt(ang);
    txtimgflag = 0;
    if(shapeBeingEdited != null && shapeBeingEdited instanceof StringShape)
    ((StringShape)shapeBeingEdited).Mystring=stringToDraw;
    ((StringShape)shapeBeingEdited).Mycolor=colormain;
    ((StringShape)shapeBeingEdited).Myfont=fontmain;
    ((StringShape)shapeBeingEdited).msg=msg;
    ((StringShape)shapeBeingEdited).frcolor=frocolor;
    ((StringShape)shapeBeingEdited).Siz=new Integer(size);
    ((StringShape)shapeBeingEdited).ang=new Integer(angle);
    drawIt();
    repaint();
    //Method Called from JavaScript used To Draw an Image takes Image name as param
    public void setImgName(String limgName)
    txtimgflag = 1;
    addnew = 1;
    imgName = limgName;
    someimg2 = getImage(getDocumentBase(),imgName);
    //System.out.println("Path -- >"+getDocumentBase() + imgName);
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(someimg2,1);
    try
    mt.waitForAll();
    catch(Exception e)
    e.printStackTrace();
    drawIt();
    repaint();
    public void setImageWidthHeight(String lparamwidth,String lparamHeight)
    int width = Integer.parseInt(lparamwidth);
    int height = Integer.parseInt(lparamHeight);
    if(shapeBeingEdited != null && shapeBeingEdited instanceof ImageShape)
    addnew=0;
    ((ImageShape)shapeBeingEdited).htwtimg(width,height);
    drawIt();
    repaint();
    /*Method to save Image on the Server .
    this methos makes a call to servlet and passes ImageIcon to it which is then saved
    as a jpeg file on given path
    public void uploadImage(BufferedImage fimg,BufferedImage bimg)
    try
    String path = "http://"+hostname+":"+port+"/javatool/sampleServlet";
    url = new URL(path);
    //System.out.println("after url");
    //System.out.println("Path--->"+path);
    conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
    BufferedImage bi = fimg;
    Image imgg=(Image)bi;
    ImageIcon imgc = new ImageIcon(imgg);
    ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
    out.writeObject(imgc);
    bi = null;
    imgg= null;
    imgc= null;
    out.flush();
    bi = bimg;
    imgg=(Image)bi;
    imgc = new ImageIcon(imgg);
    out.writeObject(imgc);
    out.flush();
    out.close();
    //System.out.println("file saved...");
    InputStream ins = conn.getInputStream();
    ObjectInputStream objin = new ObjectInputStream(ins);
    String msg = (String)objin.readObject();
    //System.out.println(msg.toString());
    catch (java.io.IOException io)
    //System.out.println("IOException ----->" + io);
    catch (Exception e)
    //System.out.psrintln("Exception " + e);
    }//End of Upload
    //Applet Init()
    public void init()
    js = JSObject.getWindow(this);
    hostname = getCodeBase().getHost();
    port = getCodeBase().getPort();
    //System.out.println("HostName -->" + hostname );
    //System.out.println("port -->" + port);
    JButton buttcolor = new JButton("Choose Color");
    JButton front = new JButton("Front");
    JButton back = new JButton("Back");
    /*JButton save = new JButton("Save");*/
    img = getImage(getDocumentBase(),getParameter("img"));
    //System.out.println(getDocumentBase() +" \\ "+getParameter("img"));
    canvas = new ShapeCanvas(img);
    imgback = getImage(getDocumentBase(),getParameter("imgback"));
    backcanvas = new ShapeCanvas(imgback);
    scalingfactor = (float) 1.0;
    // txtimgflag = 2;
    getContentPane().setLayout(null);
    getContentPane().setSize(325,300);
    io = (ImageObserver)this;
    addMouseListener(canvas);
    addMouseListener(backcanvas);
    JPanel top = new JPanel();
    JPanel bottom = new JPanel();
    top.add(front);
    top.add(back);
    top.setSize(425,50);
    top.setLocation(0,0);
    final JColorChooser colorchooser = new JColorChooser();
    final JFrame internalfrm = new JFrame("Please Choose the Colors");
    internalfrm.setSize(450,320);
    internalfrm.setVisible(false);
    internalfrm.getContentPane().add(colorchooser);
    canvas.setSize(425,370);
    canvas.setLocation(0,50);
    backcanvas.setSize(425,370);
    backcanvas.setLocation(0,50);
    backcanvas.setVisible(false);
    bottom.setLayout(null);
    buttcolor.setLocation(175,10);
    buttcolor.setSize(120,30);
    /*save.setLocation(220,10);
    save.setSize(120,30);*/
    l1.setLocation(10,45);
    l1.setSize(300,30);
    bottom.add(l1);
    bottom.add(buttcolor);
    /*bottom.add(save);*/
    bottom.setSize(425,100);
    bottom.setLocation(0,420);
    bottom.setBackground(Color.lightGray);
    getContentPane().add(top);
    getContentPane().add(bottom);
    getContentPane().add(backcanvas);
    getContentPane().add(canvas);
    //sets Background of two panels i.e front and back
    colorchooser.getSelectionModel().addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    canvas.setBackground(colorchooser.getColor());
    backcanvas.setBackground(colorchooser.getColor());
    //Shows Color Chooser
    buttcolor.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    internalfrm.setVisible(true);
    //Show back panel and hide front
    back.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    canvas.setVisible(false);
    backcanvas.setVisible(true);
    //backcanvas.repaint();
    //Show front panel and hide back
    front.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    backcanvas.setVisible(false);
    canvas.setVisible(true);
    *Save Image a call to UploadIamge
    save.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    uploadImage(canvas.bimg,backcanvas.bimg);
    drawIt();
    repaint();
    } //End of Applet Init();
    //Generates a Action Event calling ActionPerformed
    public void drawIt()
    ActionEvent evt=new ActionEvent(this,1,"HTML");
    if(canvas.isVisible())
    canvas.actionPerformed(evt);
    else
    backcanvas.actionPerformed(evt);
    //Paint of Applet
    public void paint(Graphics g)
    super.paint(g);
    //Update of Applet
    public void update(Graphics g)
    paint(g);
    //A panel Implemented to have Images Drawn on it
    static class ShapeCanvas extends JPanel implements ActionListener, MouseListener, MouseMotionListener,Runnable
    ArrayList shapes = new ArrayList();
    Color currentColor = Color.red;
    Image limg;
    BufferedImage bimg = new BufferedImage(430,400,BufferedImage.TYPE_INT_ARGB);
    Thread t = new Thread(this);
    ShapeCanvas(Image img)
    limg = img;
    addMouseListener(this);
    addMouseMotionListener(this);
    this.setBackground(Color.white);
    // t.start();
    zx = this.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);
    System.out.println("The parameter are"+zwidth+"and"+zheight);
    t.start();
    public void run()
    try
    for(int i=0;i<25;i++)
    repaint();
    t.sleep(250);
    repaint();
    catch(InterruptedException iee)
    public void updateComponent(Graphics g)
    paintComponent(g);
    public void deleteit(Shape shapetodelete)
    if(shapeBeingEdited != null)
    shapes.remove(shapeBeingEdited);
    repaint();
    public void paintComponent(Graphics go)
    //System.out.println("Called");
    super.paintComponent(go);
    go.drawImage(bimg,0,0,this);
    Graphics g = bimg.getGraphics();
    g.setColor(getBackground());
    g.drawRect(0,0,getSize().width,getSize().height);
    g.fillRect(0,0,getSize().width,getSize().height);
    g.drawImage(limg,0,0,this);
    /*zx = limg.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);*/
    zwidth *= scalingfactor;
    zheight *= scalingfactor;
    zx -= zwidth / 2;
    zy -= zheight /2;
    System.out.println("The values are"+zwidth);
    g.drawImage(limg, zx, zy, zwidth, zheight, this);
    int top = shapes.size();
    for (int i = 0; i < top; i++)
    s = (Shape)shapes.get(i);
    s.draw(g);
    g.dispose();
    go.dispose();
    public void actionPerformed(ActionEvent evt)
    //System.out.println(evt.getActionCommand());
    if(addnew == 1)
    //System.out.println("in new obj addnew "+ addnew);
    currentColor=Color.decode("1024");
    if(txtimgflag==0)
         System.out.println("string Function called");
    addShape(new StringShape(stringToDraw,fontmain,colormain,frocolor,msg,size,angle,str1,str2));
    else if(txtimgflag == 1)
    System.out.println("image function called");
    addShape(new ImageShape(someimg2));
    else if(txtimgflag==2)
    addShape(new ImageString(stringToDraw,fontmain,colormain,angle,size));
    System.out.println("txtimgflag in if else="+txtimgflag);
    else if(txtimgflag==3)
    addShape(new StyledString(stringToDraw,colormain,angle,size,str1,str2));
    System.out.println("txtimgflag in if else="+txtimgflag);
    repaint();
    void addShape(Shape shape)
    shape.setColor(currentColor);
    if(txtimgflag == 0)
    shape.reshape(150,80,100,20);
    shapes.add(shape);
    else if(txtimgflag == 1)
    shape.reshape(150,50,shape.width,shape.height);
    shapes.add(shape);
    else if(txtimgflag == 2)
    shape.reshape(150,50,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    else if(txtimgflag == 3)
    shape.reshape(150,60,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    repaint();
    Shape shapeBeingDragged = null;
    int prevDragX;
    int prevDragY;
    public boolean handleEvent (Event e)
    System.out.println("In zooming section");
    switch (e.id)
    case (Event.MOUSE_DOWN):
    oldy = e.y;
    return super.handleEvent(e);
    case (Event.MOUSE_UP):
    if (oldy > e.y)
    scalingfactor += (float) .1;
    else scalingfactor -= (float) .1;
    if (scalingfactor > (float) 5.0)
    scalingfactor = (float)5.0;
    if (scalingfactor < (float) .1)
    scalingfactor = (float).1;
    oldy = e.y;
    repaint();
    return super.handleEvent(e);
    default:
    return super.handleEvent(e);
    public void mousePressed(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingDragged = s;
    shapeBeingDraggedtemp =s;
    shapeBeingEdited = s;
    prevDragX = x;
    prevDragY = y;
    // shapeBeingEdited = s;
    if(shapeBeingEdited instanceof ImageShape)
    try
    Object obj[] = new Object[2];
    obj[0]=new Integer(((ImageShape)shapeBeingEdited).width);
    obj[1]=new Integer(((ImageShape)shapeBeingEdited).height);
    js.call("setValuesimg",obj);
    System.out.println("found Image shape");
    catch (JSException ex)
    else if(shapeBeingEdited instanceof StringShape)
    try
    String foreColor=Integer.toHexString(((StringShape)shapeBeingEdited).Mycolor.getRGB() );
    foreColor=( foreColor.substring(2)).toUpperCase();
    String backColor=Integer.toHexString(((StringShape)shapeBeingEdited).frcolor.getRGB() );
    backColor=( backColor.substring(2)).toUpperCase();
    //System.out.println("found string shape");
    Object obj[] = new Object[7];
    obj[0] = ((StringShape)shapeBeingEdited).Mystring;
    obj[1] = ((StringShape)shapeBeingEdited).Myfont.getFontName();
    obj[2] = foreColor;
    obj[3] = ((StringShape)shapeBeingEdited).msg;
    obj[4] = backColor;
    obj[5] = ((StringShape)shapeBeingEdited).Siz;
    obj[6] = ((StringShape)shapeBeingEdited).ang;
    js.call("setValues",obj);
    catch (JSException ex)
    else if(shapeBeingEdited instanceof ImageString)
    System.out.println("bulls eye");
    if (evt.isShiftDown())
    shapes.remove(s);
    shapes.add(s);
    repaint();
    if(evt.isAltDown())
    shapes.remove(s);
    repaint();
    else
    l1.setText("");
    if(evt.isControlDown())
    if(s instanceof ImageShape)
    if(evt.getButton() == MouseEvent.BUTTON1)
    s.htwt((s.width+1),(s.height+1));
    repaint();
    else if(evt.getButton() == MouseEvent.BUTTON3)
    s.htwt((s.width-1),(s.height-1));
    repaint();
    return;
    }//end of if
    else
    //shapeBeingEdited = null;
    public void mouseDragged(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null)
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    prevDragX = x;
    prevDragY = y;
    repaint();
    /*if(globalGrahics == null)
    System.out.println("globalGrahics is null ");
    globalGrahics = this.getGraphics();
    else
    globalGrahics.setColor(Color.CYAN);
    globalGrahics.drawRect(shapeBeingEdited.left,shapeBeingEdited.top,shapeBeingEdited.width+10,shapeBeingEdited.height);
    public void mouseReleased(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null) {
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
    shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
    shapeBeingDragged.top + shapeBeingDragged.height < 0 )
    //shapes.remove(shapeBeingDragged);
    if(x <=20 || y <= 20 || x >340 || y >330)
    shapeBeingDragged.left = (150);
    shapeBeingDragged.top = (100);
    repaint();
    shapeBeingDragged = null;
    repaint();
    public void mouseEntered(MouseEvent evt){repaint();}
    public void mouseExited(MouseEvent evt){}
    public void mouseMoved(MouseEvent evt)
    if(evt.isControlDown())
    l1.setText("Left Click on Image to Zoom in , Right to Zoom out");
    else if(evt.isAltDown())
    l1.setText("Click on Image or Text to Delete");
    else if(evt.isShiftDown())
    l1.setText("Click on Image to bring it forward");
    else
    l1.setText("");
    public void mouseClicked(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if(evt.getClickCount()>=2)
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingEdited = s;
    }//end of shapeCanvas
    static abstract class Shape
    int left, top;
    int width, height;
    Color color = Color.white;
    void reshape(int left, int top, int width, int height)
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
    void htwt(int width,int height)
    this.width = width;
    this.height = height;
    void moveBy(int dx, int dy)
    left += dx;
    top += dy;
    void setColor(Color color)
    this.color = color;
    boolean containsPoint(int x, int y)
    if (x >= left && x < left+width && y >= top && y < top+height)
    return true;
    else
    return false;
    abstract void draw(Graphics g);
    }//end of abstarct shape class
    static class StringShape extends Shape
    String Mystring;
    Font Myfont ;
    Color Mycolor;
    Color frcolor;
    String msg="",font;
    Integer Siz,ang;
    int font_size;
    int w,size,angle,w1,style;
    int speed= 12;
    StringShape(String lstr,Font lfont,Color lcolor,Color lfcolor,String lmsg,int lsiz,int lang,String lfon,int lsty)
    Mystring = lstr;
    Myfont = lfont;
    Mycolor = lcolor;
    frcolor = lfcolor;
    size=lsiz;
    msg = lmsg;
    angle=lang;
    Siz= new Integer(lsiz);
    style=lsty;
    font=lfon;
    System.out.println("In the String shape");
    int ShiftNorth(int p, int distance)
    return (p - distance);
    int ShiftSouth(int p, int distance)
    return (p + distance);
    int ShiftEast(int p, int distance)
    return (p + distance);
    int ShiftWest(int p, int distance)
    return (p - distance);
    BufferedImage bimg,temp,bimg1,bimg2,bimg3;
    void draw(Graphics g)
    g.setColor(Mycolor);
    g.setFont(this.Myfont);
    int wt=g.getFontMetrics().stringWidth(Mystring);
    int ht=g.getFontMetrics().getHeight();
    this.htwt(wt,ht);
    int h1=size ;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    int w2=g.getFontMetrics().stringWidth(Mystring);
    int len=Mystring.length();
    int w1=(w2*len);
    this.htwt(w1,w2);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    if(msg.equals("outlined"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg1 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg1.getGraphics();
    gimg = (Graphics2D)lgimg;
    System.out.println("Message --> " + msg);
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    else if(msg.equals("segment"))
    System.out.println("Message --> " + msg);
    int w = (g.getFontMetrics()).stringWidth("Segment");
    int h = (g.getFontMetrics()).getHeight();
    int d = (g.getFontMetrics()).getDescent();
    g.setColor(Mycolor);
    g.drawString(this.Mystring, (left+5), (top+Myfont.getSize()));
    g.setColor(frcolor);
    for (int i = 0; i < h; i += 3)
    g.drawLine((left+5), (top+Myfont.getSize()) + d - i, (left+wt) + w, (top+Myfont.getSize()) + d - i);
    else if(msg.equals("3d"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg2 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg2.getGraphics();
    gimg = (Graphics2D)lgimg;
    Color top_color = new Color(200, 200, 0);
    System.out.println("Message --> " + msg);
    for (int i = 0; i < 5; i++)
    gimg.setColor(top_color);
    gimg.drawString(this.Mystring, ShiftEast((left+4), i), ShiftNorth(ShiftSouth((top+Myfont.getSize()), i), 1));
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftWest(ShiftEast((left+4), i), 1), ShiftSouth((top+Myfont.getSize()), i));
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftEast((left+4), 5), ShiftSouth((top+Myfont.getSize()), 5));
    g.drawImage(bimg2,left+10,top,null);
    else if(msg.equals("flow"))
    System.out.println("Message"+msg);
    int len1=Mystring.length();
    int lsize=size;
    int lleft =25;
    int ltop = g.getFontMetrics().getHeight();
    w1=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("The value of w1 is"+w1);
    for(int j=0;j<Mystring.length();j++)
         w1=w1+size;
         System.out.println("Size"+w1);
    bimg3 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg3.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(new Font(font,style,lsize));
    gimg.setColor(Mycolor);
    for (int i = 0; i<Mystring.length(); i++)
    gimg.setFont(new Font(font,style,lsize));
    ltop= ltop+5;
    gimg.drawString(""+Mystring.charAt(i),lleft,ltop);
    //gimg.drawRect(lleft,ltop-20,gimg.getFontMetrics().charWidth(Mystring.charAt(i)),gimg.getFontMetrics().getHeight());
    lleft=lleft+gimg.getFontMetrics().charWidth(Mystring.charAt(i));
    lsize = lsize + 5;
    g.setColor(Mycolor);
    // g.drawRect(left+5,top,bimg.getWidth(),bimg.getHeight());
    g.drawImage(bimg3,left+5,top,null);
    else
         // g.drawString(this.Mystring,(left+5),(top+Myfont.getSize()));
    gimg.drawString(Mystring,30,10);
    g.drawImage(bimg,left+10,top,null);
    }//end of Draw Function
    static class ImageShape extends Shape
    Image someimg;
    ImageShape(Image lsomeimg)
    someimg = lsomeimg;
    width = someimg.getWidth(null);
    height = someimg.getHeight(null);
    System.out.println("constr width "+width+ " height"+ height);
    this.htwtimg(width,height);
    void htwtimg(int width,int height)
    this.width = width;
    this.height = height;
    System.out.println("its from image");
    void draw(Graphics g)
    g.drawImage(this.someimg,left,top,width,height,io);
    }//END OF IMageShape Class
    static class ImageString extends Shape
    String bstring;
    int ang,siz;
    Font lfont;
    Color lcolor;
    ImageString(String istr,Font lfon,Color lclr,int lang,int lsiz)
         bstring=istr;
         ang=lang;
         siz=lsiz;
         lfont=lfon;
         lcolor=lclr;
    BufferedImage bimg,temp;
    public void draw(Graphics g)
    int h=siz;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);
    System.out.println("Font is"+lfont);
    gimg.setColor(lcolor);
    int w=g.getFontMetrics().stringWidth(bstring);
    System.out.println("tWidth"+w+"theight"+h);
    int len=bstring.length();
    int w1=(w*len);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);

    can you tell in short what are you doing and what you wish to do.

  • Mysterious null pointers during Applet.paint(g)

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

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

  • Java graphics app prob regarding painting........ app does NOT use applets

    Hi ,
    I basically want to write a java graphics game application ......At this point in time all I want to do is add a green rectangle to the content pane.......I can do this but I want to stick with OO concepts so I have various classes......the thing is ....when a user resizes the window the graphic I have painted dissapeared
    I will show the classes I have used and the code below......I want to do the program conforming to the way I was tought java which is to have a main controlling class that orchestrates communication between unrelated classes and their methods. In addition to my question if anyone sees stuff fundementally wrong with my code and has a better solution please feel free to enlighten me :-)
    main controlling class:
    import java.awt.Graphics;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class PoolApp {
    public PoolApp() {
    //creates new gamescreen object
    GameScreen aScreen = new GameScreen(this);
    public static void main(String[] args) {
    PoolApp poolApp1 = new PoolApp();
    public Graphics getPaintedTable(GameScreen aGameScreen) {
    Paint aPaint = new Paint(this);
    Graphics tblObj = aPaint.getTbleGraphic(aGameScreen);
    return tblObj;
    ------end main controlling class
    ------TLayer Class start
    import javax.swing.*;
    /* The purpose of this class was to create a generic frame that would
    be inherited from all screen classes ...I initially had this creating a black background that would be inherited from child classes but that created
    more problems when the screen was resized by one of the child classes*/
    public class TLayer extends JFrame {
    public TLayer() {
    -----TLayer Class end
    -----GameScreen class start--------
    public class GameScreen extends TLayer{
    private PoolApp thePoolApp;
    public GameScreen(PoolApp aPoolApp) {
    thePoolApp = aPoolApp; //set a reference from here to the controlling PoolApp initGameScreen(); //initialise and show GameScreen .....screen
    public void initGameScreen() {
    this.setSize(800,600);
    this.show();
    //now make a request to the poolapp controlling class to ask for a painted green table and get the paint class to paint it to screen
    thePoolApp.getPaintedTable(this);
    ----GameScreen class end------------
    ----PaintScreen class start-------------
    PoolApp thePoolApp;
    public Paint() {
    public Paint(PoolApp apoolApp) {
    thePoolApp = apoolApp;
    public Graphics getTbleGraphic(GameScreen aGameScreen) {
    Container theCont = aGameScreen.getContentPane(); //assign the gamescreen content pane to a container
    theCont.setSize(200,200); //set a viewable size to the container
    Graphics thetbl = theCont.getGraphics(); //get container graphics context and assign it to a graphics object
    thetbl.setColor(Color.green); //color the object
    thetbl.fillRect(30,30,20,60); //fill the rectangle
    return thetbl; //return the object
    ---PaintScreen class end---------------
    This code actually draws the green rectangle to the gamescreen from the paint class .......so it works to a degree! ......whenever I resize the window the painted image dissapears, could anyone suggest a way around this also ...am I going about this the correct way? Im open to making mass changes to better the program ......the only thing I do not want is to use applets! .....as I want to learn the fundementals of custom painting my stuff
    Any help is much needed and appreciated
    David

    Hi .....I managed to fix my problem .....but I have really had to get my head around method overiding! ......Your advice is taken onboard ...also Im going to try and find a straight forward diagram of the java graphics heirrachy ......well the parts that are reasnable to what Im doing ......Also from what I know and what you have said yes threads would definately be the way to go as far as animation and paintings concerned...I plan to do some serious research on that as I progress.
    I am going to post my basic working program ........I was wandering if you think this is an effiecent way I have done this? or if you could make any recommendations? its just I dont want to adopt this approach and find its no good when I get further into the programs development :-)) anyway heres the code :
    ------Class PoolApp start--------------
    public class PoolApp {
      public PoolApp() {
        GameScreen aGScreen = new GameScreen(this);
      public static void main(String[] args) {
        PoolApp poolApp1 = new PoolApp();
    }------Class PoolApp end--------------
    ------Class TLayer start--------------
    import javax.swing.*;
    import java.awt.Graphics;
    public class TLayer extends JFrame {
      public TLayer() {
         System.out.println("In TLayer default constructor");
         this.setSize(800,600);
    }------Class TLayer end--------------
    ------Class GameScreen start--------------
    import java.awt.Graphics;
    public class GameScreen extends TLayer {
      PoolApp thepoolApp;
      Table theTable;
      Graphics g;
      public GameScreen() {
       System.out.println("In gamescreen default constructor table");
      public GameScreen(PoolApp apoolApp) {
      thepoolApp = apoolApp;
      System.out.println("In gamescreen  constructor 2");
      addTable();
    public void addTable() {
    System.out.println("in addTable");
    this.show();
    //theTable = new Draw(this);
    //theTable.setTable();
    //theTable.paint(g);
    public void paint(Graphics g) {
         System.out.println("In Gamescreen paint ");
         theTable = new Table(this);
         theTable.paint(g);
    public void update(Graphics g) {
        System.out.println("In Gamescreen update ");
        theTable = new Table(this);
        theTable.paint(g);
    }------Class GameScreen end--------------
    ------Class Table start--------------
    import java.awt.Graphics;
    import java.awt.Container;
    import java.awt.Color;
    public class Table extends TLayer{
      GameScreen thegameScreen;
      public Table() {
          System.out.println("In Table default constructor");
      public Table(GameScreen agameScreen) {
        thegameScreen = agameScreen;
        System.out.println("In Table 2nd constructor");
      public void paint(Graphics theGraphic) {
        System.out.println("In Table paint ");
        Container tablecont = thegameScreen.getContentPane();
        theGraphic = tablecont.getGraphics();
        theGraphic.setColor(Color.green);
        theGraphic.fillRect(310,220,180,80);
      public void update(Graphics theGraphic) {
           System.out.println("In Table update");
       paint(theGraphic);
    }------Class Table end--------------
    To be honest I would rather have created a table object then added it to the content pane ....but when i did it that way ......and I resized the screen the green table graphic dissapeared .....I would also have prefered all painting of the table to be done in the table class but I had the same problem of the graphic dissapearing when the window was resized and this is the best solution I have come up with as yet ....:-) .....any recommendations are greatly appreciated
    Thanks
    David

Maybe you are looking for

  • When to Use XSLT,Java or Graphical Mapping

    Hi Friends,    Could any one please give me a clear picture on when to use Java/XSLT/Graphical Mappings. Which mapping should be used in which case. Regards, Shyam

  • How to manage empties Deposite Article in IS-Retail

    Hi Experts, I have a requirement as follows for deposit articles : My client is starting a retail business in which he wants to maintain deposit article like crates which are returnable to vendor. At the time of buying main<full> article, vendor will

  • ISSUE with accessing Printer on the DMZ !!

    Hi, We are facing issues while accesing the printer in the DMZ interface from inside interface.The issue is happening when we are adding a printer to a new desktop. The printer is added via print server.The issue started happening after the server te

  • Iphone 3g, os4 automatically going into recovery mode

    hey when i first upgraded to os4 i had no problems i upgraded the day it came out, and as of 20/7 at random times my phone keeps switching itself off, and i have no access to anything, nothing even comes up on the screen the only way ive found to fix

  • Can't sign in to yahoomail

    Anybody knows why I can't sign in to my yahoomail after I upgraded it to iOS6? It keeps looping back to signing in window...