p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_java thread: No compilation errors but no Sketcher !


Message #1 by dominskis@a... on Wed, 24 Apr 2002 22:03:57
Dear People,
 I have a message (but no compilation errors) that says:

java.lang.NullPointerException
	at javax.swing.JPopupMenu.createActionComponent
(JPopupMenu.java:285)
	at javax.swing.JPopupMenu.add(JPopupMenu.java:265)
	at sketchercalculator.SketchFrame.<init>(SketchFrame.java:120)
	at sketchercalculator.SketcherCalculator.init
(SketcherCalculator.java:30)
	at sketchercalculator.SketcherCalculator.main
(SketcherCalculator.java:104)

below is the coding.
Thank you in advance,

Stan


package sketchercalculator;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.*;


//Sketcher Program version  #12

public class SketcherCalculator
{
  //declare the application window reference variable as private
  private static SketchFrame myJFrame;

  //declare the application window object
  private static SketcherCalculator theApp;

  //the data model for the sketch
  private SketchModel sketch;

 //the view of the sketch
 private SketchView view;


  public void init()
   {

     myJFrame =  new SketchFrame("Enjoying the design process", this);

     myJFrame.setSize(400,400);

     Dimension myFrameSize = myJFrame.getSize();
     Toolkit myToolkit = myJFrame.getToolkit();
     Dimension myScreenSize = myToolkit.getDefaultToolkit().getScreenSize
();

     //center the frame on the screen
     myJFrame.setLocation((myScreenSize.width -  myFrameSize.width)/2,
                         (myScreenSize.height - myFrameSize.height)/2);

    //charnge the backgroud color of the content pane
    myJFrame.getContentPane().setBackground(Color.yellow);

    //create the WindowAdapter object that is the listener for the 
myJFrame object
    myJFrame.addWindowListener(new WindowHandler() );

    //#11
    //create the model object
    sketch = new SketchModel();

    //create the view object
    view = new SketchView(this);

    //register the view with the model
    sketch.addObserver((Observer)view);

    myJFrame.getContentPane().add(view, BorderLayout.CENTER);

    myJFrame.setVisible(true);
   }

   //Return a reference to the aplication window
   public SketchFrame getWindow()
    {
     return myJFrame;
    }

    //return a referrrence to the model
    public SketchModel getModel()
     {
       return sketch;
     }

     //Return a reference to the view
     public SketchView getView()
      {
       return view;
      }




   //Handler class for window events
   class WindowHandler extends WindowAdapter
    {
      //Handler method for window closing event
        public void windowClosing(WindowEvent e)
           {
             //release window resources
             myJFrame.dispose();

             //end the application
             System.exit(0);
           }
    }

   public static void main(String[] args)
    {
         //create the application object
     theApp =  new SketcherCalculator();

     //initialize the application object
     theApp.init();

            new Calculator6();
    }
}



package sketchercalculator;

