PaintComponent help

I guess my confusion comes from not really understanding when paintComponent method is called. I am trying to draw a polygon on an image(in a JLabel) AFTER the image is displayed. I wrote the following small extension to JLabel(notice the I call paintComponent from drawRegion):
class NVOImageMap extends JLabel {
public int raLength;
public int decLength;
final Color bg = Color.yellow;
final Color fg = Color.yellow;
public void NVOImageMap() {
setBackground(bg);
setForeground(fg);
public void drawRegion(int [] x, int [] y){
Graphics g = this.getGraphics();
// g.setColor(Color.yellow);
// g.drawPolygon(x, y, x.length);
this.paintComponents(g,x,y);
public void paintComponents(Graphics g,int [] x, int[] y) {
super.paintComponent(g); //clears the background
g.setColor(Color.yellow);
g.drawPolygon(x, y, x.length);
and in my main program I have
backGround.setIcon("background.gif");
<code to get some region>
backGround.drawRegion(x,y);
what happens when this method is invoked is the polygon appears for a split second and then disappears. Can someone explain to me why this is happening?.

Seems weird. Just some ideas:
You must never call 'paintComponent' by yourself. Just overwrite that method like:
public void paintCompoenent( Graphics g ) {
super.paintComponent ( g );
myDraw ();
to force a redraw just call 'repaint ();' in your main program. The Swing renderer will then call 'paintComponent' recursively down all children of 'contentPane'

Similar Messages

  • This paintComponent Method is Annoying - HELP

    ok, I think I touched upon this problem sometime earlier, however I face a larger problem which I've been trying to solve by a different and simpler means but I get nothin.
    I have a paintComponent method which DRAWS lines, strings and shapes that get PAINTED on to a JFrame all good and well.
    Now, because of the amount of lines, strings and shapes I have on this "paintComponent", I want to put it in a class of its own. and THEN call it from the class it was in.
    So I want to create a new class, just for the paintComponent.
    Now, I've tried Numerous ways of trying to call it from another class but it just comes up as a blank screen. Oh and no I am not calling it directly too.
    Does anyone know where I am going wrong?
    help would be very much appreciated.

    ok LETS do this.
    class beep
    I call the paintComponent here to paint my JFrame BUT HOW!
    class drawingBoard----------------------------------------------------
    // create a rectangle called 'therectangle';
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(therectangle)
    g2.drawString("", 100, 100)
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM

  • Can anyone help with PaintComponent???

    Can someone give me a bit of backgroubd on the paintComponent method in a JPanel?
    I am under the impression that it is called by paint(), and that paint is only called when the screen needs to be refresed.
    However, in my program, paintComponenet is calling over and over continiuously.
    I forced a nullPointerException in order to get a stack trace, and none of my classes are lised in it (except for the one with the paintComponent method).
    Under what circumstaces would the panel constantly call this method?

    This section on "Painting" from the Swing tutorial might help:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to continue with the "Working With Graphics" link at the bottom.

  • PaintComponent is slow - help

    I have the following code for painting a image on to screen. I keep updating the image continuously. This application is slow.
    I read that using active rendering/ BufferStrategy will be faster. but i am not able to find any examples for the same but i could not find any examples for the same.
    If i put the same code in paint() then there is flickering ..
    Appreciate your comments on how i could increase the performance of the application.
    Thanks in advance.
    <code>
    import java.awt.*;
    import javax.swing.JPanel;
    public class PaintPanel extends JPanel
    public PaintPanel()
    setPreferredSize(new Dimension(800, 600));
    revalidate();
    objInsets = getInsets();
    iHeight = getHeight();
    iWidth = getWidth();
    iPaintableWidth = iWidth - objInsets.right - objInsets.left - 1;
    iPaintableHeight = iHeight - objInsets.top - objInsets.bottom -1;
    boolStartImageDisplay=true;
    repaint();
    public void updatePicture(PictData pictData)
    this.pictData = pictData;
    int w = pictData.getRight() - pictData.getLeft() + 1;
    int h = pictData.getBottom() - pictData.getTop() + 1;
    int y = pictData.getTop();
    int x = pictData.getLeft();
    repaint(x,y,w,h);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    // Start Image Display so paint the background BLACK.
    if (boolStartImageDisplay == true) {
    g.setColor(Color.BLUE);
    g.fillRect(objInsets.left, objInsets.top, iPaintableWidth, iPaintableHeight);
    boolStartImageDisplay = false;
    } else if (this.pictData != null) {
    if (this.pictData != null) {
    this.m_image = MyUtil.getImage(this.pictData); //get the image from the pictData object.
    this.pictData = null;
    g.drawImage(this.m_image, objInsets.left, objInsets.top, this);
    private Insets objInsets = getInsets();
    private int iHeight = getHeight();
    private int iWidth = getWidth();
    private int iPaintableWidth = iWidth - objInsets.right - objInsets.left - 1;
    private int iPaintableHeight = iHeight - objInsets.top - objInsets.bottom -1;
    private PictData pictData = null;
    private boolean boolStartImageDisplay=false;
    private Image m_image = null;
    public static void main(String args[]) {
    java.awt.Frame f = new java.awt.Frame();
    PaintPanel c = new PaintPanel ();
    JScrollPane scroll = new JScrollPane (c);
    f.add("Center", scroll );
    f.setTitle("My PaintPanel");
    c.setSize(800, 600);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    f.pack();
    f.show();
    try {
    c.repaint();
    } catch (Exception e) {
    e.printStackTrace();
    </code>

    "I keep updating the image continuously"What? I guess your loading images from somewhere and
    then calling the repaint method on the frame. This is
    most likely the slow part of your program. Look at the
    MemoryImageSource object. In the javadoc there's some
    code animating an image included.I get the stream of data from a different machine, from which i create a BufferedImage and use this image to drawImage(..)
    in normal conditions the performance is ok but When the mouse is moved continuously the image does not get updated soon enough. I guess this is because both the (mouse event and the image updation) runs on the same thread - eventdispatcher.

  • Problem with threads and simulation: please help

    please help me figure this out..
    i have something like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawShapes extends JApplet{
         private JButton choices[];
         private String names[]={"line", "square", "oval"};
         private JPanel buttonPanel;
         private DrawPanel drawingArea;
         private int width=300, height=200;
         public void init(){
              drawingArea=new DrawPanel(width, height);
              choices=new JButton[names.length];
              buttonPanel=new JPanel();
              buttonPanel.setLayout(new GridLayout(1, choices.length));
              ButtonHandler handler=new ButtonHandler();
              for(int i=0; i<choices.length; i++){
                   choices=new JButton(names[i]);
                   buttonPanel.add(choices[i]);
                   choices[i].addActionListener(handler);
              Container c=getContentPane();
              c.add(buttonPanel, BorderLayout.NORTH);
              c.add(drawingArea, BorderLayout.CENTER);
         }//end init
         public void setWidth(int w){
              width=(w>=0 ? w : 300);
         public void setHeight(int h){
              height=(h>=0 ? h : 200);
         /*public static void main(String args[]){
              int width, height;
              if(args.length!=2){
                   height=200; width=300;
              else{
                        width=Integer.parseInt(args[0]);
                        height=Integer.parseInt(args[1]);
              JFrame appWindow=new JFrame("An applet running as an application");
              appWindow.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              DrawShapes appObj=new DrawShapes();
              appObj.setWidth(width);
              appObj.setHeight(height);
              appObj.init();          
              appObj.start();
              appWindow.getContentPane().add(appObj);
              appWindow.setSize(width, height);
              appWindow.show();
         }//end main*/
         private class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   for(int i=0; i<choices.length; i++){
                        if(e.getSource()==choices[i]){
                             drawingArea.setCurrentChoice(i);
                             break;
    }//end class DrawShapes
    class DrawPanel extends JPanel{
         private int currentChoice=-1;
         private int width=100, height=100;
         public DrawPanel(int w, int h){
              width=(w>=0 ? w : 100);
              height=(h>=0 ? h : 100);
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              switch(currentChoice){
                   case 0:     g.drawLine(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 1: g.drawRect(randomX(), randomY(), randomX(), randomY());
                             break;
                   case 2: g.drawOval(randomX(), randomY(), randomX(), randomY());
                             break;
         public void setCurrentChoice(int c){
              currentChoice=c;
              repaint();          
         private int randomX(){
              return (int) (Math.random()*width);
         private int randomY(){
              return (int) (Math.random()*height);
    }//end class drawPanel
    That one's from a book. I used that code to start with my applet. Mine calls different merthod from the switch cases. Say I have:
    case 0: drawStart(g); break;
    public void drawStart(Graphics g){
      /* something here */
    drawMain(g);
    public void drawMain(graphics g){
    g.drawString("test", x, y);
    //here's where i'm trying to pause
    //i've tried placing Thread.sleep between these lines
    g.drawLine(x, y, a, b);
    //Thread.sleep here
    g.drawRect(x, y, 50, 70);
    }I also need to put delays between method calls but I need to synchronize them. Am I doing it all wrong? The application pauses or sleeps but afterwards, it still drew everything all at once. Thanks a lot!

    It is. Sorry about that. Just answer any if you want to. I'd appreciate your help. Sorry again if it caused you anything or whatever. .n_n.

  • NEED HELP IN LABELLING A TRIANGLE _ VERTICES

    PLEASE HELP ______
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.lang.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.FileDialog;
    import java.io.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class Geometry {
        CardLayout cards;
        JPanel panel;
        public Geometry() {
            cards = new CardLayout();
            panel = new JPanel(cards);
            addCards();
            JFrame f = new JFrame("Geometry");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setJMenuBar(getMenuBar());
            f.getContentPane().add(panel);
            f.setSize(500,500);
            f.setLocation(0,0);
            f.setVisible(true);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                   System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                System.out.println("Moving: x=" + me.getX() + "; y=" + me.getY());
            //        panel.addMouseMotionListener(
            //        new MouseMotionListener() { //anonymous inner class
            //            //handle mouse drag event
            //           public void mouseDragged(MouseEvent me) {
            //               setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        private void addCards() {
            // card one
            TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
            TriangleView view  = new TriangleView(tri);
            JPanel panelOne = new JPanel(new BorderLayout());
            panelOne.add(view.getUIPanel(), "North");
            panelOne.add(view);
            panelOne.add(view.getTablePanel(), "South");
            panelOne.setName("Pythagoras's Theorem");
            panel.add("Pythagoras's Theorem", panelOne);
                  view.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            // card two
            TestModel trin = new TestModel(175,100,175,250,325,250);
            TestView viewn  = new TestView(trin);
            JPanel panelTwo = new JPanel(new BorderLayout());
            panelTwo.add(viewn.getUIPanel(), "North");
          // panelTwo.setBackground(Color.blue);
            panelTwo.setName("Similar Triangles");
            panelTwo.add(viewn);
            panelTwo.add(viewn.getTablePanel(), "South");
                  viewn.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            panel.add("Similar Triangles", panelTwo);
            JPanel panelThree = new JPanel();
            panelThree.setBackground(Color.white);
            panelThree.setName("Circle Theorem1");
            panel.add("Circle Theorem1", panelThree);
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JSeparator separator1 = new JSeparator();
            JMenuItem Open = new JMenuItem("Open");
    //         Open.addActionListener(new java.awt.event.ActionListener() {
    //            public void actionPerformed(java.awt.event.ActionEvent evt) {
    //                openActionPerformed(evt);
            JMenuItem Save = new JMenuItem("Save");
            JMenuItem Print = new JMenuItem("Print");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenu theorem = new JMenu("Theorem");
            ActionListener l = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem)e.getSource();
                    String name = item.getActionCommand();
                    cards.show(panel, name);
            Component[] c = panel.getComponents();
            for(int j = 0; j < panel.getComponentCount(); j++) {
                String name = c[j].getName();
                JMenuItem item = new JMenuItem(name);
                item.setActionCommand(name);
                item.addActionListener(l);
                theorem.add(item);
            JMenuBar menuBar = new JMenuBar();
            JMenuBar menuBar1 = new JMenuBar();
            menuBar.add(File);
            File.add(Open);
            File.add(separator1);
            File.add(Save);
            File.add(Print);       
            File.add(Exit);
            menuBar.add(theorem);
            return menuBar;
    //    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    //        FileDialog fileDialog = new FileDialog(this, "Open...", FileDialog.LOAD);
    //        fileDialog.show();
    //        if (fileDialog.getFile() == null)
    //            return;
    //        fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile();
    //        FileInputStream fis = null;
    //        String str = null;
    //        try {
    //            fis = new FileInputStream(fileName);
    //            int size = fis.available();
    //            byte[] bytes = new byte [size];
    //            fis.read(bytes);
    //            str = new String(bytes);
    //        } catch (IOException e) {
    //        } finally {
    //            try {
    //                fis.close();
    //            } catch (IOException e2) {
    //        if (str != null)
    //            textBox.setText(str);
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        public static void main(String[] args) {
            new Geometry();
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class Triangle
    public Triangle()
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import javax.swing.JTable;
    import javax.swing.event.MouseInputAdapter;
    * TriangleControl.java
    * Created on 06 February 2005, 01:19
    * @author  Rahindra Naidoo
    public class TriangleControl extends MouseInputAdapter
        TriangleView view;
        TriangleModel model;
        Point start;
        boolean dragging, altering;
        Rectangle lineLens;            // used for line selection
        public TriangleControl(TriangleView tv)
            view = tv;
            model = view.getModel();
            dragging = altering = false;
            lineLens = new Rectangle(0, 0, 6, 6);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            lineLens.setLocation(p.x - 3, p.y - 3);
            // are we over a line
            if(model.isLineSelected(lineLens))
                start = p;
                altering = true;
            // or are we within the triangle
            else if(model.contains(p))
                start = p;
                dragging = true;
        public void mouseReleased(MouseEvent e)
            altering = false;
            dragging = false;
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
            view.repaint();  // for the construction lines
        public void mouseDragged(MouseEvent e)
            Point p = e.getPoint();
            if(altering)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.moveSide(x, y, p);
                updateTable();
                view.repaint();
                start = p;
            else if(dragging)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.translate(x, y);
                view.repaint();
                start = p;
        private void updateTable()
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            JTable table = view.getTable();
            for(int j = 0; j < angles.length; j++)
                table.setValueAt(lengths[j], 1, j + 1);
                table.setValueAt(squares[j], 2, j + 1);
                table.setValueAt(angles[j],  3, j + 1);
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
    * TriangleModel.java
    * Created on 06 February 2005, 01:18
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * @author  Rahindra Naidoo
    public class TriangleModel                      //  (x1, y1)
    {                                         //      |\
        static final int SIDES = 3;         //      | \
        private int cx, cy;                  //      |  \
        Polygon triangle;                     //      |_ _\ (x3, y3)
        int selectedIndex;                   //  (x2, y2)
        NumberFormat nf;
        Line2D[] medians;
        Point2D centroid;
        public TriangleModel(int x1, int y1, int x2, int y2, int x3, int y3)
            int[] x = new int[] { x1, x2, x3 };
            int[] y = new int[] { y1, y2, y3 };
            triangle = new Polygon(x, y, SIDES);
            nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(1);
        public boolean contains(Point p)
            // Polygon.contains doesn't work well enough
            return (new Area(triangle)).contains(p);
        public boolean isLineSelected(Rectangle r)
            Line2D line = new Line2D.Double();
            for(int j = 0; j < SIDES; j++)
                int[] x = triangle.xpoints;
                int[] y = triangle.ypoints;
                int x1 = x[j];
                int y1 = y[j];
                int x2 = x[(j + 1) % SIDES];
                int y2 = y[(j + 1) % SIDES];
                line.setLine(x1, y1, x2, y2);
                if(line.intersects(r))
                    selectedIndex = j;
                    return true;
            selectedIndex = -1;
            return false;
         * Only works for right triangle with right angle at (x2, y2)
        public void moveSide(int dx, int dy, Point p)
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            switch(selectedIndex)
                case 0:
                    x[0] += dx;
                    x[1] += dx;
                    break;
                case 1:
                    y[1] += dy;
                    y[2] += dy;
                    break;
                case 2:
                    double rise  = y[2] - y[0];
                    double run   = x[2] - x[0];
                    double slope = rise/run;
                    // rise / run == (y[2] - p.y) / (x[2] - p.x)
                    x[2] = p.x + (int)((y[2] - p.y) / slope);
                    // rise / run == (p.y - y[0]) / (p.x - x[0])
                    y[0] = p.y - (int)((p.x - x[0]) * slope);
        public void translate(int dx, int dy)
            triangle.translate(dx, dy);
        public Polygon getTriangle()
            return triangle;
        public String findCentroid()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            // construct the medians defined as the line from
            // any vertex to the midpoint of the opposite line
            medians = new Line2D[x.length];
            for(int j = 0; j < x.length; j++)
                int next = (j + 1) % x.length;
                int last = (j + 2) % x.length;
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                // get midpoint of line opposite vertex
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D oppLineCenter = new Point2D.Double(x[next] + dx,
                                                           y[next] + dy);
                medians[j] = new Line2D.Double(vertex, oppLineCenter);
            // centroid is located on any median 2/3 the way from the
            // vertex (P1) to the midpoint (P2) on the opposite side
            double[] lengths = getSideLengths();
            double dx = (medians[0].getX2() - medians[0].getX1())*2/3;
            double dy = (medians[0].getY2() - medians[0].getY1())*2/3;
            double px = medians[0].getX1() + dx;
            double py = medians[0].getY1() + dy;
            //System.out.println("px = " + nf.format(px) +
            //                 "\tpy = " + nf.format(py));
            centroid = new Point2D.Double(px, py);
            return "(" + nf.format(px) + ",  " + nf.format(py) + ")";
        public String[] getAngles()
            double[] lengths = getSideLengths();
            String[] vertices = new String[lengths.length];
            for(int j = 0; j < lengths.length; j++)
                int opp  = (j + 1) % lengths.length;
                int last = (j + 2) % lengths.length;
                double top = lengths[j] * lengths[j] +
                             lengths[last] * lengths[last] -
                             lengths[opp] * lengths[opp];
                double divisor = 2 * lengths[j] * lengths[last];
                double vertex = Math.acos(top / divisor);
                vertices[j] = nf.format(Math.toDegrees(vertex));
            return vertices;
        public String[] getLengths()
            double[] lengths = getSideLengths();
            String[] lengthStrs = new String[lengths.length];
            for(int j = 0; j < lengthStrs.length; j++)
                lengthStrs[j] = nf.format(lengths[j]);
            return lengthStrs;
        public String[] getSquares()
            double[] lengths = getSideLengths();
            String[] squareStrs = new String[lengths.length];
            for(int j = 0; j < squareStrs.length; j++)
                squareStrs[j] = nf.format(lengths[j] * lengths[j]);
            return squareStrs;
        private double[] getSideLengths()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            double[] lengths = new double[SIDES];
            for(int j = 0; j < SIDES; j++)
                int next = (j + 1) % SIDES;
                lengths[j] = Point.distance(x[j], y[j], x[next], y[next]);
            return lengths;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * TriangleView.java
    * Created on 06 February 2005, 01:21
    public class TriangleView extends JPanel
        private TriangleModel model;
        private Polygon triangle;
        private JTable table;
        private JLabel centroidLabel;
        private boolean showConstruction;
        TriangleControl control;
        public TriangleView(TriangleModel model)
            this.model = model;
            triangle = model.getTriangle();
            showConstruction = false;
            control = new TriangleControl(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.draw(triangle);
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging)
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                                             model.centroid.getY() - 2, 4, 4));
        public TriangleModel getModel()
            return model;
        public JTable getTable()
            return table;
        public JLabel getCentroidLabel()
            return centroidLabel;
        public JPanel getUIPanel()
            JCheckBox showCon = new JCheckBox("show construction");
            showCon.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    boolean state = ((JCheckBox)e.getSource()).isSelected();
                    showConstruction = state;
                    repaint();
            JPanel panel = new JPanel();
            panel.add(showCon);
            return panel;
        public JPanel getTablePanel()
            String[] headers = new String[] { "", "", "", "" };
            // row and column data labels
            String[] rowHeaders = {
                "sides", "lengths", "squares", "angles", "degrees"
            String[] sidesRow = { "vertical", "horizontal", "hypotenuse" };
            String[] anglesRow = { "hyp to ver", "ver to hor", "hor to hyp" };
            // collect data from model
            String[] angles  = model.getAngles();
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[][] allData = { sidesRow, lengths, squares, anglesRow, angles };
            int rows = 5;
            int cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                data[row][0] = rowHeaders[row];
                for(int col = 1; col < cols; col++)
                    data[row][col] = allData[row][col - 1];
            table = new JTable(data, headers)
                public boolean isCellEditable(int row, int col)
                    return false;
            DefaultTableCellRenderer renderer =
                (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
            renderer.setHorizontalAlignment(JLabel.CENTER);
            centroidLabel = new JLabel("centroid location:  ", JLabel.CENTER);
            Dimension d = centroidLabel.getPreferredSize();
            d.height = table.getRowHeight();
            centroidLabel.setPreferredSize(d);
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createTitledBorder("triangle data"));
            panel.add(table);
            panel.add(centroidLabel, "South");
            return panel;
    }PLEASE HELP ME TO LABEL THE TRIANGLE AND CHANGE THE VALUES OF THE JTABLE - to SHOW ASquare b Square and C square as well as a label on the bottom of the screen to show A^2 + B^2 = C^2 ...
    ThANKS

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawPolygon(triangle);
            // label the triangle
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            for(int j = 0; j < x.length; j++) {
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                int next = (j + 0) % x.length;
                int last = (j + 1) % x.length;
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D center = new Point2D.Double(x[next] + dx, y[next] + dy);
                g2.drawString(angles[j],(int)vertex.getX(),(int)vertex.getY());
                g2.drawString(lengths[j],(int)center.getX(),(int)center.getY());
            g2.drawString(squares[0],100, getHeight());
            g2.drawString(" + "+squares[1],150, getHeight());
            g2.drawString(" = "+squares[2],200, getHeight());
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging) {
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                        model.centroid.getY() - 2, 4, 4));
        }

  • URGENT HELP REQUIRED _ Creating Labels for Triangle

    Hi everyone... the code below is my application - Pythagoras Theorem.. or rather displaying it.. But i have not been able to get the Vertex of the triangle Labelled as A B C... I need to do that and change the Triangle Table data to A B C insted of Horizontal Vertical and Hypotenuise and as the triangle is stretched on screen A B And C keep moving as well ...
    Besides i need to Show this in the tabel
    - Values of A ^ 2 , B^2 and C ^2 as welll as a row showing A^2+B^2 = C^2
    the code is as follows..
    This is the main class called Geometry
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.lang.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.FileDialog;
    import java.io.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class Geometry {
        CardLayout cards;
        JPanel panel;
        public Geometry() {
            cards = new CardLayout();
            panel = new JPanel(cards);
            addCards();
            JFrame f = new JFrame("Geometry");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setJMenuBar(getMenuBar());
            f.getContentPane().add(panel);
            f.setSize(500,500);
            f.setLocation(0,0);
            f.setVisible(true);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                   System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                System.out.println("Moving: x=" + me.getX() + "; y=" + me.getY());
            //        panel.addMouseMotionListener(
            //        new MouseMotionListener() { //anonymous inner class
            //            //handle mouse drag event
            //           public void mouseDragged(MouseEvent me) {
            //               setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        private void addCards() {
            // card one
            TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
            TriangleView view  = new TriangleView(tri);
            JPanel panelOne = new JPanel(new BorderLayout());
            panelOne.add(view.getUIPanel(), "North");
            panelOne.add(view);
            panelOne.add(view.getTablePanel(), "South");
            panelOne.setName("Pythagoras's Theorem");
            panel.add("Pythagoras's Theorem", panelOne);
                  view.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            // card two
            TestModel trin = new TestModel(175,100,175,250,325,250);
            TestView viewn  = new TestView(trin);
            JPanel panelTwo = new JPanel(new BorderLayout());
            panelTwo.add(viewn.getUIPanel(), "North");
          // panelTwo.setBackground(Color.blue);
            panelTwo.setName("Similar Triangles");
            panelTwo.add(viewn);
            panelTwo.add(viewn.getTablePanel(), "South");
                  viewn.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            panel.add("Similar Triangles", panelTwo);
            JPanel panelThree = new JPanel();
            panelThree.setBackground(Color.white);
            panelThree.setName("Circle Theorem1");
            panel.add("Circle Theorem1", panelThree);
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JSeparator separator1 = new JSeparator();
            JMenuItem Open = new JMenuItem("Open");
    //         Open.addActionListener(new java.awt.event.ActionListener() {
    //            public void actionPerformed(java.awt.event.ActionEvent evt) {
    //                openActionPerformed(evt);
            JMenuItem Save = new JMenuItem("Save");
            JMenuItem Print = new JMenuItem("Print");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenu theorem = new JMenu("Theorem");
            ActionListener l = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem)e.getSource();
                    String name = item.getActionCommand();
                    cards.show(panel, name);
            Component[] c = panel.getComponents();
            for(int j = 0; j < panel.getComponentCount(); j++) {
                String name = c[j].getName();
                JMenuItem item = new JMenuItem(name);
                item.setActionCommand(name);
                item.addActionListener(l);
                theorem.add(item);
            JMenuBar menuBar = new JMenuBar();
            JMenuBar menuBar1 = new JMenuBar();
            menuBar.add(File);
            File.add(Open);
            File.add(separator1);
            File.add(Save);
            File.add(Print);       
            File.add(Exit);
            menuBar.add(theorem);
            return menuBar;
    //    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    //        FileDialog fileDialog = new FileDialog(this, "Open...", FileDialog.LOAD);
    //        fileDialog.show();
    //        if (fileDialog.getFile() == null)
    //            return;
    //        fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile();
    //        FileInputStream fis = null;
    //        String str = null;
    //        try {
    //            fis = new FileInputStream(fileName);
    //            int size = fis.available();
    //            byte[] bytes = new byte [size];
    //            fis.read(bytes);
    //            str = new String(bytes);
    //        } catch (IOException e) {
    //        } finally {
    //            try {
    //                fis.close();
    //            } catch (IOException e2) {
    //        if (str != null)
    //            textBox.setText(str);
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        public static void main(String[] args) {
            new Geometry();
    }import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class Triangle
    public Triangle()
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import javax.swing.JTable;
    import javax.swing.event.MouseInputAdapter;
    * TriangleControl.java
    * Created on 06 February 2005, 01:19
    * @author  Rahindra Naidoo
    public class TriangleControl extends MouseInputAdapter
        TriangleView view;
        TriangleModel model;
        Point start;
        boolean dragging, altering;
        Rectangle lineLens;            // used for line selection
        public TriangleControl(TriangleView tv)
            view = tv;
            model = view.getModel();
            dragging = altering = false;
            lineLens = new Rectangle(0, 0, 6, 6);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            lineLens.setLocation(p.x - 3, p.y - 3);
            // are we over a line
            if(model.isLineSelected(lineLens))
                start = p;
                altering = true;
            // or are we within the triangle
            else if(model.contains(p))
                start = p;
                dragging = true;
        public void mouseReleased(MouseEvent e)
            altering = false;
            dragging = false;
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
            view.repaint();  // for the construction lines
        public void mouseDragged(MouseEvent e)
            Point p = e.getPoint();
            if(altering)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.moveSide(x, y, p);
                updateTable();
                view.repaint();
                start = p;
            else if(dragging)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.translate(x, y);
                view.repaint();
                start = p;
        private void updateTable()
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            JTable table = view.getTable();
            for(int j = 0; j < angles.length; j++)
                table.setValueAt(lengths[j], 1, j + 1);
                table.setValueAt(squares[j], 2, j + 1);
                table.setValueAt(angles[j],  3, j + 1);
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
    * TriangleModel.java
    * Created on 06 February 2005, 01:18
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * @author  Rahindra Naidoo
    public class TriangleModel                      //  (x1, y1)
    {                                         //      |\
        static final int SIDES = 3;         //      | \
        private int cx, cy;                  //      |  \
        Polygon triangle;                     //      |_ _\ (x3, y3)
        int selectedIndex;                   //  (x2, y2)
        NumberFormat nf;
        Line2D[] medians;
        Point2D centroid;
        public TriangleModel(int x1, int y1, int x2, int y2, int x3, int y3)
            int[] x = new int[] { x1, x2, x3 };
            int[] y = new int[] { y1, y2, y3 };
            triangle = new Polygon(x, y, SIDES);
            nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(1);
        public boolean contains(Point p)
            // Polygon.contains doesn't work well enough
            return (new Area(triangle)).contains(p);
        public boolean isLineSelected(Rectangle r)
            Line2D line = new Line2D.Double();
            for(int j = 0; j < SIDES; j++)
                int[] x = triangle.xpoints;
                int[] y = triangle.ypoints;
                int x1 = x[j];
                int y1 = y[j];
                int x2 = x[(j + 1) % SIDES];
                int y2 = y[(j + 1) % SIDES];
                line.setLine(x1, y1, x2, y2);
                if(line.intersects(r))
                    selectedIndex = j;
                    return true;
            selectedIndex = -1;
            return false;
         * Only works for right triangle with right angle at (x2, y2)
        public void moveSide(int dx, int dy, Point p)
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            switch(selectedIndex)
                case 0:
                    x[0] += dx;
                    x[1] += dx;
                    break;
                case 1:
                    y[1] += dy;
                    y[2] += dy;
                    break;
                case 2:
                    double rise  = y[2] - y[0];
                    double run   = x[2] - x[0];
                    double slope = rise/run;
                    // rise / run == (y[2] - p.y) / (x[2] - p.x)
                    x[2] = p.x + (int)((y[2] - p.y) / slope);
                    // rise / run == (p.y - y[0]) / (p.x - x[0])
                    y[0] = p.y - (int)((p.x - x[0]) * slope);
        public void translate(int dx, int dy)
            triangle.translate(dx, dy);
        public Polygon getTriangle()
            return triangle;
        public String findCentroid()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            // construct the medians defined as the line from
            // any vertex to the midpoint of the opposite line
            medians = new Line2D[x.length];
            for(int j = 0; j < x.length; j++)
                int next = (j + 1) % x.length;
                int last = (j + 2) % x.length;
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                // get midpoint of line opposite vertex
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D oppLineCenter = new Point2D.Double(x[next] + dx,
                                                           y[next] + dy);
                medians[j] = new Line2D.Double(vertex, oppLineCenter);
            // centroid is located on any median 2/3 the way from the
            // vertex (P1) to the midpoint (P2) on the opposite side
            double[] lengths = getSideLengths();
            double dx = (medians[0].getX2() - medians[0].getX1())*2/3;
            double dy = (medians[0].getY2() - medians[0].getY1())*2/3;
            double px = medians[0].getX1() + dx;
            double py = medians[0].getY1() + dy;
            //System.out.println("px = " + nf.format(px) +
            //                 "\tpy = " + nf.format(py));
            centroid = new Point2D.Double(px, py);
            return "(" + nf.format(px) + ",  " + nf.format(py) + ")";
        public String[] getAngles()
            double[] lengths = getSideLengths();
            String[] vertices = new String[lengths.length];
            for(int j = 0; j < lengths.length; j++)
                int opp  = (j + 1) % lengths.length;
                int last = (j + 2) % lengths.length;
                double top = lengths[j] * lengths[j] +
                             lengths[last] * lengths[last] -
                             lengths[opp] * lengths[opp];
                double divisor = 2 * lengths[j] * lengths[last];
                double vertex = Math.acos(top / divisor);
                vertices[j] = nf.format(Math.toDegrees(vertex));
            return vertices;
        public String[] getLengths()
            double[] lengths = getSideLengths();
            String[] lengthStrs = new String[lengths.length];
            for(int j = 0; j < lengthStrs.length; j++)
                lengthStrs[j] = nf.format(lengths[j]);
            return lengthStrs;
        public String[] getSquares()
            double[] lengths = getSideLengths();
            String[] squareStrs = new String[lengths.length];
            for(int j = 0; j < squareStrs.length; j++)
                squareStrs[j] = nf.format(lengths[j] * lengths[j]);
            return squareStrs;
        private double[] getSideLengths()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            double[] lengths = new double[SIDES];
            for(int j = 0; j < SIDES; j++)
                int next = (j + 1) % SIDES;
                lengths[j] = Point.distance(x[j], y[j], x[next], y[next]);
            return lengths;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * TriangleView.java
    * Created on 06 February 2005, 01:21
    public class TriangleView extends JPanel
        private TriangleModel model;
        private Polygon triangle;
        private JTable table;
        private JLabel centroidLabel;
        private boolean showConstruction;
        TriangleControl control;
        public TriangleView(TriangleModel model)
            this.model = model;
            triangle = model.getTriangle();
            showConstruction = false;
            control = new TriangleControl(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.draw(triangle);
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging)
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                                             model.centroid.getY() - 2, 4, 4));
        public TriangleModel getModel()
            return model;
        public JTable getTable()
            return table;
        public JLabel getCentroidLabel()
            return centroidLabel;
        public JPanel getUIPanel()
            JCheckBox showCon = new JCheckBox("show construction");
            showCon.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    boolean state = ((JCheckBox)e.getSource()).isSelected();
                    showConstruction = state;
                    repaint();
            JPanel panel = new JPanel();
            panel.add(showCon);
            return panel;
        public JPanel getTablePanel()
            String[] headers = new String[] { "", "", "", "" };
            // row and column data labels
            String[] rowHeaders = {
                "sides", "lengths", "squares", "angles", "degrees"
            String[] sidesRow = { "vertical", "horizontal", "hypotenuse" };
            String[] anglesRow = { "hyp to ver", "ver to hor", "hor to hyp" };
            // collect data from model
            String[] angles  = model.getAngles();
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[][] allData = { sidesRow, lengths, squares, anglesRow, angles };
            int rows = 5;
            int cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                data[row][0] = rowHeaders[row];
                for(int col = 1; col < cols; col++)
                    data[row][col] = allData[row][col - 1];
            table = new JTable(data, headers)
                public boolean isCellEditable(int row, int col)
                    return false;
            DefaultTableCellRenderer renderer =
                (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
            renderer.setHorizontalAlignment(JLabel.CENTER);
            centroidLabel = new JLabel("centroid location:  ", JLabel.CENTER);
            Dimension d = centroidLabel.getPreferredSize();
            d.height = table.getRowHeight();
            centroidLabel.setPreferredSize(d);
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createTitledBorder("triangle data"));
            panel.add(table);
            panel.add(centroidLabel, "South");
            return panel;
    }PLEASE HELP ---- Also does any one know how to draw a Triangle on a screen which can be controlled by a JSlider such that as and whenits incremented the triangle increase and vice versa... I need to prove Similarity in triangles using A Jslider that controls one triangle while the other triangle is Still on screen

    Sharan,
    The code given was part of the assignment and you are supposed to make the changes for your part right?
    Please give details of what you have done so far and not expect us to do your assignment for you. We'll be glad to help answer questions and point to the right direction, but giving us the entire assignment and saying, very nicely I might add, "Please do it for me." Just seems to make a mockery of the hours, days, and years that many of us has spent earning our degrees and learning our skills.
    Work on it and ask specific questions with examples of what you have done and you'll get a much better response.

  • Netbeans 5.0 crashes... please help..

    Hi, i just installed netbeans 5.0 with the latest java package. When i first execute the program, it crashes. Below is the error log. Can anyone help me? This is not the first time. I already uninstall and reinstall java and reinstalling netbeans. This same outcome.
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00d18280, pid=3352, tid=3872
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode, sharing)
    # Problematic frame:
    # J java.awt.GradientPaintContext.clipFillRaster([IIIIIDDD)V
    --------------- T H R E A D ---------------
    Current thread (0x030081e0): JavaThread "AWT-EventQueue-1" [_thread_in_Java, id=3872]
    siginfo: ExceptionCode=0xc0000005, reading address 0xffffffff
    Registers:
    EAX=0x1cadd928, EBX=0x00000000, ECX=0x1cb53c80, EDX=0x00000000
    ESP=0x0365e4f8, EBP=0x0365e528, ESI=0x00000000, EDI=0x00000020
    EIP=0x00d18280, EFLAGS=0x00010246
    Top of Stack: (sp=0x0365e4f8)
    0x0365e4f8: 00000000 00000000 00000000 00000000
    0x0365e508: 00ad29fa 00000001 1cadd934 00000000
    0x0365e518: 00000000 ffffffff 1c71c71c 3fbc71c7
    0x0365e528: 0365e588 00d8e3eb 1c71c71c 3fac71c7
    0x0365e538: 00000000 00000000 1c71c71c 3fbc71c7
    0x0365e548: 00000000 00000020 00000000 00000000
    0x0365e558: 1cadd928 1cb53c80 0365e5ac 00000000
    0x0365e568: 00000000 1cadd928 00000000 00000000
    Instructions: (pc=0x00d18280)
    0x00d18270: dd 45 18 dd 5d f8 8b 7d 24 dd 45 f8 d9 ee d9 c9
    0x00d18280: df e9 dd c0 d9 f7 0f 8a 06 00 00 00 0f 86 0e 00
    Stack: [0x03620000,0x03660000), sp=0x0365e4f8, free space=249k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    J java.awt.GradientPaintContext.clipFillRaster([IIIIIDDD)V
    J java.awt.GradientPaintContext.getRaster(IIII)Ljava/awt/image/Raster;
    J sun.java2d.pipe.AlphaPaintPipe.renderPathTile(Ljava/lang/Object;[BIIIIII)V
    j sun.java2d.pipe.SpanShapeRenderer$Composite.renderBox(Ljava/lang/Object;IIII)V+15
    j sun.java2d.pipe.SpanShapeRenderer.spanClipLoop(Ljava/lang/Object;Lsun/java2d/pipe/SpanIterator;Lsun/java2d/pipe/Region;[I)V+56
    j sun.java2d.pipe.SpanShapeRenderer.renderSpans(Lsun/java2d/SunGraphics2D;Lsun/java2d/pipe/Region;Ljava/awt/Shape;Lsun/java2d/pipe/ShapeSpanIterator;)V+131
    j sun.java2d.pipe.SpanShapeRenderer.renderPath(Lsun/java2d/SunGraphics2D;Ljava/awt/Shape;)V+43
    j sun.java2d.pipe.SpanShapeRenderer.fill(Lsun/java2d/SunGraphics2D;Ljava/awt/Shape;)V+33
    j sun.java2d.pipe.PixelToShapeConverter.fillPolygon(Lsun/java2d/SunGraphics2D;[I[II)V+14
    j sun.java2d.pipe.ValidatePipe.fillPolygon(Lsun/java2d/SunGraphics2D;[I[II)V+17
    j sun.java2d.SunGraphics2D.fillPolygon([I[II)V+8
    j java.awt.Graphics.fillPolygon(Ljava/awt/Polygon;)V+13
    j org.netbeans.swing.tabcontrol.plaf.WinXPEditorTabCellRenderer.paintGradient(Ljava/awt/Graphics;Lorg/netbeans/swing/tabcontrol/plaf/WinXPEditorTabCellRenderer;Lorg/netbeans/swing/tabcontrol/plaf/TabPainter;)V+39
    j org.netbeans.swing.tabcontrol.plaf.WinXPEditorTabCellRenderer.access$700(Ljava/awt/Graphics;Lorg/netbeans/swing/tabcontrol/plaf/WinXPEditorTabCellRenderer;Lorg/netbeans/swing/tabcontrol/plaf/TabPainter;)V+3
    j org.netbeans.swing.tabcontrol.plaf.WinXPEditorTabCellRenderer$WinXPPainter.paintInterior(Ljava/awt/Graphics;Ljava/awt/Component;)V+8
    j org.netbeans.swing.tabcontrol.plaf.AbstractTabCellRenderer.paintComponent(Ljava/awt/Graphics;)V+27
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+260
    j org.netbeans.swing.tabcontrol.plaf.BasicTabDisplayerUI.paint(Ljava/awt/Graphics;Ljavax/swing/JComponent;)V+404
    j javax.swing.plaf.ComponentUI.update(Ljava/awt/Graphics;Ljavax/swing/JComponent;)V+32
    j javax.swing.JComponent.paintComponent(Ljava/awt/Graphics;)V+26
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+260
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    j org.netbeans.core.windows.view.ui.MultiSplitPane.paint(Ljava/awt/Graphics;)V+2
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    j javax.swing.JLayeredPane.paint(Ljava/awt/Graphics;)V+73
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    j javax.swing.JLayeredPane.paint(Ljava/awt/Graphics;)V+73
    J javax.swing.JComponent.paintChildren(Ljava/awt/Graphics;)V
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+292
    j javax.swing.JComponent.paintWithOffscreenBuffer(Ljavax/swing/JComponent;Ljava/awt/Graphics;IIIILjava/awt/Image;)V+174
    j javax.swing.JComponent.paintDoubleBuffered(Ljavax/swing/JComponent;Ljava/awt/Component;Ljava/awt/Graphics;IIII)Z+131
    J javax.swing.JComponent._paintImmediately(IIII)V
    j javax.swing.JComponent.paintImmediately(IIII)V+83
    j javax.swing.RepaintManager.paintDirtyRegions()V+314
    j javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run()V+32
    j java.awt.event.InvocationEvent.dispatch()V+47
    j java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+26
    J java.awt.EventDispatchThread.pumpOneEventForHierarchy(ILjava/awt/Component;)Z
    v ~RuntimeStub::alignment_frame_return Runtime1 stub
    j java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+26
    j java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
    j java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
    j java.awt.EventDispatchThread.run()V+9
    v ~StubRoutines::call_stub
    V [jvm.dll+0x845a9]
    V [jvm.dll+0xd9317]
    V [jvm.dll+0x8447a]
    V [jvm.dll+0x841d7]
    V [jvm.dll+0x9ed69]
    V [jvm.dll+0x109fe3]
    V [jvm.dll+0x109fb1]
    C [MSVCRT.dll+0x2a3b0]
    C [kernel32.dll+0xb50b]
    --------------- P R O C E S S ---------------
    Java Threads: ( => current thread )
    0x02d1d188 JavaThread "Image Fetcher 1" daemon [_thread_blocked, id=216]
    0x02d00d90 JavaThread "Image Fetcher 0" daemon [_thread_blocked, id=3472]
    0x0302df18 JavaThread "Inactive RequestProcessor thread [Was:Parsing Event Queue/org.netbeans.modules.javacore.JMManager$5]" daemon [_thread_blocked, id=3532]
    0x032ac270 JavaThread "Inactive RequestProcessor thread [Was:Default RequestProcessor/org.netbeans.modules.editor.errorstripe.AnnotationView$RepaintTask]" daemon [_thread_blocked, id=2444]
    0x032d7dd0 JavaThread "Inactive RequestProcessor thread [Was:Default RequestProcessor/org.netbeans.modules.navigator.NavigatorController$ActNodeSetter]" daemon [_thread_blocked, id=2364]
    0x02f42500 JavaThread "Inactive RequestProcessor thread [Was:ToolTip-Evaluator/org.netbeans.modules.editor.NbToolTip$Request]" daemon [_thread_blocked, id=1060]
    0x02ced900 JavaThread "Inactive RequestProcessor thread [Was:Overriddens Queue/org.netbeans.modules.java.OverrideAnnotationSupport$Request]" daemon [_thread_blocked, id=3868]
    0x02e1d7d0 JavaThread "MDR event dispatcher" daemon [_thread_blocked, id=3996]
    0x00037b60 JavaThread "DestroyJavaVM" [_thread_blocked, id=900]
    =>0x030081e0 JavaThread "AWT-EventQueue-1" [_thread_in_Java, id=3872]
    0x031ebb28 JavaThread "TimerQueue" daemon [_thread_blocked, id=2448]
    0x031d2b80 JavaThread "Inactive RequestProcessor thread [Was:ListModelSupport loader/org.netbeans.modules.java.navigation.spi.ListModelSupport$Loader]" daemon [_thread_blocked, id=1836]
    0x031a6dd8 JavaThread "Inactive RequestProcessor thread [Was:Java Node State Updater/org.netbeans.modules.java.JavaNode$StateUpdater]" daemon [_thread_blocked, id=1788]
    0x0316cb90 JavaThread "Inactive RequestProcessor thread [Was:ToolTip-Evaluator/org.netbeans.modules.editor.NbToolTip$Request]" daemon [_thread_blocked, id=3228]
    0x02f3d390 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=3456]
    0x00acf638 JavaThread "AWT-Windows" daemon [_thread_in_native, id=628]
    0x02ecd948 JavaThread "AWT-Shutdown" [_thread_blocked, id=2720]
    0x00acd950 JavaThread "Timer-0" daemon [_thread_blocked, id=1852]
    0x02cd8820 JavaThread "CLI Requests Server" daemon [_thread_in_native, id=1340]
    0x00ab7a70 JavaThread "Active Reference Queue Daemon" daemon [_thread_blocked, id=2492]
    0x00a70268 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=3004]
    0x00a6eed8 JavaThread "CompilerThread0" daemon [_thread_blocked, id=3440]
    0x00a6e1c0 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=3444]
    0x0003fa20 JavaThread "Finalizer" daemon [_thread_blocked, id=3492]
    0x00a48aa0 JavaThread "Reference Handler" daemon [_thread_blocked, id=2580]
    Other Threads:
    0x00a68428 VMThread [id=3628]
    0x00a714b8 WatcherThread [id=3752]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 2304K, used 914K [0x1ca70000, 0x1ccf0000, 0x1d440000)
    eden space 2048K, 44% used [0x1ca70000, 0x1cb54868, 0x1cc70000)
    from space 256K, 0% used [0x1cc70000, 0x1cc70000, 0x1ccb0000)
    to space 256K, 0% used [0x1ccb0000, 0x1ccb0000, 0x1ccf0000)
    tenured generation total 30272K, used 16957K [0x1d440000, 0x1f1d0000, 0x24a70000)
    the space 30272K, 56% used [0x1d440000, 0x1e4cf758, 0x1e4cf800, 0x1f1d0000)
    compacting perm gen total 32768K, used 21094K [0x24a70000, 0x26a70000, 0x2aa70000)
    the space 32768K, 64% used [0x24a70000, 0x25f098f0, 0x25f09a00, 0x26a70000)
    ro space 8192K, 66% used [0x2aa70000, 0x2afcbcc0, 0x2afcbe00, 0x2b270000)
    rw space 12288K, 46% used [0x2b270000, 0x2b812060, 0x2b812200, 0x2be70000)
    Dynamic libraries:
    0x00400000 - 0x0040c000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\java.exe
    0x7c900000 - 0x7c9b0000 C:\WINDOWS\system32\ntdll.dll
    0x7c800000 - 0x7c8f4000 C:\WINDOWS\system32\kernel32.dll
    0x77dd0000 - 0x77e6b000 C:\WINDOWS\system32\ADVAPI32.dll
    0x77e70000 - 0x77f01000 C:\WINDOWS\system32\RPCRT4.dll
    0x77c10000 - 0x77c68000 C:\WINDOWS\system32\MSVCRT.dll
    0x6d6e0000 - 0x6d874000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\client\jvm.dll
    0x77d40000 - 0x77dd0000 C:\WINDOWS\system32\USER32.dll
    0x77f10000 - 0x77f56000 C:\WINDOWS\system32\GDI32.dll
    0x76b40000 - 0x76b6d000 C:\WINDOWS\system32\WINMM.dll
    0x6d2f0000 - 0x6d2f8000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\hpi.dll
    0x76bf0000 - 0x76bfb000 C:\WINDOWS\system32\PSAPI.DLL
    0x6d6b0000 - 0x6d6bc000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\verify.dll
    0x6d370000 - 0x6d38d000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\java.dll
    0x6d6d0000 - 0x6d6df000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\zip.dll
    0x6d530000 - 0x6d543000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\net.dll
    0x71ab0000 - 0x71ac7000 C:\WINDOWS\system32\WS2_32.dll
    0x71aa0000 - 0x71aa8000 C:\WINDOWS\system32\WS2HELP.dll
    0x76d60000 - 0x76d79000 C:\WINDOWS\system32\iphlpapi.dll
    0x76d40000 - 0x76d58000 C:\WINDOWS\system32\MPRAPI.dll
    0x77cc0000 - 0x77cf2000 C:\WINDOWS\system32\ACTIVEDS.dll
    0x76e10000 - 0x76e35000 C:\WINDOWS\system32\adsldpc.dll
    0x5b860000 - 0x5b8b4000 C:\WINDOWS\system32\NETAPI32.dll
    0x76f60000 - 0x76f8c000 C:\WINDOWS\system32\WLDAP32.dll
    0x76b20000 - 0x76b31000 C:\WINDOWS\system32\ATL.DLL
    0x774e0000 - 0x7761c000 C:\WINDOWS\system32\ole32.dll
    0x77120000 - 0x771ac000 C:\WINDOWS\system32\OLEAUT32.dll
    0x76e80000 - 0x76e8e000 C:\WINDOWS\system32\rtutils.dll
    0x71bf0000 - 0x71c03000 C:\WINDOWS\system32\SAMLIB.dll
    0x77920000 - 0x77a13000 C:\WINDOWS\system32\SETUPAPI.dll
    0x71a50000 - 0x71a8f000 C:\WINDOWS\system32\mswsock.dll
    0x662b0000 - 0x66308000 C:\WINDOWS\system32\hnetcfg.dll
    0x71a90000 - 0x71a98000 C:\WINDOWS\System32\wshtcpip.dll
    0x76f20000 - 0x76f47000 C:\WINDOWS\system32\DNSAPI.dll
    0x76fb0000 - 0x76fb8000 C:\WINDOWS\System32\winrnr.dll
    0x76fc0000 - 0x76fc6000 C:\WINDOWS\system32\rasadhlp.dll
    0x0ffd0000 - 0x0fff8000 C:\WINDOWS\system32\rsaenh.dll
    0x769c0000 - 0x76a73000 C:\WINDOWS\system32\USERENV.dll
    0x6d070000 - 0x6d1d7000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\awt.dll
    0x73000000 - 0x73026000 C:\WINDOWS\system32\WINSPOOL.DRV
    0x76390000 - 0x763ad000 C:\WINDOWS\system32\IMM32.dll
    0x5ad70000 - 0x5ada8000 C:\WINDOWS\system32\uxtheme.dll
    0x73760000 - 0x737a9000 C:\WINDOWS\system32\ddraw.dll
    0x73bc0000 - 0x73bc6000 C:\WINDOWS\system32\DCIMAN32.dll
    0x73940000 - 0x73a10000 C:\WINDOWS\system32\D3DIM700.DLL
    0x10000000 - 0x10005000 C:\WINDOWS\BricoPacks\Vista Inspirat\ObjectDock\DockShellHook.dll
    0x74720000 - 0x7476b000 C:\WINDOWS\system32\MSCTF.dll
    0x03510000 - 0x0351f000 C:\WINDOWS\BricoPacks\Vista Inspirat\YzToolbar\YzToolBar.dll
    0x5d090000 - 0x5d127000 C:\WINDOWS\system32\COMCTL32.dll
    0x7c9c0000 - 0x7e77e000 C:\WINDOWS\system32\shell32.dll
    0x77f60000 - 0x77ff7000 C:\WINDOWS\system32\SHLWAPI.dll
    0x773d0000 - 0x774d2000 C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.2180_x-ww_a84f1ff9\comctl32.dll
    0x6d2b0000 - 0x6d2ed000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\fontmanager.dll
    0x6d550000 - 0x6d559000 C:\Program Files\Java\jdk1.5.0_06\jre\bin\nio.dll
    0x605d0000 - 0x605d9000 C:\WINDOWS\system32\mslbui.dll
    0x71b20000 - 0x71b32000 C:\WINDOWS\system32\MPR.dll
    0x75f60000 - 0x75f67000 C:\WINDOWS\System32\drprov.dll
    0x71c10000 - 0x71c1e000 C:\WINDOWS\System32\ntlanman.dll
    0x71cd0000 - 0x71ce7000 C:\WINDOWS\System32\NETUI0.dll
    0x71c90000 - 0x71cd0000 C:\WINDOWS\System32\NETUI1.dll
    0x71c80000 - 0x71c87000 C:\WINDOWS\System32\NETRAP.dll
    0x75f70000 - 0x75f79000 C:\WINDOWS\System32\davclnt.dll
    0x77b40000 - 0x77b62000 C:\WINDOWS\system32\appHelp.dll
    0x76fd0000 - 0x7704f000 C:\WINDOWS\system32\CLBCATQ.DLL
    0x77050000 - 0x77115000 C:\WINDOWS\system32\COMRes.dll
    0x77c00000 - 0x77c08000 C:\WINDOWS\system32\VERSION.dll
    0x76980000 - 0x76988000 C:\WINDOWS\system32\LINKINFO.dll
    0x03bc0000 - 0x03c09000 C:\WINDOWS\system32\ntshrui.dll
    VM Arguments:
    jvm_args: -Dnetbeans.importclass=org.netbeans.upgrade.AutoUpgrade -Dnetbeans.accept_license_class=org.netbeans.license.AcceptLicense -Xms32m -Xmx128m -XX:PermSize=32m -XX:MaxPermSize=96m -Xverify:none -Dapple.laf.useScreenMenuBar=true -Dnetbeans.osenv=C:\DOCUME~1\M996F~1.KHA\LOCALS~1\Temp\nbenv3 -Dnetbeans.osenv.nullsep=true -Djdk.home=C:\Program Files\Java\jdk1.5.0_06 -Dnetbeans.home=C:\Program Files\netbeans-5.0\platform6 -Dnetbeans.dirs=C:\Program Files\netbeans-5.0\nb5.0;C:\Program Files\netbeans-5.0\ide6;C:\Program Files\netbeans-5.0\enterprise2;C:\Program Files\netbeans-5.0\harness -Dnetbeans.user=C:\Documents and Settings\M.Khalid\.netbeans\5.0 -Dnetbeans.system_http_proxy=DIRECT -Dsun.awt.keepWorkingSetOnMinimize=true
    java_command: org/netbeans/Main --branding nb
    Launcher Type: SUN_STANDARD
    Environment Variables:
    CLASSPATH=.
    PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Common Files\Adobe\AGL;C:\Program Files\QuickTime\QTSystem\ ; C:\Program Files\Java\jre1.5.0_06\bin
    USERNAME=M.Khalid
    OS=Windows_NT
    PROCESSOR_IDENTIFIER=x86 Family 6 Model 13 Stepping 6, GenuineIntel
    --------------- S Y S T E M ---------------
    OS: Windows XP Build 2600 Service Pack 2
    CPU:total 1 family 6, cmov, cx8, fxsr, mmx, sse, sse2
    Memory: 4k page, physical 514544k(100160k free), swap 1258580k(883052k free)
    vm_info: Java HotSpot(TM) Client VM (1.5.0_06-b05) for windows-x86, built on Nov 10 2005 11:12:14 by "java_re" with MS VC++ 6.0

    Did you try asking Netbeans support too?

  • Urgent  help needed(java frames)

    Hi,
    I need urgent help for correcting a piece of code.
    I have written a piece of code for building a gui with some buttons, drawing some geometric shapes.The code consists of two files called Graph and Frame.
    The problem I suppose in the last part of the Graph file, which Rectangle and Circle are called together, the only shape that the program draws is rectangle.Here is the code:
    //Graph
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;
    public class Graph extends JPanel {
    LinkedList color;
    LinkedList figures;
    public Graph() {
    setBackground(Color.white);
    figures = new LinkedList();
    color = new LinkedList();
    int z;
    class Point {
    int x;
    int y;
    public Point(int x, int y) {
    this.x = x;
    this.y = y;
    public Point(Point p) {
    x = p.x;
    y = p.y;
    public String toString() {
    return "(" + x + ", " + y + ")";
    public void move(Point dist) {
    x += dist.x;
    y += dist.y;
    abstract class GeomFigur {
    public abstract void move(Point p);
    class Line extends GeomFigur {
    Point p1, p2;
    public Line(Point p1, Point p2) {
    this.p1 = new Point(p1);
    this.p2 = new Point(p2);
    public String toString() { return "Line from " + p1 + " to " + p2;  }
    public void move(Point dist) {
    p1.move(dist);
    p2.move(dist);
    class Rectangle extends Line {
    public Rectangle(Point p1, Point p2) {
    super(p1, p2);
    public String toString() { return "Rectangle from " + p1 + " to " + p2; }
    class Circle extends GeomFigur{
    Point centre;
    int radius;
    public Circle(Point centre, int radius) {
    this.centre = new Point(centre);
    this.radius = radius;
    public String toString() {
    return "Circle, centre " + centre + ", radius " + radius;
    public void move(Point dist) { centre.move(dist); }
    public void addRectangle(int x, int y, Color col) {
    Rectangle r =new Rectangle(new Point(x,y),new Point(x+20,y+20));
    figures.addLast(r);
    color.addLast(col);
    repaint();
    public void addCircle(int x, int y, Color col) {
    Circle c =new Circle(new Point(x,y), 1 );
    figures.addLast(c);
    color.addLast(col);
    repaint();
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i=0;i < figures.size();i++) {
    Rectangle rect = (Rectangle)figures.get(i);
    //Circle circ = (Circle)figures.get(i);
    g.setColor(Color.black);
    g.drawRect(rect.p1.x,rect.p1.y,20,20);
    g.setColor((Color)color.get(i));
    g.fillRect(rect.p1.x,rect.p1.y,20,20);
    //g.setColor(Color.black);
    // g.drawOval(circ.centre.x,circ.centre.y,20,20);
    // g.setColor((Color)color.get(i));
    // g.fillOval(circ.centre.x, circ.centre.y, 20, 20);
    //Frame
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class Frame extends JFrame implements ActionListener {
    JButton button1, button2, button3, button4, button5 ;
    Graph gr;
    JComboBox cbx;
    JComboBox cby;
    JComboBox col;
    JMenu filemenu;
    JMenuItem quit;
    JMenuBar menubar;
    int x=10;
    int y=10;
    Color color=Color.red;
    public Frame() {
    menubar = new JMenuBar();
    filemenu = new JMenu("File");
    filemenu.setMnemonic('F');
    quit = new JMenuItem("Quit");
    quit.addActionListener(this);
    quit.setMnemonic('Q');
    quit.setAccelerator(KeyStroke.getKeyStroke('Q',Event.CTRL_MASK,false));
    filemenu.add(quit);
    menubar.add(filemenu);
    setJMenuBar(menubar);
    button1 = new JButton("Rectangle");
    button1.addActionListener(this);
    button2 = new JButton("Circle");
    button2.addActionListener(this);
    button4 = new JButton("Ellipse");
    button4.addActionListener(this);
    button5 = new JButton("Triangle");
    button5.addActionListener(this);
    button3 = new JButton("Reset");
    button3.addActionListener(this);
    String[] elements_x= {"10","20","30","40","50","60","70"};
    cbx = new JComboBox(elements_x);
    cbx.addActionListener(this);
    cbx.setActionCommand("cbx");
    String[] elements_y= {"10","20","30","40","50","60","70"};
    cby = new JComboBox(elements_y);
    cby.addActionListener(this);
    cby.setActionCommand("cby");
    String[] elements_color = {"Red","Blue","Green","Orange","Yellow" };
    col = new JComboBox(elements_color);
    col.addActionListener(this);
    col.setActionCommand("col");
    gr = new Graph();
    JPanel top = new JPanel(new BorderLayout());
    JPanel inputs = new JPanel(new GridLayout(6,1));
    inputs.add(button1);
    inputs.add(button2);
    inputs.add(button3);
    inputs.add(button4);
    inputs.add(button5);
    inputs.add(cbx);
    inputs.add(cby);
    inputs.add(col);
    top.add(gr,BorderLayout.CENTER);
    top.add(inputs,BorderLayout.WEST);
    getContentPane().add(BorderLayout.CENTER, top);
    setSize(500,300);//set window size
    //take care of actions
    public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (command.equals("Quit")){
    System.exit(0);//terminate program
    else if (command.equals("Rectangle")){
    //add Rectangle to graph at
    //position x,y and with certain color
    gr.addRectangle(x,y,color);
    else if (command.equals("Circle")){
    gr.addCircle(x,y,color);
    else if (command.equals("Reset")){
    else if (command.equals("Triangle")){
    else if (command.equals("Ellipse")){
    else if (command.equals("cbx")){
    x=Integer.valueOf((String)((JComboBox)e.getSource()).getSelectedItem()).intValue();
    else if (command.equals("cby")){
    y=Integer.valueOf((String)((JComboBox)e.getSource()).getSelectedItem()).intValue();
    else if (command.equals("col")){
    String temp=(String)((JComboBox)e.getSource()).getSelectedItem();
    if (temp=="Red") color=Color.red;
    else if (temp=="Blue") color=Color.blue;
    else if (temp=="Green") color=Color.green;
    else if (temp=="pink") color=Color.pink;
    else if (temp=="lightGray") color=Color.lightGray;
    //main program
    public static void main(String [] args) {
    Frame appl = new Frame();
    appl.setVisible(true);
    Thanks in advance
    Marina

    Hi,
    You are very lucky that I'm currently boored. You should never tag a question as urgent. It might be urgent to you, but not to us who answer. And you should also use code formatting when you post code (see the formatting tips, or use the code-button).
    I made some changes to your Graph class. The most important thing is the abstract draw method that I added to the GeomFigur class.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Graph extends JPanel {
        LinkedList figures;
        public Graph() {
            setBackground(Color.white);
            figures = new LinkedList();
        int z;
        abstract class GeomFigur {
            protected Color color;
            public GeomFigur(Color color) {
                this.color = color;
            public abstract void move(Point p);
            public abstract void draw(Graphics g);
        abstract class Line extends GeomFigur {
            Point p1, p2;
            public Line(Color c, Point p1, Point p2) {
                super(c);
                this.p1 = new Point(p1);
                this.p2 = new Point(p2);
            public String toString() {
                return "Line from " + p1 + " to " + p2;
            public void move(Point dist) {
                p1.move(dist.x, dist.y);
                p2.move(dist.x, dist.y);
        class Rectangle extends Line {
            public Rectangle(Color c, Point p1, Point p2) {
                super(c, p1, p2);
            public String toString() {
                return "Rectangle from " + p1 + " to " + p2;
            public void draw(Graphics g) {
                System.out.println("Draw rectangle at " + p1 + " with color " + color);
                g.setColor(Color.black);
                g.drawRect(p1.x, p1.y, 20, 20);
                g.setColor(color);
                g.fillRect(p1.x, p1.y, 20, 20);
        class Circle extends GeomFigur {
            Point centre;
            int radius;
            public Circle(Color c, Point centre, int radius) {
                super(c);
                this.centre = new Point(centre);
                this.radius = radius;
            public String toString() {
                return "Circle, centre " + centre + ", radius " + radius;
            public void move(Point dist) {
                centre.move(dist.x, dist.y);
            public void draw(Graphics g) {
                System.out.println("Draw circle at " + centre + " with color " + color);
                g.setColor(Color.black);
                g.drawOval(centre.x, centre.y, 20, 20);
                g.setColor(color);
                g.fillOval(centre.x, centre.y, 20, 20);
        public void addRectangle(int x, int y, Color col) {
            System.out.println("x,y,col " + x + ":" + y + ":" + col);
            Rectangle r = new Rectangle(col, new Point(x, y), new Point(x + 20, y + 20));
            figures.addLast(r);
            repaint();
        public void addCircle(int x, int y, Color col) {
            System.out.println("x,y,col" + x + ":" + y + ":" + col);
            Circle c = new Circle(col, new Point(x, y), 1);
            figures.addLast(c);
            repaint();
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0; i < figures.size(); i++) {
                GeomFigur drawable = (GeomFigur)figures.get(i);
                drawable.draw(g);
    }/Kaj

  • Need help to drag a rectangle to define a zoom level

    Can some help me figure this out. I am trying to draw some graphics on a JPanel, then drag a rectangle to define a new zoom extent. I am having problems understanding how to do this with the AffineTransform. If you run the following code, you will see what I am trying to do....
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    public class TestCase extends JPanel implements MouseListener, MouseMotionListener {
      private Integer _startX = 0; // start x for dragging of rectangle
      private Integer _startY = 0; // start y for dragging of rectangle
      private Integer _lastX = 0; // end x for dragging of rectangle
      private Integer _lastY = 0; // end y for dragging of rectangle
      private boolean _isDragging = false;
      private Rectangle _rect = new Rectangle();
      private Rectangle[] _rects = null;
      private Color[] _colors = null;
      protected BufferedImage _imageBuffer = null;
      protected AffineTransform _xform = null;
      public TestCase() {
        _xform = new AffineTransform();
        _rects = new Rectangle[6];
        _rects[0] = new Rectangle(0, 0, 100, 100);
        _rects[1] = new Rectangle(100, 100, 100, 100);
        _rects[2] = new Rectangle(200, 200, 100, 100);
        _rects[3] = new Rectangle(300, 300, 100, 100);
        _rects[4] = new Rectangle(200, 0, 50, 50);
        _rects[5] = new Rectangle(250, 50, 50, 50);
        _colors = new Color[6];
        _colors[0] = Color.RED;
        _colors[1] = Color.WHITE;
        _colors[2] = Color.BLUE;
        _colors[3] = Color.GREEN;
        _colors[4] = Color.YELLOW;
        _colors[5] = Color.CYAN;
        setBackground(Color.LIGHT_GRAY);
        addMouseListener(this);
        addMouseMotionListener(this);
      // The next three methods enable user to drag a retangle
      // First, set the start points of the rectangle
      public void mousePressed(MouseEvent e) {
        _startX = new Integer(e.getX());
        _startY = new Integer(e.getY());
        _lastX = new Integer(e.getX());
        _lastY = new Integer(e.getY());
        _isDragging = true;
      // Second, drag the rectangle
      public void mouseDragged(MouseEvent e) {
        _lastX = new Integer(e.getX());
        _lastY = new Integer(e.getY());
        repaint();
      // Third, complete the rectangle, then zoom
      public void mouseReleased(MouseEvent event) {
        _lastX = new Integer(event.getX());
        _lastY = new Integer(event.getY());
        _lastX = new Integer(event.getX());
        _lastY = new Integer(event.getY());
        Rectangle rect = new Rectangle(_startX, _startY, _lastX - _startX, _lastY - _startY);
        Double widPanel = new Integer(this.getWidth()).doubleValue() / _xform.getScaleX();
        Double hgtPanel = new Integer(getHeight()).doubleValue() / _xform.getScaleY();
        Double widRect = rect.getWidth();
        Double hgtRect = rect.getHeight();
        Double scalex = widPanel.doubleValue() / widRect;
        Double scaley = hgtPanel.doubleValue() / hgtRect;
        Double translatex = _startX.doubleValue() * scalex;
        Double translatey = _startY.doubleValue() * scaley;
        _xform.setToScale(scalex, scaley);
        _xform.setToTranslation(translatex, translatey);
        _isDragging = false;
        repaint();
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if(_isDragging){
          g2.drawImage(_imageBuffer, 0, 0, this);
          g2.setPaint(Color.RED);
          g2.drawRect(_startX, _startY, _lastX - _startX, _lastY - _startY);
        else{
          paintPanel(g2);
      protected void paintPanel(Graphics2D g) {
        Double width = this.getSize().getWidth();
        Double height = this.getSize().getHeight();
        Dimension size = this.getSize();
        _imageBuffer = new BufferedImage(Math.round(width.floatValue()), Math.round(height.floatValue()), BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) _imageBuffer.getGraphics();
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
        for(int i = 0; i <= _rects.length - 1; i++){
          Rectangle rect = _rects;
    Shape shape = _xform.createTransformedShape(rect);
    graphics.setColor(_colors[i]);
    graphics.fill(shape);
    g.drawImage(_imageBuffer, 0, 0, this);
    protected void zoomToExtent() {
    _xform.setToIdentity();
    repaint();
    public void mouseClicked(MouseEvent event) {
    public void mouseEntered(MouseEvent event) {
    public void mouseExited(MouseEvent event) {
    public void mouseMoved(MouseEvent event) {
    public static void main(String[] args) {
    final TestCase test = new TestCase();
    JButton btnFullExtent = new JButton("Reset");
    btnFullExtent.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    test.zoomToExtent();
    JToolBar toolBar = new JToolBar();
    toolBar.add(btnFullExtent);
    final JFrame f = new JFrame();
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(toolBar, BorderLayout.NORTH);
    f.getContentPane().add(new TestCase(), BorderLayout.CENTER);
    f.setSize(600, 400);
    f.setVisible(true);

    I modified you code a little bit, just so I could improve my understanding. I tried to swap out the class level scale and translate variables, with an AffineTransform object, but wasn't able to get it working? Do you know why this won't work?
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Rectangle2D;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    public class TestCase extends JPanel implements MouseListener, MouseMotionListener {
      private Point start;
      private Point end;
      private boolean dragging = false;
      private double zoom_x = 1.0;
      private double zoom_y = 1.0;
      private double translateX;
      private double translateY;
      private Rectangle[] _rects = null;
      private Color[] _colors = null;
      public TestCase() {
        setBackground(Color.LIGHT_GRAY);
        _rects = new Rectangle[6];
        _rects[0] = new Rectangle(0, 0, 100, 100);
        _rects[1] = new Rectangle(100, 100, 100, 100);
        _rects[2] = new Rectangle(200, 200, 100, 100);
        _rects[3] = new Rectangle(300, 300, 100, 100);
        _rects[4] = new Rectangle(200, 0, 50, 50);
        _rects[5] = new Rectangle(250, 50, 50, 50);
        _colors = new Color[6];
        _colors[0] = Color.RED;
        _colors[1] = Color.WHITE;
        _colors[2] = Color.BLUE;
        _colors[3] = Color.GREEN;
        _colors[4] = Color.YELLOW;
        _colors[5] = Color.CYAN;
        addMouseListener(this);
        addMouseMotionListener(this);
      public void mousePressed(MouseEvent e) {
        start = e.getPoint();
        dragging = true;
      public void mouseDragged(MouseEvent e) {
        end = e.getPoint();
        repaint();
      public void mouseReleased(MouseEvent e) {
        end = e.getPoint();
        double visibleWidth = getWidth();
        double visibleHeight = getHeight();
        double selectedWidth = Math.abs(end.getX() - start.getX());
        double selectedHeight = Math.abs(end.getY() - start.getY());
        double zoomFactorX = visibleWidth / selectedWidth;
        double zoomFactorY = visibleHeight / selectedHeight;
        translateX -= start.x / zoom_x;
        translateY -= start.y / zoom_y;
        zoom_x *= zoomFactorX;
        zoom_y *= zoomFactorY;
        dragging = false;
        repaint();
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        paintShapes((Graphics2D) g2.create());
        if(dragging){
          g2.setPaint(Color.RED);
          g2.drawRect(start.x, start.y, end.x - start.x, end.y - start.y);
      private void paintShapes(Graphics2D g2) {
        System.out.println("translateX=" + translateX + ", translateY=" + translateY + ", zoom_x=" + zoom_x + ", zoom_y=" + zoom_y);
        g2.scale(zoom_x, zoom_y);
        g2.translate(translateX, translateY);
        for(int i = 0; i <= _rects.length - 1; i++){
          Rectangle rect = _rects;
    g2.setColor(_colors[i]);
    g2.fill(rect);
    public void reset() {
    zoom_x = 1.0;
    zoom_y = 1.0;
    translateX = 0;
    translateY = 0;
    repaint();
    public void mouseClicked(MouseEvent event) {
    public void mouseEntered(MouseEvent event) {
    public void mouseExited(MouseEvent event) {
    public void mouseMoved(MouseEvent event) {
    public static void main(String[] args) {
    final TestCase test = new TestCase();
    JButton btnFullExtent = new JButton("Reset");
    btnFullExtent.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    test.reset();
    JToolBar toolBar = new JToolBar();
    toolBar.add(btnFullExtent);
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(toolBar, BorderLayout.NORTH);
    f.getContentPane().add(test, BorderLayout.CENTER);
    f.setSize(600, 400);
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • I need help to draw in a frame, please

    Hi Im new to java and I need some help to draw a rainbow in a frame. I already made the frame , but i dont know how to draw inside the frame.
    here is my code so far:
    import java.awt.*;
    import javax.swing.*;
    public class Regnbue {
         public static void main(String[]args){
              JFrame ramme = new JFrame();
              ramme.setSize(600,300);
              Container cp = ramme.getContentPane();
              cp.setBackground(Color.white);
              ramme.setVisible(true);
    any help to finish this simple draw would be nice!!
    thanx

    I forgot , here is my code so far :
    import java.awt.*;
    import javax.swing.*;
    public class Regnbue {
         public static void main(String[]args){
              Rainbowpanel r= new Rainbowpanel();// her is where i make
    // my frame I think.
              JFrame ramme = new JFrame();
              ramme.setSize(600,300);
              Container cp = ramme.getContentPane();
              cp.setBackground(Color.white);
              ramme.setVisible(true);
    class Rainbowpanel extends JPanel {
         public void paintComponent(Graphics g) {// this is the part that I
    // dont understand, how can I put the arc into the container above??
              super.paintComponent(g);
              g.fillArc(5, 5, 10, 50, 0, 180);
         thanks
    elektropan

  • Need help to draw a graph from the output I get with my program please

    Hi all,
    I please need help with this program, I need to display the amount of money over the years (which the user has to enter via the textfields supplied)
    on a graph, I'm not sure what to do further with my program, but I have created a test with a System.out.println() method just to see if I get the correct output and it looks fine.
    My question is, how do I get the input that was entered by the user (the initial deposit amount as well as the number of years) and using these to draw up the graph? (I used a button for the user to click after he/she has entered both the deposit and year values to draw the graph but I don't know how to get this to work?)
    Please help me.
    The output that I got looked liked this: (just for a test!) - basically this kind of output must be shown on the graph...
    The initial deposit made was: 200.0
    After year: 1        Amount is:  210.00
    After year: 2        Amount is:  220.50
    After year: 3        Amount is:  231.53
    After year: 4        Amount is:  243.10
    After year: 5        Amount is:  255.26
    After year: 6        Amount is:  268.02
    After year: 7        Amount is:  281.42
    After year: 8        Amount is:  295.49
    After year: 9        Amount is:  310.27
    After year: 10        Amount is:  325.78
    After year: 11        Amount is:  342.07
    After year: 12        Amount is:  359.17
    After year: 13        Amount is:  377.13
    After year: 14        Amount is:  395.99
    After year: 15        Amount is:  415.79
    After year: 16        Amount is:  436.57
    After year: 17        Amount is:  458.40And here is my code that Iv'e done so far:
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Math;
    import java.text.DecimalFormat;
    public class CompoundInterestProgram extends JFrame implements ActionListener {
        JLabel amountLabel = new JLabel("Please enter the initial deposit amount:");
        JTextField amountText = new JTextField(5);
        JLabel yearsLabel = new JLabel("Please enter the numbers of years:");
        JTextField yearstext = new JTextField(5);
        JButton drawButton = new JButton("Draw Graph");
        public CompoundInterestProgram() {
            super("Compound Interest Program");
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            amountText.addActionListener(this);
            yearstext.addActionListener(this);
            JPanel panel = new JPanel();
            panel.setBackground(Color.white);
            panel.add(amountLabel);
            amountLabel.setToolTipText("Range of deposit must be 20 - 200!");
            panel.add(amountText);
            panel.add(yearsLabel);
            yearsLabel.setToolTipText("Range of years must be 1 - 25!");
            panel.add(yearstext);
            panel.add(drawButton);
            add(panel);
            setVisible(true);
            public static void main(String[] args) {
                 DecimalFormat dec2 = new DecimalFormat( "0.00" );
                CompoundInterestProgram cip1 = new CompoundInterestProgram();
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.getContentPane().add(new GraphPanel());
                f.setSize(500, 500);
                f.setLocation(200,200);
                f.setVisible(true);
                Account a = new Account(200);
                System.out.println("The initial deposit made was: " + a.getBalance() + "\n");
                for (int year = 1; year <= 17; year++) {
                      System.out.println("After year: " + year + "   \t" + "Amount is:  " + dec2.format(a.getBalance() + a.calcInterest(year)));
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
    class Account {
        double balance = 0;
        double interest = 0.05;
        public Account() {
             balance = 0;
             interest = 0.05;
        public Account(int deposit) {
             balance = deposit;
             interest = 0.05;
        public double calcInterest(int year) {
               return  balance * Math.pow((1 + interest), year) - balance;
        public double getBalance() {
              return balance;
    class GraphPanel extends JPanel {
        public GraphPanel() {
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.red);
    }Your help would be much appreciated.
    Thanks in advance.

    watertownjordan wrote:
    http://www.jgraph.com/jgraph.html
    The above is also good.Sorry but you need to look a bit more closely at URLs that you cite. What the OP wants is a chart (as in X against Y) not a graph (as in links and nodes) . 'jgraph' deals with links and nodes.
    The best free charting library that I know of is JFreeChart from www.jfree.org.

  • Need help making ball move and bounce off of sides of JPanel

    I'm currently working on a program that creates a ball of random color. I'm trying to make the ball move around the JPanel it is contained in and if it hits a wall it should bounce off of it. I have been able to draw the ball and make it fill with a random color. However, I cannot get it to move around and bounce off the walls. Below is the code for the class that creates the ball. Should I possible be using multithreads? As part of the project requirements I will need to utilizes threads and include a runnable. However, I wanted to get it working with one first and than add to it as the final product needs to include new balls being added with each mouse click. Any help would be appreciated.
    Thanks
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    public class Ball extends JPanel{
        Graphics g;
        int rval; // red color value
        int gval; // green color value
        int bval; // blue color value
        private int x = 1;
        private int y = 1;
        private int dx = 2;
        private int dy = 2;
        public void paintComponent(Graphics g){
            for(int counter = 0; counter < 100; counter++){
                // randomly chooses red, green and blue values changing color of ball each time
                rval = (int)Math.floor(Math.random() * 256);
                gval = (int)Math.floor(Math.random() * 256);
                bval = (int)Math.floor(Math.random() * 256);
                super.paintComponent(g);
                g.drawOval(0,0,30,30);   // draws circle
                g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
                g.fillOval(x,y,30,30); // adds color to circle
                move(g);
        } // end paintComponent
        public void move(Graphics g){
            g.fillOval(x, y, 30, 30);
            x += dx;
            y += dy;
            if(x < 0){
                x = 0;
                dx = -dx;
            if (x + 30 >= 400) {
                x = 400 - 30;
                dx = -dx;
            if (y < 0) {
                y = 0;
                dy = -dy;
            if (y + 30 >= 400) {
                y = 400 - 30;
                dy = -dy;
            g.fillOval(x, y, 30, 30);
            g.dispose();
    } // end Ball class

    Create a bounding box using the size of the panel. Each time you move the ball, check that it's still inside the box. If it isn't, then change it's direction. You know where the ball is, (x, y), so just compare those values to the boundary values.

  • Need help: BufferedImage and zooming

    please help me understand what i am doing wrong. i am having a hard time understanding the concept behind BufferedImage and zooming. the applet code loads an image as its background. after loading, you can draw line segments on it. but when i try to zoom in, the image in the background remains the same in terms of size, line segments are the only ones that are being zoomed, and the mouse coordinates are confusing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.image.*;
    public class Testing extends JApplet {
         private String url;
         private Map map;
         public void init() {
         public void start()
              url = "http://localhost/image.gif";
                  map = new Map(url);
                 getContentPane().add(map, "Center");
                 validate();
                 map.validate();
    class Map extends JPanel implements MouseListener, MouseMotionListener{
         private Image image;
         private ArrayList<Point2D> points;
         private ArrayList<Line2D> lineSegment;
         private Point2D startingPoint;
         private int mouseX;
         private int mouseY;
         private BufferedImage bimg;
         private AffineTransform xform;
         private AffineTransform inverse;
         private double zoomFactor = 1;
         public Map(String url)
                         super();
              //this.image = image;
              try
                   image = ImageIO.read(new URL(url));
              catch(Exception e)
              Insets insets = getInsets();
              xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
              xform.scale(zoomFactor,zoomFactor);
              try {
                   inverse = xform.createInverse();
              } catch (NoninvertibleTransformException e) {
                   System.out.println(e);
              points = new ArrayList();
              startingPoint = new Point();
              bimg = new BufferedImage(this.image.getWidth(this), this.image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
              repaintBImg();
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D)g;
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            bimg = (BufferedImage)image;
            g2d.drawRenderedImage(bimg, xform);
            if(!points.isEmpty())
                 for(int i=0; i<points.size(); i++)
                      if(i > 0)
                           drawLineSegment(g2d,points.get(i-1),points.get(i));
                      drawPoint(g2d, points.get(i));
            if(startingPoint != null)
                drawTempLine(startingPoint, g2d);
            else
                mouseX = 0;
                mouseY = 0;
         private void repaintBImg()
              bimg.flush();
              Graphics2D g2d = bimg.createGraphics();
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            g2d.drawRenderedImage(bimg, xform);
            g2d.dispose();
         private void drawPoint(Graphics2D g2d, Point2D p)
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
              g2d.setColor(Color.ORANGE);
              g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
         private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2)
              double x1 = p1.getX() * zoomFactor;
                 double y1 = p1.getY() * zoomFactor;
                 double x2 = p2.getX() * zoomFactor;
                 double y2 = p2.getY() * zoomFactor;
                 g2d.setColor(Color.RED);
                 g2d.setStroke(new BasicStroke(3.0F));
                 g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
             private void drawTempLine(Point2D p, Graphics2D g2d)
                 int startX = (int)(p.getX() * zoomFactor);
                 int startY = (int)(p.getY() * zoomFactor);
                 if(mouseX != 0 && mouseY != 0)
                         g2d.setColor(Color.RED);
                          g2d.setStroke(new BasicStroke(2.0F));
                          g2d.drawLine(startX, startY, mouseX, mouseY);
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              mouseX = (int)(e.getX()*zoomFactor);
              mouseY = (int)(e.getY()*zoomFactor);
              repaint();
         public void mousePressed(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
                   if(points.size() > 0)
                        startingPoint = points.get(points.size()-1);
                        mouseX = mouseY = 0;
                   repaint();
              else if(e.getButton() == 2)
                   zoomFactor = zoomFactor + .05;
                   repaintBImg();
              else if(e.getButton() == 3)
                   zoomFactor = zoomFactor - .05;
                   repaintBImg();
         public void mouseReleased(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
              repaint();
         public void mouseEntered(MouseEvent mouseevent)
         public void mouseExited(MouseEvent mouseevent)
         public void mouseMoved(MouseEvent mouseevent)
    }Message was edited by:
    hardc0d3r

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ZoomTesting extends JApplet {
        public void init() {
            //String dir = "file:/" + System.getProperty("user.dir");
            //System.out.printf("dir = %s%n", dir);
            String url = "http://localhost/image.gif";
                         //dir + "/images/cougar.jpg";
            MapPanel map = new MapPanel(url);
            getContentPane().add(map, "Center");
        public static void main(String[] args) {
            JApplet applet = new ZoomTesting();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class MapPanel extends JPanel implements MouseListener, MouseMotionListener {
        private BufferedImage image;
        private ArrayList<Point2D> points;
        private Point2D startingPoint;
        private int mouseX;
        private int mouseY;
        private AffineTransform xform;
        private AffineTransform inverse;
        RenderingHints hints;
        private double zoomFactor = 1;
        public MapPanel(String url) {
            super();
            try {
                image = ImageIO.read(new URL(url));
            } catch(Exception e) {
                System.out.println(e.getClass().getName() +
                                   " = " + e.getMessage());
            Map<RenderingHints.Key, Object> map =
                        new HashMap<RenderingHints.Key, Object>();
            map.put(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            map.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints = new RenderingHints(map);
            setTransforms();
            points = new ArrayList<Point2D>();
            startingPoint = new Point();
            addMouseListener(this);
            addMouseMotionListener(this);
        private void setTransforms() {
            Insets insets = getInsets();
            xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
            xform.scale(zoomFactor,zoomFactor);
            try {
                inverse = xform.createInverse();
            } catch (NoninvertibleTransformException e) {
                System.out.println(e);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setRenderingHints(hints);
            g2d.drawRenderedImage(image, xform);
            if(!points.isEmpty()) {
                for(int i=0; i<points.size(); i++) {
                    if(i > 0)
                        drawLineSegment(g2d,points.get(i-1),points.get(i));
                    drawPoint(g2d, points.get(i));
            if(startingPoint != null) {
                drawTempLine(startingPoint, g2d);
            } else {
                mouseX = 0;
                mouseY = 0;
        private void drawPoint(Graphics2D g2d, Point2D p) {
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
            g2d.setColor(Color.ORANGE);
            g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
        private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2) {
            double x1 = p1.getX() * zoomFactor;
            double y1 = p1.getY() * zoomFactor;
            double x2 = p2.getX() * zoomFactor;
            double y2 = p2.getY() * zoomFactor;
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(3.0F));
            g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
        private void drawTempLine(Point2D p, Graphics2D g2d) {
            int startX = (int)(p.getX() * zoomFactor);
            int startY = (int)(p.getY() * zoomFactor);
            if(mouseX != 0 && mouseY != 0) {
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(2.0F));
                g2d.drawLine(startX, startY, mouseX, mouseY);
        public void mouseClicked(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {
            mouseX = (int)(e.getX()*zoomFactor);
            mouseY = (int)(e.getY()*zoomFactor);
            repaint();
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
                if(points.size() > 0) {
                    startingPoint = points.get(points.size()-1);
                    mouseX = mouseY = 0;
            } else if(e.getButton() == 2) {
                zoomFactor = zoomFactor + .05;
                setTransforms();
            } else if(e.getButton() == 3) {
                zoomFactor = zoomFactor - .05;
                setTransforms();
            repaint();
        public void mouseReleased(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
            repaint();
        public void mouseEntered(MouseEvent mouseevent) {}
        public void mouseExited(MouseEvent mouseevent) {}
        public void mouseMoved(MouseEvent mouseevent) {}
    }

  • Can you help me with mouse pressed method please?

    hi
    can you help me with my problem please, player label doesn't show up in the applet and the draw string method it doesn't draw any strings like X or O for the game I don't know what is the problem maybe it is with MousePressed method which is in Board class. I tried to write the code of the location many times I'm not sure if the problem comes from there.
    there is no error in my code, but it doesn't work.
    this is class Board which has the mouseListener
    class Board extends JPanel  implements MouseListener, MouseMotionListener
        private JLabel playerlabel; 
         private boolean play;
         private boolean start;
        private int turn; 
        private Square squares[][];
      private Player myplayer[][];
         public Board()
              setBackground( Color.WHITE );
              playerlabel = new JLabel( "X player first" );
              //playerlabel.setLayout(null);
         //     playerlabel.setLocation(500,500);
              add( playerlabel );
              play = true;
              turn = 1;
             squares = new Square[3][3];
             myplayer = new Player[3][3];
             int x = 40;
              int y = 40;
              for (int i=0; i<3; i++){
                   x = 40;
                   for (int j=0; j<3; j++){
                        Square s = new Square( x,y );
                        squares[i][j] = s;
                        x +=50;
                   y +=50;
                this.addMouseListener(this);
            this.addMouseMotionListener(this);
          public void mouseClicked( MouseEvent event ){}
          public void mouseMoved( MouseEvent event ){}
          public void mouseEntered( MouseEvent event ){}
          public void mouseExited( MouseEvent event ){}
          public void mousePressed( MouseEvent event )
          {int xPos = event.getX();
                  int yPos = event.getY();
                    if(play && turn ==1){
                    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "X";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(1);
                                       playerlabel.setText( "O Player Turn" );
                                       turn = 2;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 2;
                                       playerlabel.setText( "O Player Turn" );
                                       repaint();
              if ( play && turn ==2 )
    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "O";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(2);
                                       playerlabel.setText( "X Player Turn" );
                                       turn = 1;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 1;
                                       playerlabel.setText( "X Player Turn" );
                                       repaint();
          public void mouseReleased( MouseEvent event )
          public void mouseDragged( MouseEvent event )
         public void Win(){
              if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
                   if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Vertically win
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Diagonal win
                    if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
         }//end win
    public void setTurn(int t)
              turn = t;
              playerlabel.setText( "X Player Plays First" );
         public void paintComponent( Graphics g )
               super.paintComponent( g );
               this.setBackground( Color.WHITE );
              for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                        g.setColor( Color.BLACK );
                         g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );     
               for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                         myplayer[i][j].draw(g);     
            //End of paintComponent   
    }and this is the whole code of my program.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    class Player{
         private int xCoordinate;
         private int yCoordinate;
        private String playerText;
      public   Player(int x, int y, String t)
            playerText = t;
            xCoordinate = x;
            yCoordinate = y;
        public void draw(Graphics g)
               g.drawString(playerText,  xCoordinate, yCoordinate);
         public void SetText(String t)
         { playerText = t;
    }//end player
    class Square
         private int x;
         private int y;
         private int occupied;
         public Square(int x1, int y1)
              x = x1;
              y= y1;
              occupied = 0;
         public void setX(int x1)
              x = x1;
         public int getX()
              return x;
         public void setY(int y1)
              y = y1;
         public int getY()
              return y;
         public void setOccupied(int o)
              occupied = o;
         public int getOccupied()
              return occupied;
    public class TicTac extends JApplet implements ActionListener
    { private JPanel panel;
         private JButton newgame;
         private Board B;
         public void init()
              B = new Board();
              add( B, BorderLayout.CENTER );
              panel = new JPanel();
               newgame = new JButton( "New Game" );
               panel.add( newgame);
               add( panel, BorderLayout.SOUTH );
               newgame.addActionListener(this);
              public void actionPerformed( ActionEvent ev)
               {     Object source = ev.getSource();
         if (source == newgame)
                    {remove(B);
                   repaint();
              B = new Board();
                   add( B, BorderLayout.CENTER );
         B.setTurn(1);
                   repaint();
                   validate();
            }//end class TicTac
    class Board extends JPanel  implements MouseListener, MouseMotionListener
        private JLabel playerlabel; 
         private boolean play;
         private boolean start;
        private int turn; 
        private Square squares[][];
      private Player myplayer[][];
         public Board()
              setBackground( Color.WHITE );
              playerlabel = new JLabel( "X player first" );
              //playerlabel.setLayout(null);
         //     playerlabel.setLocation(500,500);
              add( playerlabel );
              play = true;
              turn = 1;
             squares = new Square[3][3];
             myplayer = new Player[3][3];
             int x = 40;
              int y = 40;
              for (int i=0; i<3; i++){
                   x = 40;
                   for (int j=0; j<3; j++){
                        Square s = new Square( x,y );
                        squares[i][j] = s;
                        x +=50;
                   y +=50;
                this.addMouseListener(this);
            this.addMouseMotionListener(this);
          public void mouseClicked( MouseEvent event ){}
          public void mouseMoved( MouseEvent event ){}
          public void mouseEntered( MouseEvent event ){}
          public void mouseExited( MouseEvent event ){}
          public void mousePressed( MouseEvent event )
          {int xPos = event.getX();
                  int yPos = event.getY();
                    if(play && turn ==1){
                    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "X";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(1);
                                       playerlabel.setText( "O Player Turn" );
                                       turn = 2;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 2;
                                       playerlabel.setText( "O Player Turn" );
                                       repaint();
              if ( play && turn ==2 )
    for (int i=0; i<3; i++){
                        for (int j=0; j<3; j++){
                             int x = squares[i][j].getX();
                             int y = squares[i][j].getY();
                             if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
                                  if( squares[i][j].getOccupied() ==0 ){
                                       String ptext;
                                       ptext = "O";
                                       Player p = new Player(x, y,ptext);
                                       myplayer[i][j] = p;
                                       squares[i][j].setOccupied(2);
                                       playerlabel.setText( "X Player Turn" );
                                       turn = 1;
                                       repaint();
                                       Win();
                                  else{
                                       turn = 1;
                                       playerlabel.setText( "X Player Turn" );
                                       repaint();
          public void mouseReleased( MouseEvent event )
          public void mouseDragged( MouseEvent event )
         public void Win(){
              if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
                   if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Vertically win
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else      if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              //Diagonal win
                    if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
              {playerlabel.setText("Player 1 X WON THE GAME!");
              play =false;          }
               if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
              else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
              {playerlabel.setText("Player 2 O WON THE GAME!");
              play =false;          }
         }//end win
    public void setTurn(int t)
              turn = t;
              playerlabel.setText( "X Player Plays First" );
         public void paintComponent( Graphics g )
               super.paintComponent( g );
               this.setBackground( Color.WHITE );
              for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                        g.setColor( Color.BLACK );
                         g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );     
               for (int i=0; i<3; i++){
                   for (int j=0; j<3; j++){
                         myplayer[i][j].draw(g);     
            //End of paintComponent   
            Edited by: mshadows on May 18, 2008 7:53 AM

    I was playing with this a little bit and came up with this game model, something that I'm sure can be improved upon greatly:
    TttXO.java
    an enum to encapsulate X vs O. I could use a boolean here since it has 2 states, but this seems more intuitive to me
    package dy08.m05.ttt;
    * tic tac toe encapsulation of X vs O
    * @author Pete
    public enum TttXO
        X, O
    }TttCell.java
    encapsulates an individual cell in the tictactoe grid.
    package dy08.m05.ttt;
    * Tic Tac Toe Game cell
    * can be occupied or not
    * can hold TttXO X or O or null 
    * @author Pete
    public class TttCell
        private boolean occupied = false;
        private TttXO xo = null;
        public TttCell()
         * sets a Square for either x or o
         * @param TttXO
         * @return true if successful, false if already occupied
        public boolean setXO(TttXO xo)
            if (occupied)
                return false;
            else
                occupied = true;
                this.xo = xo;
                return true;
        public void reset()
            occupied = false;
            xo = null;
        public boolean isOccupied()
            return occupied;
        public TttXO getXO()
            return xo;
        // used to test and debug the class
        public String toString()
            if (occupied)
                return xo.toString();
            else
                return "-";
    package dy08.m05.ttt;
    * Tic Tac Toe game model
    * @author Pete
    public class TttGameModel
        private TttCell[][] cellGrid = new TttCell[3][3];
        private boolean xTurn = true;
        private boolean win = false;
        public TttGameModel()
            for (int i = 0; i < cellGrid.length; i++)
                for (int j = 0; j < cellGrid.length; j++)
    cellGrid[i][j] = new TttCell();
    public void reset()
    xTurn = true;
    win = false;
    for (int i = 0; i < cellGrid.length; i++)
    for (int j = 0; j < cellGrid[i].length; j++)
    cellGrid[i][j].reset();
    public boolean isXTurn()
    return xTurn;
    public boolean isWin()
    return win;
    * @param row
    * @param col
    * @return true if valid move, false if game already over or cell occupied
    public boolean takeTurn(int col, int row)
    TttXO currentXO = TttXO.O;
    TttCell cell = cellGrid[row][col];
    if (win)
    return false;
    if (cell.isOccupied())
    return false;
    if (xTurn)
    currentXO = TttXO.X;
    cell.setXO(currentXO);
    win = checkWin(col, row, currentXO);
    xTurn = !xTurn; // toggle xturn
    return true;
    public boolean checkWin(int col, int row, TttXO xo)
    boolean win = false;
    // first rows and columns
    boolean temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[row][i].getXO() == xo;
    win |= temp;
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][col].getXO() == xo;
    win |= temp;
    if (row == col) // if slash diagonal
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][i].getXO() == xo;
    win |= temp;
    if (row + col == 2) // if backslash diagonal
    temp = true;
    for (int i = 0; i < 3; i++)
    temp &= cellGrid[i][2 - i].getXO() == xo;
    win |= temp;
    return win;
    // used to test and debug the class
    public String toString()
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < cellGrid.length; i++)
    for (int j = 0; j < cellGrid[i].length; j++)
    sb.append(cellGrid[i][j] + " ");
    sb.append("\n");
    if (win)
    sb.append("win! Game over");
    else
    sb.append("No winner yet");
    return sb.toString();
    // test the class
    public static void main(String[] args)
    TttGameModel model = new TttGameModel();
    checkMove(model, 0, 0);
    checkMove(model, 1, 0);
    checkMove(model, 1, 1);
    checkMove(model, 2, 0);
    checkMove(model, 1, 0); // bad move
    checkMove(model, 2, 2);
    // to test the class
    private static void checkMove(TttGameModel model, int i, int j)
    System.out.println("OK move: " + model.takeTurn(i, j));
    System.out.println(model + "\n");

Maybe you are looking for

  • File Adapter BPEL Process getting switched off

    The file adapter BPEL process reads a csv file which has a series of records in itfrom /xfer/chroot/data/aramex/accountUpdate/files. In between reading the files, the BPEL process gets switched off. The below snippet is the error we found in the doma

  • Multiple View sessions, same PC?

    View 6.0.1, Client 3.3.0 Can I have multiple View sessions from the same PC? In other words Launch the Horizon View client, login, and access a desktop Launch the Horizon View client again, login as a different user, and access a different desktop Re

  • Inserting all manner of characters into database

    Hello friends, Consider this code snippet of mine: String sentence = "My name is nameless aka 'anonymous' or \"anonymous\" ('did I hear that? Maybe!! now where were we?') -\"yawn! Am bored..."; PreparedStatement statement = connection.prepareStatemen

  • Will 20" ACD work in OS9?

    I know system requirements list 10.2.8 as minimum, but will it run in OS9 with an nVidia GeForce4 MX video card? Or would I need to get a new video card to run the wide aspect ratio resolution? thanks in advance for the help. michael PowerMac G4 Quic

  • Sorting by "x" then by "y" my table (multiple criterias ascending and descending)

    Hi, I converted some text to a table using this: function ConvertoTable(){ var myStory = app.selection[0].parentStory; var myTexts = myStory.texts[0]; //We now can convert that "texts" object to a table: //Both arguments are separated by a "comma" my