// Frame for the Sketcher application Horton version#13
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SketchFrame extends JFrame implements Constants, 
ActionListener
{
  private SketcherCalculator theApp;

  // Constructor
  public SketchFrame(String title, SketcherCalculator theApp)
  {
    setTitle(title);                              // Set the window title
    this.theApp = theApp;
    setJMenuBar(menuBar);                         // Add the menu bar to 
the window
    setDefaultCloseOperation(EXIT_ON_CLOSE);      // Default is exit the 
application

    JMenu fileMenu = new JMenu("File");           // Create File menu
    JMenu elementMenu = new JMenu("Elements");    // Create Elements menu
    JMenu helpMenu =  new JMenu("Help");          //create help menu
    fileMenu.setMnemonic('F');                    // Create shortcut
    elementMenu.setMnemonic('E');                 // Create shortcut
    helpMenu.setMnemonic('H');                    //create the shortcut
    // Create the action items for the file menu
    newAction = new FileAction("New", KeyStroke.getKeyStroke
('N',Event.CTRL_MASK ), "Create new sketch");
    openAction = new FileAction("Open", KeyStroke.getKeyStroke
('O',Event.CTRL_MASK ), "Open existing sketch");
    closeAction = new FileAction("Close", "Close sketch");
    saveAction = new FileAction("Save", KeyStroke.getKeyStroke
('S',Event.CTRL_MASK ), "Save sketch");
    saveAsAction = new FileAction("Save As...", "Save as new file");
    printAction = new FileAction("Print", KeyStroke.getKeyStroke
('P',Event.CTRL_MASK ), "Print sketch");

    // Construct the file pull down menu
    addMenuItem(fileMenu, newAction);
    addMenuItem(fileMenu, openAction);
    addMenuItem(fileMenu, closeAction);
    fileMenu.addSeparator();                                       // Add 
separator
    addMenuItem(fileMenu, saveAction);
    addMenuItem(fileMenu, saveAsAction);
    fileMenu.addSeparator();                              	   // Add 
separator
    addMenuItem(fileMenu, printAction);

    // Construct the Element pull down menu
    addMenuItem(elementMenu, lineAction = new TypeAction("Line", 
LINE, "Draw lines"));
    addMenuItem(elementMenu, rectangleAction = new  TypeAction
("Rectangle",RECTANGLE, "Draw rectangles"));
    addMenuItem(elementMenu, circleAction = new TypeAction("Circle", 
CIRCLE, "Draw circles"));
    addMenuItem(elementMenu, curveAction = new TypeAction("Curve", 
CURVE, "Draw curves"));

    elementMenu.addSeparator();

    JMenu colorMenu = new JMenu("Color");         // Color sub-menu
    elementMenu.add(colorMenu);                   // Add the sub-menu

    addMenuItem(colorMenu, redAction = new ColorAction("Red", 
Color.red, "Draw in red"));
    addMenuItem(colorMenu, yellowAction = new ColorAction("Yellow", 
Color.yellow, "Draw in yellow"));
    addMenuItem(colorMenu, greenAction = new ColorAction("Green", 
Color.green, "Draw in green"));
    addMenuItem(colorMenu, blueAction = new ColorAction("Blue", 
Color.blue, "Draw in blue"));

    menuBar.add(fileMenu);                        // Add the file menu
    menuBar.add(elementMenu);                     // Add the element menu

    // Add file buttons
    toolBar.addSeparator();                                 // Space at 
the start
    addToolBarButton(newAction);
    addToolBarButton(openAction);
    addToolBarButton(saveAction);
    addToolBarButton(printAction);

    // Add element type buttons
    toolBar.addSeparator();
    addToolBarButton(lineAction);
    addToolBarButton(rectangleAction);
    addToolBarButton(circleAction);
    addToolBarButton(curveAction);

    // Add element color buttons
    toolBar.addSeparator();
    addToolBarButton(redAction);
    addToolBarButton(yellowAction);
    addToolBarButton(greenAction);
    addToolBarButton(blueAction);
    toolBar.addSeparator();                            // Space at the end

    toolBar.setBorder(BorderFactory.createCompoundBorder(       // Toolbar 
border
                      BorderFactory.createLineBorder(Color.darkGray),
                      BorderFactory.createEmptyBorder(2,2,4,2)));

    //add the about item to the help menu
    aboutItem = new JMenuItem("About");

    //listener is the frame
    aboutItem.addActionListener(this);

    //add item to menu
    helpMenu.add(aboutItem);

    //add the help menu to the menu bar
    menuBar.add(helpMenu);


    toolBar.setFloatable(false);    // Inhibit toolbar floating
    getContentPane().add(toolBar, BorderLayout.NORTH);
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    // Disable actions
    saveAction.setEnabled(false);
    closeAction.setEnabled(false);
    printAction.setEnabled(false);


     //version#13   popup
    // Create pop-up menu
    popup.add(lineAction);
    popup.add(rectangleAction);
    popup.add(circleAction);
    popup.add(curveAction);
    popup.add(textAction);

    popup.addSeparator();
    popup.add(redAction);
    popup.add(yellowAction);
    popup.add(greenAction);
    popup.add(blueAction);

      }

  private JMenuItem addMenuItem(JMenu menu, Action action)
  {
    JMenuItem item = menu.add(action);			// Add the menu 
item

    KeyStroke keystroke = (KeyStroke)action.getValue
(action.ACCELERATOR_KEY);
    if(keystroke != null)
      item.setAccelerator(keystroke);
    item.setIcon(null);
    return item;						// Return 
the menu item
  }

  //FILE ACTION INNER CLASS
  class FileAction extends AbstractAction
  {
    // Constructor
    FileAction(String name)
    {
      super(name);
      String iconFileName = "Images/" + name + ".gif";
      if(new File(iconFileName).exists())
        putValue(SMALL_ICON, new ImageIcon(iconFileName));
    }

    // Constructor
    FileAction(String name, KeyStroke keystroke)
    {
      this(name);
      if(keystroke != null)
        putValue(ACCELERATOR_KEY, keystroke);
    }

    // Constructor
    FileAction(String name, KeyStroke keystroke, String tooltip)
    {
      this(name, keystroke);                          // Call the other 
constructor
      if(tooltip != null)                             // If there is 
tooltip text
        putValue(SHORT_DESCRIPTION, tooltip);         // ...squirrel it 
away
    }

    // Constructor
    FileAction(String name, String tooltip)
    {
      this(name);                                     // Call the other 
constructor
      if(tooltip != null)                             // If there is 
tooltip text
        putValue(SHORT_DESCRIPTION, tooltip);         // ...squirrel it 
away
    }

    // Event handler
    public void actionPerformed(ActionEvent e)
    {
      // We will add action code here eventually...
    }
  }

  //TYPE ACTION INNER CLASS
  class TypeAction extends AbstractAction
  {
    // Constructor
    TypeAction(String name, int typeID)
    {
      super(name);
      this.typeID = typeID;
      String iconFileName = "Images/" + name + ".gif";
      if(new File(iconFileName).exists())
        putValue(SMALL_ICON, new ImageIcon(iconFileName));
    }

    // Constructor
    TypeAction(String name, int typeID, String tooltip)
    {
      this(name, typeID);
      if(tooltip != null)                               // If there is a 
tooltip
        putValue(SHORT_DESCRIPTION, tooltip);           // ...squirrel it 
away
    }

    public void actionPerformed(ActionEvent e)
    {  elementType = typeID;
       statusBar.setTypePane(typeID);
    }

    private int typeID;
  }

  //COLOR ACTION INNER CLASS
  class ColorAction  extends AbstractAction
  {
    // Constructor
    public ColorAction(String name, Color color)
    {
      super(name);
      this.color = color;
      String iconFileName = "Images/" + name + ".gif";
      if(new File(iconFileName).exists())
        putValue(SMALL_ICON, new ImageIcon(iconFileName));
    }

    // Constructor
    public ColorAction(String name, Color color, String tooltip)
    {
      this(name, color);
      if(tooltip != null)                               // If there is a 
tooltip
        putValue(SHORT_DESCRIPTION, tooltip);           // ...squirrel it 
away
    }

    // Constructor
    public void actionPerformed(ActionEvent e)
    {
      elementColor = color;
      statusBar.setColorPane(color);
    }

    private Color color;
  }

  // File actions
  private FileAction newAction, openAction, closeAction, saveAction, 
saveAsAction, printAction;

  // Element type actions
  private TypeAction lineAction, rectangleAction, circleAction, 
curveAction, textAction;

  // Element color actions
  private ColorAction redAction, yellowAction,
                      greenAction, blueAction;

  private JMenuBar menuBar = new JMenuBar();               // Window menu 
bar

  private JToolBar toolBar = new JToolBar();               // Window 
toolbar

  //define the status bar as a data member
  StatusBar statusBar = new StatusBar();

  private JButton addToolBarButton(Action action)
    {
    JButton button = toolBar.add(action);                     // Add 
toolbar button
    button.setBorder(BorderFactory.createRaisedBevelBorder()); // Add 
button border
    button.setText(null);                                     // No button 
text
    return button;
  }

  private Color elementColor = DEFAULT_ELEMENT_COLOR;      // Current 
element color
  private int elementType = DEFAULT_ELEMENT_TYPE;          // Current 
element type


        //implementation to handle the About menu item's events
        public void actionPerformed(ActionEvent e)
         {
          if (e.getSource() == aboutItem)
           {
            //create about dialog with the app window as parent
             JOptionPane.showMessageDialog(this, "In God we 
trust", "Enjoying the design process",JOptionPane.INFORMATION_MESSAGE);

           }
         }

         //retrieve the pop up menu
         public JPopupMenu getPopup()
          {
            return popup;
          }

    private JPopupMenu popup = new JPopupMenu("General");    // Window pop-
up

  public Color getElementColor()
  {
    return elementColor;
  }

  public int getElementType()
  {
    return elementType;
  }
  private JMenuItem aboutItem;
}



package sketchercalculator;

import java.awt.*;
import java.awt.geom.*;

  //Sketcher version  #12 includes lines, rectangles, cirlces and curves

   public abstract class Element
    {
      public Element(Color color)
       {
         this.color = color;
       }

       public Color getColor()
        {
          return color;
        }

        public abstract Shape getShape();
        public abstract java.awt.Rectangle getBounds();

        protected Color color;

        public abstract void modify(Point start, Point last);

        //Nested class defining a line
        public static class Line extends Element
         {
           public Line(Point start, Point end, Color color)
            {
              super(color);
              line = new Line2D.Double(start, end);
            }

           public Shape getShape()
            {
             return line;
            }

            public java.awt.Rectangle getBounds()
             {
               return line.getBounds();
             }

             public void modify(Point start, Point last)
              {
                line.x2 = last.x;
                line.y2 = last.y;
              }
              private Line2D.Double line;
           }

              //nested class defining a rectangle
              public static class Rectangle extends Element
               {
                public Rectangle(Point start, Point end, Color color)
                 {
                  super(color);
                  rectangle = new Rectangle2D.Double(
                  Math.min(start.x, end.x), Math.min(start.y, end.y),
                  Math.abs(start.x - end.x), Math.abs(start.y - 
end.y));  //width & height
                 }
                   public Shape getShape()
                    {
                     return rectangle;
                    }

                    public java.awt.Rectangle getBounds()
                     {
                      return rectangle.getBounds();
                     }

                     public void modify(Point start, Point last)
                      {
                       rectangle.x = Math.min(start.x, last.x);
                       rectangle.y = Math.min(start.y, last.y);
                       rectangle.width = Math.abs(start.x - last.x);
                       rectangle.height = Math.abs(start.y - last.y);
                      }

              private Rectangle2D.Double rectangle;
            }
              //Nested class defiing a circle
              public static class Circle extends Element
               {
                 public Circle(Point center, Point circumference, Color 
color)
                  {
                    super(color);
                    double radius = center.distance(circumference);
                    circle = new Ellipse2D.Double(center.x - radius, 
center.y - radius, 2.*radius, 2.*radius);
                  }

                  public Shape getShape()
                   {
                     return circle;
                   }

                   public java.awt.Rectangle getBounds()
                    {
                      return circle.getBounds();
                    }

                    public void modify(Point center, Point circumference)
                     {
                       double radius = center.distance(circumference);
                       circle.x = center.x -  (int)radius;
                       circle.y = center.y - (int)radius;
                       circle.width = circle.height = 2*radius;
                     }
                     private Ellipse2D.Double circle;

                }//closing brace for the circle inner class

                //Nested class defining a curve
                public static class Curve extends Element
                 {
                   public Curve(Point start, Point next, Color color)
                    {
                      super(color);
                      curve =  new GeneralPath();
                      curve.moveTo(start.x, start.y);

                      curve.lineTo(next.x, next.y);

                    }
                    //add another segment
                    public void modify(Point start, Point next)
                     {
                       curve.lineTo(next.x, next.y);
                     }

                    public Shape getShape()
                     {
                       return curve;
                     }

                     public java.awt.Rectangle getBounds()
                      {
                        return curve.getBounds();
                      }

                      private GeneralPath curve;
               }//closing brace of the curve class
          } //closing brace for the Element outer class



package sketchercalculator;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

class StatusBar extends JPanel implements Constants
{
  public StatusBar()
   {
     setLayout(new FlowLayout(FlowLayout.LEFT, 10, 3));
     setBackground(Color.lightGray);
     setBorder(BorderFactory.createLineBorder(Color.lightGray));
     setColorPane(DEFAULT_ELEMENT_COLOR);
     setTypePane(DEFAULT_ELEMENT_TYPE);

     //add color pane to status bar
     add(colorPane);

     //add type pane to status bar
     add(typePane);
   }
     //add color panel label
     public void setColorPane(Color color)
      {
        // part 2 ...Code to set color pane text
        String text;
        if(color.equals(Color.red))
          text = "RED";

          else if (color.equals(Color.yellow))
           text = "YELLOW";

          else if (color.equals(Color.green))
           text =  "GREEN";

          else if ( color.equals(Color.blue))
           text = "BLUE";

           else
            text = "CUSTOM COLOR";

           colorPane.setForeground(color);

           //set the pane text
           colorPane.setText(text);
       }

       //part 2 set type pane label
       public void setTypePane(int elementType)
        {
          //declare variable for the type pane
          String text = "LINE";

          switch(elementType)
           {
             case LINE:
              text = "LINE";
              break;
             case RECTANGLE:
              text = "RECTANGLE";
              break;
             case CIRCLE:
              text = "CIRCLE";
              break;
            case CURVE:
             text = "CURVE";
             break;
           }
        //set the pane text
        typePane.setText(text);
      }
       //panes in the  status bar
       private StatusPane colorPane = new StatusPane("BLUE");
       private StatusPane typePane = new StatusPane("LINE");

       //Class defining a status bar pane
           class StatusPane extends JLabel
           {
             public StatusPane (String text)
              {
                setBackground(Color.lightGray);
                setForeground(Color.black);

                //set the fixed font
                setFont(paneFont);

                //center the pane text
                setHorizontalAlignment(CENTER);

                setBorder(BorderFactory.createBevelBorder
(BevelBorder.LOWERED));

                setPreferredSize(new Dimension(100,20));

                //set the text in the pane
                setText(text);
              }
              //font for pane text
              private Font paneFont = new Font("Serif", Font.BOLD, 10);
             }
   }

package sketchercalculator;

//Sketcher Program #12
//has  switch statement  enabling lines,rectangles, circles and curves

import java.awt.*;          //for graphics
import javax.swing.*;
import java.util.*;        //for Observer
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.event.*;   // for mouse input adapter

   class SketchView extends JComponent implements Observer,Constants
    {
       private SketcherCalculator theApp;

      public SketchView(SketcherCalculator theApp)
       {

       this.theApp = theApp;

       //create the mouse listener
       MouseHandler handler = new MouseHandler();

       //Listen for button events
       addMouseListener(handler);

       //Listen for motion events
       addMouseMotionListener(handler);
    }

     //Method called by observable object when it changes
        public void update (Observable o, Object rectangle)
     {
       if(rectangle == null)
        repaint();
        else
          repaint((Rectangle)rectangle);
     }

      public void paint(Graphics g)
       {
         //get a 2D device context
         Graphics2D g2D = (Graphics2D)g;
         Iterator elements = theApp.getModel().getIterator();
         Element element;

         //go through the list
         while(elements.hasNext())
          {
            //get the next element
            element = (Element)elements.next();

            //set the element color
            g2D.setPaint(element.getColor());

            //draw its shape
            g2D.draw(element.getShape());
          }
      }

         class MouseHandler extends MouseInputAdapter
          {
            public void mousePressed(MouseEvent e)
             {
               //save the cursor position
               start = e.getPoint();

                //get modifires
                int modifier = e.getModifiers();

                if((modifier & e.BUTTON1_MASK) != 0)
                 {
                   //get graphics context
                   g2D = (Graphics2D)getGraphics();

                   // set XOR mode
                   g2D.setXORMode(getBackground());

                   //set color
                   g2D.setPaint(theApp.getWindow().getElementColor());

                 }
              }


            public void mouseDragged(MouseEvent e)
             {
               last =   e.getPoint();
               int modifier = e.getModifiers();

               if((modifier & e.BUTTON1_MASK) != 0)
                {
                  //is there an element :
                  if(tempElement == null)
                     //no , so create one
                    tempElement =   createElement(start,last);
                  else
                   {
                     // yes - draw to erase it
                     g2D.draw(tempElement.getShape());

                     //now modify it
                     tempElement.modify(start,last);
                   }
                     //draw it
                     g2D.draw(tempElement.getShape());

                }
              }

                public void mouseReleased(MouseEvent e)
                 {
                  int modifier = e.getModifiers();

                  if(e.isPopupTrigger())
                   {
                     start = e.getPoint();
                     theApp.getWindow().getPopup().show((Component)
e.getSource(), start.x,start.y);
                     start = null;
                   }
                    else if(((modifier & e.BUTTON1_MASK) != 0) && 
((theApp.getWindow().getElementType() != TEXT)))
                     {
                      if(tempElement != null)
                       {
                         // add element to the model
                         theApp.getModel().add(tempElement);

                         tempElement = null;

                    }

                       if(g2D != null)
                        {
                          g2D.dispose();
                          g2D = null;
                        }
                       //remove the points
                       start = last = null;
                   }
                }


             private Element createElement(Point  start, Point end)
              {
                switch(theApp.getWindow().getElementType())
                 {
                   case LINE:
                     return new Element.Line(start, end, theApp.getWindow
().getElementColor());

                     //version 2 Of Element class and SkecthView 
createElement() method changes...
                     // Take away the comment symbol for case RECTANGLE  
to activate the rectangle coding
                   case RECTANGLE:
                     return new Element.Rectangle(start, end, 
theApp.getWindow().getElementColor());

                     //version 3 Of Element class and SketchView 
createElement() method changes...
                   // take away the comment sysmol for case CIRCLE
                   case CIRCLE:
                     return new Element.Circle(start, end, theApp.getWindow
().getElementColor());

                      //version 4 Of Element class and SketchView 
createElement() method changes...
                   //take away the comment symbol for case CURVE
                   case CURVE:
                     return new Element.Curve(start, end, theApp.getWindow
().getElementColor());
               }
                 return null;
            } //end of class MouseHandler

    //temporary graphics context
    private Graphics2D g2D;

    // Stores cursor     position on press
    private Point start;

    //stores cursor position on drag
    private Point last;

    //stores a temporary element
    private Element tempElement;
 }
}


package sketchercalculator;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public interface Constants
{
  //Element type definitions
  int LINE = 101;
  int RECTANGLE = 102;
  int CIRCLE = 103;
  int CURVE = 104;
  int TEXT = 105;
  //Initial conditions
  int DEFAULT_ELEMENT_TYPE = LINE;
  Color DEFAULT_ELEMENT_COLOR = Color.blue;
}


package sketchercalculator;

//Sketcher Program #12
//has  switch statement  enabling lines,rectangles, circles and curves

import java.awt.*;          //for graphics
import javax.swing.*;
import java.util.*;        //for Observer
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.event.*;   // for mouse input adapter

   class SketchView extends JComponent implements Observer,Constants
    {
       private SketcherCalculator theApp;

      public SketchView(SketcherCalculator theApp)
       {

       this.theApp = theApp;

       //create the mouse listener
       MouseHandler handler = new MouseHandler();

       //Listen for button events
       addMouseListener(handler);

       //Listen for motion events
       addMouseMotionListener(handler);
    }

     //Method called by observable object when it changes
        public void update (Observable o, Object rectangle)
     {
       if(rectangle == null)
        repaint();
        else
          repaint((Rectangle)rectangle);
     }

      public void paint(Graphics g)
       {
         //get a 2D device context
         Graphics2D g2D = (Graphics2D)g;
         Iterator elements = theApp.getModel().getIterator();
         Element element;

         //go through the list
         while(elements.hasNext())
          {
            //get the next element
            element = (Element)elements.next();

            //set the element color
            g2D.setPaint(element.getColor());

            //draw its shape
            g2D.draw(element.getShape());
          }
      }

         class MouseHandler extends MouseInputAdapter
          {
            public void mousePressed(MouseEvent e)
             {
               //save the cursor position
               start = e.getPoint();

                //get modifires
                int modifier = e.getModifiers();

                if((modifier & e.BUTTON1_MASK) != 0)
                 {
                   //get graphics context
                   g2D = (Graphics2D)getGraphics();

                   // set XOR mode
                   g2D.setXORMode(getBackground());

                   //set color
                   g2D.setPaint(theApp.getWindow().getElementColor());

                 }
              }


            public void mouseDragged(MouseEvent e)
             {
               last =   e.getPoint();
               int modifier = e.getModifiers();

               if((modifier & e.BUTTON1_MASK) != 0)
                {
                  //is there an element :
                  if(tempElement == null)
                     //no , so create one
                    tempElement =   createElement(start,last);
                  else
                   {
                     // yes - draw to erase it
                     g2D.draw(tempElement.getShape());

                     //now modify it
                     tempElement.modify(start,last);
                   }
                     //draw it
                     g2D.draw(tempElement.getShape());

                }
              }

                public void mouseReleased(MouseEvent e)
                 {
                  int modifier = e.getModifiers();

                  if(e.isPopupTrigger())
                   {
                     start = e.getPoint();
                     theApp.getWindow().getPopup().show((Component)
e.getSource(), start.x,start.y);
                     start = null;
                   }
                    else if(((modifier & e.BUTTON1_MASK) != 0) && 
((theApp.getWindow().getElementType() != TEXT)))
                     {
                      if(tempElement != null)
                       {
                         // add element to the model
                         theApp.getModel().add(tempElement);

                         tempElement = null;

                    }

                       if(g2D != null)
                        {
                          g2D.dispose();
                          g2D = null;
                        }
                       //remove the points
                       start = last = null;
                   }
                }


             private Element createElement(Point  start, Point end)
              {
                switch(theApp.getWindow().getElementType())
                 {
                   case LINE:
                     return new Element.Line(start, end, theApp.getWindow
().getElementColor());

                     //version 2 Of Element class and SkecthView 
createElement() method changes...
                     // Take away the comment symbol for case RECTANGLE  
to activate the rectangle coding
                   case RECTANGLE:
                     return new Element.Rectangle(start, end, 
theApp.getWindow().getElementColor());

                     //version 3 Of Element class and SketchView 
createElement() method changes...
                   // take away the comment sysmol for case CIRCLE
                   case CIRCLE:
                     return new Element.Circle(start, end, theApp.getWindow
().getElementColor());

                      //version 4 Of Element class and SketchView 
createElement() method changes...
                   //take away the comment symbol for case CURVE
                   case CURVE:
                     return new Element.Curve(start, end, theApp.getWindow
().getElementColor());
               }
                 return null;
            } //end of class MouseHandler

    //temporary graphics context
    private Graphics2D g2D;

    // Stores cursor     position on press
    private Point start;

    //stores cursor position on drag
    private Point last;

    //stores a temporary element
    private Element tempElement;
 }
}


package sketchercalculator;

import java.util.*;

// this class begins in version #12

class SketchModel extends Observable
{
 public  boolean   remove(Element element)
   {
     boolean removed = elementList.remove(element);
     if(removed)
      {
        setChanged();
        notifyObservers(element.getBounds());
      }

      return removed;
   }

   public void add(Element element)
    {
      elementList.add(element);
      setChanged();
      notifyObservers(element.getBounds());
    }

    public Iterator getIterator()
     {
       return elementList.listIterator();
     }

     protected LinkedList elementList = new LinkedList();
}


package sketchercalculator;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Calculator6 extends JFrame
 {
   private Container contentPane;

   private JPanel leftPanel;
   private JPanel centerPanel;
   private JPanel buttonPanel;
   private JTextField input1TextField;
   private JTextField input2TextField;
   private JLabel answerLabel;
   private JButton plusButton;
   private JButton minusButton;
   private JButton multiplyButton;
   private JButton divideButton;

   //constructor

   public Calculator6()
    {
     //invoke the generic JFrame calculator
      super(" Calculator");

     //the content pane container is now declared to be
     // an attribute. "this"is unnecessary

     contentPane = this.getContentPane();
     this.setSize(250,100);

     //center the frame of the screen
     Dimension frameSize = this.getSize();
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    this.setLocation( ( screenSize.width - frameSize.width) / 2,
                    (screenSize.height = frameSize.height) / 2);

    leftPanel = new JPanel();
    leftPanel.setLayout(new GridLayout(3,1));
    leftPanel.add(new JLabel("Input 1:   "));
    leftPanel.add(new JLabel("input 2:   "));
    leftPanel.add(new JLabel("Answer:   "));
    contentPane.add(leftPanel,BorderLayout.WEST);

    centerPanel = new JPanel();
    centerPanel.setLayout(new GridLayout(3,1));
    input1TextField = new JTextField(10);
    input2TextField = new JTextField(10);
    answerLabel = new JLabel();
    centerPanel.add(input1TextField);
    centerPanel.add(input2TextField);
    centerPanel.add(answerLabel);
    contentPane.add(centerPanel,BorderLayout.CENTER);

    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(5,1) );
    plusButton = new JButton("+");
    minusButton = new JButton("-");
    multiplyButton = new JButton("*");
    divideButton = new JButton("/");

    buttonPanel.add(plusButton);
    buttonPanel.add(minusButton);
    buttonPanel.add(multiplyButton);
    buttonPanel.add(divideButton);

    contentPane.add(buttonPanel, BorderLayout.EAST);

    //add behaviors
    ActionListener l = new ActionListener()
     {
      public void actionPerformed(ActionEvent e)
       {
         double d1 = new Double(input1TextField.getText() ).doubleValue();
         double d2 = new Double(input2TextField.getText() ).doubleValue();

          if (e.getSource() == plusButton)
             answerLabel.setText(" " + (d1 + d2) );

          else
           if(e.getSource() == minusButton)
            answerLabel.setText(" " + (d1 - d2) );

          else
          if(e.getSource() == multiplyButton)
           answerLabel.setText(" " + (d1 * d2) );

          else
          if(e.getSource() == divideButton)
            answerLabel.setText(" " + (d1 / d2) );

           else
             answerLabel.setText("Input invalid");

      }
   };

   plusButton.addActionListener(l);
   minusButton.addActionListener(l);
   multiplyButton.addActionListener(l);
   divideButton.addActionListener(l);


   //set a WindowListiner to terminate the application when the
   //user closes the window.
   //the listener is an instance of an anonymous inner class

   WindowListener w = new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
       {
         Calculator6.this.dispose();
         System.exit(0);
       }
     };

     //register it with the frame since it is the JFrame
     //object that generates the window closing event

     this.addWindowListener(w);

     this.setVisible(true);

    }

 }

Message #2 by dominskis@a... on Thu, 25 Apr 2002 16:56:44
Dear Guy Worthington,
  You are Worth alot ! I can't thank you enough . I now have the Sketcher 
working with lines, and rectangles and circles and  curves. I hope to 
eventually be able to translate and rotate the figures.

If I can can be of service to you please tell me.
Your Friend
Stan Dominski




> Stan wrote:
>>  I have a message (but no compilation errors) that says:

> > java.lang.NullPointerException
>>  at javax.swing.JPopupMenu.createActionComponent(JPopupMenu.java:285)
>>  at javax.swing.JPopupMenu.add(JPopupMenu.java:265)
>>  at sketchercalculator.SketchFrame.<init>(SketchFrame.java:120)
>>  at sketchercalculator.SketcherCalculator.init
(SketcherCalculator.java:30)
>>  at sketchercalculator.SketcherCalculator.mai
(SketcherCalculator.java:104)

> Easy one! The Java machine gives you all the hints.

> Look in the file SketchFrame.java and at about line 120, you have the
l> ine of code:

>     popup.add(textAction);

> The textAction instance variable has the value null; you can get
r> id of the error by either commenting out that line or assigning
a> n Action instance to the instance variable textAction.  

> Reading your code I came across another couple of small errors:

> First off: a small matter of coding style:

> In the file SketcherCalculator.java, you have declared the myJFrame
i> nstance variable with the code:

>     private static SketchFrame myJFrame;

> this tells the JVM that it is to set aside enough memory for a 
S> ketchFrame value and this block of memory is to be referenced
b> y the class variable myJFrame.

> Further down in the SketcherCalculator.java file you create a
S> ketchFrame instance with the code:

>      myJFrame =  new SketchFrame("Enjoying the design process", this);

> and then reassign the class variable myJFrame to this new instance.
T> he original block of memory cannot be disposed of, so you've just
w> asted some memory.

> I'd suggest you turn the myJFrame class variable into an instance
v> ariable, by getting rid of the keyword static.  That is use the 
d> eclaration:
 >  
 >    private SketchFrame myJFrame;
 >   
S> econd:

> In the SketchView.java file you'll find the line of code:

>     }//end of class MouseHandler

> Insert another brace above it.  That is

>         }//end of method createElement()
 >    }//end of class MouseHandler

> and to balance the braces you'll also need to remove one of the
b> races from the end of your SketchView.java file.  That is, look
f> or the lines of code

>         //stores a temporary element
 >        private element tempElement;

>      } <--- remove this brace
 > }

>         
Message #3 by "Guy Worthington" <guyw@m...> on Thu, 25 Apr 2002 07:11:32
Stan wrote:
> I have a message (but no compilation errors) that says:

> java.lang.NullPointerException
> at javax.swing.JPopupMenu.createActionComponent(JPopupMenu.java:285)
> at javax.swing.JPopupMenu.add(JPopupMenu.java:265)
> at sketchercalculator.SketchFrame.<init>(SketchFrame.java:120)
> at sketchercalculator.SketcherCalculator.init(SketcherCalculator.java:30)
> at sketchercalculator.SketcherCalculator.mai(SketcherCalculator.java:104)

Easy one! The Java machine gives you all the hints.

Look in the file SketchFrame.java and at about line 120, you have the
line of code:

    popup.add(textAction);

The textAction instance variable has the value null; you can get
rid of the error by either commenting out that line or assigning
an Action instance to the instance variable textAction.  

Reading your code I came across another couple of small errors:

First off: a small matter of coding style:

In the file SketcherCalculator.java, you have declared the myJFrame
instance variable with the code:

    private static SketchFrame myJFrame;

this tells the JVM that it is to set aside enough memory for a 
SketchFrame value and this block of memory is to be referenced
by the class variable myJFrame.

Further down in the SketcherCalculator.java file you create a
SketchFrame instance with the code:

     myJFrame =  new SketchFrame("Enjoying the design process", this);

and then reassign the class variable myJFrame to this new instance.
The original block of memory cannot be disposed of, so you've just
wasted some memory.

I'd suggest you turn the myJFrame class variable into an instance
variable, by getting rid of the keyword static.  That is use the 
declaration:
  
    private SketchFrame myJFrame;
   
Second:

In the SketchView.java file you'll find the line of code:

    }//end of class MouseHandler

Insert another brace above it.  That is

        }//end of method createElement()
    }//end of class MouseHandler

and to balance the braces you'll also need to remove one of the
braces from the end of your SketchView.java file.  That is, look
for the lines of code

        //stores a temporary element
        private element tempElement;

     } <--- remove this brace
 }

        
Message #4 by "Rich" <rpcee@o...> on Fri, 26 Apr 2002 11:50:35
> In the file SketcherCalculator.java, you have declared the myJFrame
i> nstance variable with the code:

>     private static SketchFrame myJFrame;

> this tells the JVM that it is to set aside enough memory for a 
S> ketchFrame value and this block of memory is to be referenced
b> y the class variable myJFrame.

I may be misinterpreting you but I don't think this is true. A static 
variable still has to be assigned if it's not to be null (primitives would 
get the default value ie 0 or false). - I think the private static 
SketchFrame myJFrame just sets aside enough memory for a reference to an 
object. Granted you would not normally want to assign this variable each 
time an instance is created. Typically you would see:

   private static AClass aStaticInst = new AClass(...);

or a static initialiser.

Message #5 by DominskiS@a... on Fri, 26 Apr 2002 07:53:12 EDT
--part1_6a.1f0f5285.29fa99a8_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit


Dear Rich,
  I took out the word static from the JFrame reference variable and commented 
out the popup statement and the Sketcher works ok now.

Thank you very much
Stan


> In the file SketcherCalculator.java, you have declared the myJFrame
i> nstance variable with the code:

>     private static SketchFrame myJFrame;

> this tells the JVM that it is to set aside enough memory for a 
S> ketchFrame value and this block of memory is to be referenced
b> y the class variable myJFrame.

I may be misinterpreting you but I don't think this is true. A static 
variable still has to be assigned if it's not to be null (primitives would 
get the default value ie 0 or false). - I think the private static 
SketchFrame myJFrame just sets aside enough memory for a reference to an 
object. Granted you would not normally want to assign this variable each 
time an instance is created. Typically you would see:

   private static AClass aStaticInst = new AClass(...);

or a static initialiser.





  Return to Index