JMENU COLOR

I've got a JMenu in my application and it's white when I execute my application in my computer but if I change the computer it becomes gray .. How can I avoid this=?
Thanks!

Consider also setting the background color for the menuitems also. Probably they get painted with a gray background unless they have a specific background color. This can do it once
public void updateComponent(Component c) {
  if(c instanceof JMenuItem) {
     JMenuItem m = (JMenuItem) c;
        m.setBackground(Color.white);
  } else if(c instanceof Container) {
       Container cn = (Container) c;
       for(int i = 0; i < cn.getComponents().length; i++) {
           updateComponent( cn.getComponent(i) );
} You call this in the constructor of your class and make sure the menu items are always painted with a specific color. ie updateComponent(this); // in the constructor of your class (perhaps Menubar)  More code can be added for item specific rendering so you do not have set the attributes for every single instance of that component ie buttons, labels, etc
ICE

Similar Messages

  • Storing Shape Information IN a Table-Like Structure

    Hi All,
    I have a Program which displays shape (rectangle,oval,etc) in the panel which is enclosed in a frame.. shape can be dragged and dropped anywhere on panel... also one can delete shape... Now I Want To Store All The Exiting Shapes (as they are added on panel ) in some structure say a table, and alongwith it, i also want to store additional information about shape, say its location currently on panel, its present color, etc so that i can use this information later in the program... how do i do implement this ?? Plz Help Me.. It would be great if you include the changes in the source code itself...
    thanks
    Here is the source code :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class ShapeDrawFrame extends javax.swing.JFrame {
        JCheckBoxMenuItem addLargeShapes;    
       JCheckBoxMenuItem addBorderedShapes; 
       JRadioButtonMenuItem red, green, blue,      
                            cyan, magenta, yellow, 
                            black, gray, white;  
       JPopupMenu popup;
        public ShapeDrawFrame() {
            super("Shape Draw");
            //initComponents();        
          ShapeCanvas canvas = new ShapeCanvas();
          setContentPane(canvas);
          /* Create the menu bar and the menus */
          JMenuBar menubar = new JMenuBar();
          setJMenuBar(menubar);
          JMenu addShapeMenu = new JMenu("Add");
          addShapeMenu.setMnemonic('A');
          menubar.add(addShapeMenu);
          JMenu shapeColorMenu = new JMenu("Color");
          shapeColorMenu.setMnemonic('C');
          menubar.add(shapeColorMenu);
          JMenu optionsMenu = new JMenu("Options");
          optionsMenu.setMnemonic('O');
          menubar.add(optionsMenu);
          /* Create menu items for adding shapes to the canvas,
             and add them to the "Add" menu.  The canvas serves
             as ActionListener for these menu items. */     
          JMenuItem rect = new JMenuItem("Rectangle");
          rect.setAccelerator( KeyStroke.getKeyStroke("ctrl R") );
          addShapeMenu.add(rect);
          rect.addActionListener(canvas);
          JMenuItem oval = new JMenuItem("Oval");
          oval.setAccelerator( KeyStroke.getKeyStroke("ctrl O") );
          addShapeMenu.add(oval);
          oval.addActionListener(canvas);
          JMenuItem roundrect = new JMenuItem("Round Rect");
          roundrect.setAccelerator( KeyStroke.getKeyStroke("ctrl D") );
          addShapeMenu.add(roundrect);
          roundrect.addActionListener(canvas);
          /* Create the JRadioButtonMenuItems that control the color
             of a newly added shape, and add them to the "Color"
             menu.  There is no ActionListener for these menu items.
             The canvas checks for the currently selected color when
             it adds a shape to the canvas.  A ButtonGroup is used
             to make sure that only one color is selected. */
          ButtonGroup colorGroup = new ButtonGroup();
          red = new JRadioButtonMenuItem("Red");
          shapeColorMenu.add(red);
          colorGroup.add(red);
          red.setSelected(true);
          green = new JRadioButtonMenuItem("Green");
          shapeColorMenu.add(green);
          colorGroup.add(green);
          blue = new JRadioButtonMenuItem("Blue");
          shapeColorMenu.add(blue);
          colorGroup.add(blue);
          cyan = new JRadioButtonMenuItem("Cyan");
          shapeColorMenu.add(cyan);
          colorGroup.add(cyan);
          magenta = new JRadioButtonMenuItem("Magenta");
          shapeColorMenu.add(magenta);
          colorGroup.add(magenta);
          yellow = new JRadioButtonMenuItem("Yellow");
          shapeColorMenu.add(yellow);
          colorGroup.add(yellow);
          black = new JRadioButtonMenuItem("Black");
          shapeColorMenu.add(black);
          colorGroup.add(black);
          gray = new JRadioButtonMenuItem("Gray");
          shapeColorMenu.add(gray);
          colorGroup.add(gray);
          white = new JRadioButtonMenuItem("White");
          shapeColorMenu.add(white);
          colorGroup.add(white);
          /* Create the "Clear" menu item, and add it to the
             "Options" menu.  The canvas will listen for events
             from this menu item. */
          JMenuItem clear = new JMenuItem("Clear");
          clear.setAccelerator( KeyStroke.getKeyStroke("ctrl C") );
          clear.addActionListener(canvas);
          optionsMenu.add(clear);
          optionsMenu.addSeparator();  // Add a separating line to the menu.
          /* Create the JCheckBoxMenuItems and add them to the Options
             menu.  There is no ActionListener for these items because
             the canvas class will check their state when it adds a
             new shape. */
          addLargeShapes = new JCheckBoxMenuItem("Add Large Shapes");
          addLargeShapes.setSelected(true);
          optionsMenu.add(addLargeShapes);
          addBorderedShapes = new JCheckBoxMenuItem("Add Shapes with Border");
          addBorderedShapes.setSelected(true);
          optionsMenu.add(addBorderedShapes);
          optionsMenu.addSeparator();
          /* Create a menu for background colors, and add it to the
             "Options" menu.  It will show up as a hierarchical sub-menu. */
          JMenu background = new JMenu("Background Color");
          optionsMenu.add(background);
          background.add("Red").addActionListener(canvas);
          background.add("Green").addActionListener(canvas);
          background.add("Blue").addActionListener(canvas);
          background.add("Cyan").addActionListener(canvas);
          background.add("Magenta").addActionListener(canvas);
          background.add("Yellow").addActionListener(canvas);
          background.add("Black").addActionListener(canvas);
          background.add("Gray").addActionListener(canvas);
          background.add("White").addActionListener(canvas);
          /* Create the pop-up menu and add commands for editing a
             shape.  This menu is not used until the user performs
             the pop-up trigger mouse gesture on a shape. */
          popup = new JPopupMenu();
          popup.add("Delete Shape").addActionListener(canvas);
          popup.add("Bring to Front").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Make Large").addActionListener(canvas);
          popup.add("Make Small").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Add Black Border").addActionListener(canvas);
          popup.add("Remove Black Border").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Set Color to Red").addActionListener(canvas);
          popup.add("Set Color to Green").addActionListener(canvas);
          popup.add("Set Color to Blue").addActionListener(canvas);
          popup.add("Set Color to Cyan").addActionListener(canvas);
          popup.add("Set Color to Magenta").addActionListener(canvas);
          popup.add("Set Color to Yellow").addActionListener(canvas);
          popup.add("Set Color to Black").addActionListener(canvas);
          popup.add("Set Color to Gray").addActionListener(canvas);
          popup.add("Set Color to White").addActionListener(canvas);
          /* Set the "DefaultCloseOperation" for the frame.  This determines
             what happens when the user clicks the close box of the frame.
             It is set here so that System.exit() will be called to end
             the program when the user closes the window. */
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          /* Set the size and location of the frame, and make it visible. */
          setLocation(20,50);
          setSize(550,420);
          show();       
       class ShapeCanvas extends JPanel
                         implements ActionListener, MouseListener, MouseMotionListener {
             // This class represents a "canvas" that can display colored shapes and
             // let the user drag them around.  It uses an off-screen images to
             // make the dragging look as smooth as possible.
          ArrayList shapes = new ArrayList();
               // holds a list of the shapes that are displayed on the canvas
          ShapeCanvas() {
               // Constructor: set background color to white
               // set up listeners to respond to mouse actions
             setBackground(Color.white);
             addMouseListener(this);
             addMouseMotionListener(this);
          public void paintComponent(Graphics g) {
               // In the paint method, all the shapes in ArrayList are
               // copied onto the canvas.
             super.paintComponent(g);  // First, fill with background color.
             int top = shapes.size();
             for (int i = 0; i < top; i++) {
                Shape s = (Shape)shapes.get(i);
                s.draw(g);
          public void actionPerformed(ActionEvent evt) {
                 // Called to respond to action events from the
                 // menus or pop-up menu.
             String command = evt.getActionCommand();
             if (command.equals("Clear")) {
                shapes.clear(); // Remove all items from the ArrayList
                repaint();
             else if (command.equals("Rectangle"))
                addShape(new RectShape());
             else if (command.equals("Oval"))
                addShape(new OvalShape());
             else if (command.equals("Round Rect"))
                addShape(new RoundRectShape());
             else if (command.equals("Red"))
                setBackground(Color.red);
             else if (command.equals("Green"))
                setBackground(Color.green);
             else if (command.equals("Blue"))
                setBackground(Color.blue);
             else if (command.equals("Cyan"))
                setBackground(Color.cyan);
             else if (command.equals("Magenta"))
                setBackground(Color.magenta);
             else if (command.equals("Yellow"))
                setBackground(Color.yellow);
             else if (command.equals("Black"))
                setBackground(Color.black);
             else if (command.equals("Gray"))
                setBackground(Color.gray);
             else if (command.equals("White"))
                setBackground(Color.white);
             else if (clickedShape != null) {
                    // Process a command from the pop-up menu.
                if (command.equals("Delete Shape"))
                   shapes.remove(clickedShape);
                else if (command.equals("Bring to Front")) {
                   shapes.remove(clickedShape);
                   shapes.add(clickedShape); 
                else if (command.equals("Make Large"))
                   clickedShape.setSize(100,60);
                else if (command.equals("Make Small"))
                   clickedShape.setSize(50,30);
                else if (command.equals("Add Black Border"))
                   clickedShape.setDrawOutline(true);
                else if (command.equals("Remove Black Border"))
                   clickedShape.setDrawOutline(false);
                else if (command.equals("Set Color to Red"))
                   clickedShape.setColor(Color.red);
                else if (command.equals("Set Color to Green"))
                   clickedShape.setColor(Color.green);
                else if (command.equals("Set Color to Blue"))
                   clickedShape.setColor(Color.blue);
                else if (command.equals("Set Color to Cyan"))
                   clickedShape.setColor(Color.cyan);
                else if (command.equals("Set Color to Magenta"))
                   clickedShape.setColor(Color.magenta);
                else if (command.equals("Set Color to Yellow"))
                   clickedShape.setColor(Color.yellow);
                else if (command.equals("Set Color to Black"))
                   clickedShape.setColor(Color.black);
                else if (command.equals("Set Color to Gray"))
                   clickedShape.setColor(Color.gray);
                else if (command.equals("Set Color to White"))
                   clickedShape.setColor(Color.white);
                repaint();
          } // end actionPerformed()
          void addShape(Shape shape) {
                 // Add the shape to the canvas, and set its size, color
                 // and whether or not it should have a black border.  These
                 // properties are determined by looking at the states of
                 // various menu items.  The shape is added at the top-left
                 // corner of the canvas.
             if (red.isSelected())
                shape.setColor(Color.red);
             else if (blue.isSelected())
                shape.setColor(Color.blue);
             else if (green.isSelected())
                shape.setColor(Color.green);
             else if (cyan.isSelected())
                shape.setColor(Color.cyan);
             else if (magenta.isSelected())
                shape.setColor(Color.magenta);
             else if (yellow.isSelected())
                shape.setColor(Color.yellow);
             else if (black.isSelected())
                shape.setColor(Color.black);
             else if (white.isSelected())
                shape.setColor(Color.white);
             else
                shape.setColor(Color.gray);
             shape.setDrawOutline( addBorderedShapes.isSelected() );
             if (addLargeShapes.isSelected())
                shape.reshape(3,3,100,60);
             else
                shape.reshape(3,3,50,30);
             shapes.add(shape);
             repaint();
          } // end addShape()
          // -------------------- This rest of this class implements dragging ----------------------
          Shape clickedShape = null;  // This is the shape that the user clicks on.
                                      // It becomes the draggedShape is the user is
                                      // dragging, unless the user is invoking a
                                      // pop-up menu.  This variable is used in
                                      // actionPerformed() when a command from the
                                      // pop-up menu is processed.
          Shape draggedShape = null;  // This is null unless a shape is being dragged.
                                      // A non-null value is used as a signal that dragging
                                      // is in progress, as well as indicating which shape
                                      // is being dragged.
          int prevDragX;  // During dragging, these record the x and y coordinates of the
          int prevDragY;  //    previous position of the mouse.
          public void mousePressed(MouseEvent evt) {
                // User has pressed the mouse.  Find the shape that the user has clicked on, if
                // any.  If there is no shape at the position when the mouse was clicked, then
                // ignore this event.  If there is then one of three things will happen:
                // If the event is a pop-up trigger, then the pop-up menu is displayed, and
                // the user can select from the pop-up menu to edit the shape.  If the user was
                // holding down the shift key, then bring the clicked shape to the front, in
                // front of all the other shapes.  Otherwise, start dragging the shape.
             if (draggedShape != null) {
                  // A drag operation is already in progress, so ignore this click.
                  // This might happen if the user clicks a second mouse button before
                  // releasing the first one(?).
                return;
             int x = evt.getX();  // x-coordinate of point where mouse was clicked
             int y = evt.getY();  // y-coordinate of point
             clickedShape = null;  // This will be set to the clicked shape, if any.
             for ( int i = shapes.size() - 1; i >= 0; i-- ) { 
                    // Check shapes from front to back.
                Shape s = (Shape)shapes.get(i);
                if (s.containsPoint(x,y)) {
                   clickedShape = s;
                   break;
             if (clickedShape == null) {
                   // The user did not click on a shape.
                return;
             else if (evt.isPopupTrigger()) {
                  // The user wants to see the pop-up menu
                popup.show(this,x-10,y-2);
             else if (evt.isShiftDown()) {
                  // Bring the clicked shape to the front
                shapes.remove(clickedShape);
                shapes.add(clickedShape);
                repaint();
             else {
                  // Start dragging the shape.
                draggedShape = clickedShape;
                prevDragX = x;
                prevDragY = y;
          public void mouseDragged(MouseEvent evt) {
                 // User has moved the mouse.  Move the dragged shape by the same amount.
             if (draggedShape == null) {
                    // User did not click a shape.  There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
          public void mouseReleased(MouseEvent evt) {
                 // User has released the mouse.  Move the dragged shape, and set
                 // draggedShape to null to indicate that dragging is over.
                 // If the shape lies completely outside the canvas, remove it
                 // from the list of shapes (since there is no way to ever move
                 // it back on screen).  However, if the event is a popup trigger
                 // event, then show the popup menu instead.
             if (draggedShape == null) {
                   // User did not click on a shape. There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             if (evt.isPopupTrigger()) {
                   // Check whether the user is trying to pop up a menu.
                   // (This should be checked in both the mousePressed() and
                   // mouseReleased() methods.)
                popup.show(this,x-10,y-2);
             else {
                draggedShape.moveBy(x - prevDragX, y - prevDragY);
                if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height ||
                        draggedShape.left + draggedShape.width < 0 ||
                        draggedShape.top + draggedShape.height < 0 ) {  // shape is off-screen
                   shapes.remove(draggedShape);  // remove shape from list of shapes
                repaint();
             draggedShape = null;  // Dragging is finished.
          public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
          public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
          public void mouseMoved(MouseEvent evt) { }
          public void mouseClicked(MouseEvent evt) { }
       }  // end class ShapeCanvas
       // ------- Nested class definitions for the abstract Shape class and three -----
       // -------------------- concrete subclasses of Shape. --------------------------
       static abstract class Shape {
             // A class representing shapes that can be displayed on a ShapeCanvas.
             // The subclasses of this class represent particular types of shapes.
             // When a shape is first constructed, it has height and width zero
             // and a default color of white.
          int left, top;      // Position of top left corner of rectangle that bounds this shape.
          int width, height;  // Size of the bounding rectangle.
          Color color = Color.white;  // Color of this shape.
          boolean drawOutline;  // If true, a black border is drawn on the shape
          void reshape(int left, int top, int width, int height) {
                // Set the position and size of this shape.
             this.left = left;
             this.top = top;
             this.width = width;
             this.height = height;
          void setSize(int width, int height) {
                // Set the size of this shape
             this.width = width;
             this.height = height;
          void moveBy(int dx, int dy) {
                 // Move the shape by dx pixels horizontally and dy pixels vertically
                 // (by changing the position of the top-left corner of the shape).
             left += dx;
             top += dy;
          void setColor(Color color) {
                 // Set the color of this shape
             this.color = color;
          void setDrawOutline(boolean draw) {
                 // If true, a black outline is drawn around this shape.
             drawOutline = draw;
          boolean containsPoint(int x, int y) {
                // Check whether the shape contains the point (x,y).
                // By default, this just checks whether (x,y) is inside the
                // rectangle that bounds the shape.  This method should be
                // overridden by a subclass if the default behavior is not
                // appropriate for the subclass.
             if (x >= left && x < left+width && y >= top && y < top+height)
                return true;
             else
                return false;
          abstract void draw(Graphics g); 
                // Draw the shape in the graphics context g.
                // This must be overridden in any concrete subclass.
       }  // end of class Shape
       static class RectShape extends Shape {
             // This class represents rectangle shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRect(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRect(left,top,width,height);
       static class OvalShape extends Shape {
              // This class represents oval shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillOval(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawOval(left,top,width,height);
          boolean containsPoint(int x, int y) {
                // Check whether (x,y) is inside this oval, using the
                // mathematical equation of an ellipse.
             double rx = width/2.0;   // horizontal radius of ellipse
             double ry = height/2.0;  // vertical radius of ellipse
             double cx = left + rx;   // x-coord of center of ellipse
             double cy = top + ry;    // y-coord of center of ellipse
             if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
                return true;
             else
               return false;
       static class RoundRectShape extends Shape {
              // This class represents rectangle shapes with rounded corners.
              // (Note that it uses the inherited version of the
              // containsPoint(x,y) method, even though that is not perfectly
              // accurate when (x,y) is near one of the corners.)
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRoundRect(left,top,width,height,width/3,height/3);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRoundRect(left,top,width,height,width/3,height/3);
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShapeDrawFrame().setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }

    Sure. In your original post, you had a sort of a design. The general idea was right. And then you asked us to implement it. Well, that's the wrong approach. You need to make the sort-of-a-design into a real design. Don't implement anything until you know what you are going to implement.

  • Problem with invoking an Action in a Menu...

    I wanted to make a program that would create a box of rectangles and have each rectangle change color when clicked.
    I want the user to be able to decide which color you want the rectangle to be. I put choices in a menu.
    However whenever an option is selected from the menu, I get exceptions:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at ShapeTest$ColorAction$ColorThread.run(ShapeTest.java:142)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    The code is displayed below. Am I missing something with the Swing thread? Please help.
    Josh
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    // This Rectangle knows it's particular color
    class ColorRectangle extends Rectangle2D.Float
       private Color color;
       public ColorRectangle( float x, float y, float w, float h, Color c )
          super( x, y, w, h );
          color = c;
       public ColorRectangle( float x, float y, float w, float h)
          super( x, y, w, h );
          color = Color.white;
       public void setColor( Color c )
          color = c;
       public Color getColor()
          return color;
    } // end ColorRectangle class
       This is the main frame.
    public class ShapeTest extends JFrame
       private ShapeTestPanel panel;
       public ShapeTest()
          setTitle( "ShapeTest" );
          setSize( 500, 500 );
          setDefaultCloseOperation( EXIT_ON_CLOSE );
          JPanel panel = new ShapeTestPanel();
          Container cp = getContentPane();
          cp.add( panel, BorderLayout.CENTER );
          // Set up the menu
          JMenuBar mb = new JMenuBar();
          JMenu mColor = new JMenu( "Color" );
          mColor.setMnemonic( KeyEvent.VK_C );
          // Adding the actions to the menu
          mColor.add( new ColorAction("Blue", Color.blue, KeyEvent.VK_B) );
          mColor.add( new ColorAction("Green", Color.green, KeyEvent.VK_G) );
          mColor.add( new ColorAction("Red", Color.red, KeyEvent.VK_R) );
          mColor.add( new ColorAction("White", Color.white, KeyEvent.VK_W) );
          mb.add( mColor );
          setJMenuBar( mb );
       } // end ShapeTest constructor
       public static void main( String [] args )
          JFrame frame = new ShapeTest();
          frame.setVisible( true );
          This action inner class will be added to the menu to change the main color
          of the panel.
       class ColorAction extends AbstractAction
          private Color color;
          private ColorThread thread; // this is used to change panel color
          public ColorAction( String name, Color c, int keyEvent )
             putValue( NAME, name );
             putValue( MNEMONIC_KEY, new Integer(keyEvent) );
             color = c;
             thread = new ColorThread();
             Here I want to change the main color of the panel, so that
                clicking on a rectangle will now display a different color.
          public void actionPerformed( ActionEvent evt )
                I tried to just call the function panel.setMainColor( color ).
                EXCEPTION!!!
                I tried to make the mainColor variable public and access it.
                EXCEPTION!!!
                I tried to use SwingUtilities.invokeLater( thread ).
                EXCEPTION!!!
                I tried to use SwingUtilities.invokeAndWait( thread );
                EXCEPTION!!!
             try
                SwingUtilities.invokeLater( thread );
             catch ( Exception ex )
                System.out.println( ex );
          } // end actionPerformed( evt )
          // Inner class of an inner class
          class ColorThread extends Thread
             public void run()
                panel.setMainColor( color );
                // panel is a member of the frame.
          } // end ColorThread class
       } // end ColorAction class
    } // end ShapeTest class
    class ShapeTestPanel extends JPanel
       private Rectangle2D bigRect; // the outer rectangle
       private ColorRectangle [][] araRects; // the inner rectangles
       public Color mainColor = Color.blue; // will change inner rectangle
                                            //   color on mouseClicked
       public ShapeTestPanel()
          int x = 10;
          int y = 10;
          // Make the outer rectangle
          bigRect = new Rectangle2D.Double( x, y, 401, 401 );
          // Make the inner rectangles
          araRects = new ColorRectangle [4][4];
          int i, j;
          for ( x = 11, i = 0; i < araRects.length; i++, x += 100 )
             for ( y = 11, j = 0; j < araRects.length; j++, y += 100 )
    araRects[i][j] = new ColorRectangle( x, y, 99, 99 );
    addMouseListener( new ShapeTestMouseListener() );
    } // end ShapeTestPanel constructor
    // This will change the main color for clicking
    public void setMainColor( Color c )
    mainColor = c;
    // Draw the outer rectangle and the inner rectangles in the right color
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    Graphics2D g2 = (Graphics2D)g;
    g2.draw( bigRect );
    for ( int i = araRects.length - 1; i > -1; i-- )
    for ( int j = araRects[i].length - 1; j > -1; j-- )
    g2.setPaint( Color.black );
    g2.draw( araRects[i][j] );
    g2.setPaint( araRects[i][j].getColor() );
    g2.fill( araRects[i][j] );
    } // end paintComponent( Graphics g )
    // I want the color to change when someone clicks on a rectangle
    class ShapeTestMouseListener extends MouseAdapter
    public void mouseClicked( MouseEvent evt )
    Point p = evt.getPoint();
    for ( int i = araRects.length - 1; i > -1; i-- )
    for ( int j = araRects[i].length - 1; j > -1; j-- )
    if ( araRects[i][j].contains(p) )
    araRects[i][j].setColor( mainColor );
    repaint();
    return;
    } // mouseClicked( MouseEvent )
    } // end ShapeTestMouseListener class
    } // end ShapeTestPanel

    replace the following line
    JPanel panel = new ShapeTestPanel();
    with
    this.panel = new ShapeTestPanel(); in the ShpaeTest constructor

  • At a dead end.  A java student in need of help.

    I've hit a wall.
    The program is supposed to allow the user to draw five different polygons using the polygon class and let the user pick the color for each polygon and move each polygon around the screen once it is filled in. The user clicks to add the points and then double clicks to fill in the polygon. Then the polygon is added to the array. Up to the dragging around the screen the program works fine. When I click on a polygon with the shift down nothing happens and I've spent several hours trying to figure out why.
    I've placed several System.out.println's in the code and I think I've narrowed down the problem. (I hope) I think it might have something to do with the canvas repainting. Because the S.O.P's show that the program is going through and executing that code. It might also have something to the do with my polygon array, but to my knowledge that is setup fine.
    Thanks a bunch if you try to help.
    Brad
    // Full Code Below
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         private JButton reset;
         private Podly polyArray[] = new Podly[5];
         private Podly currentPoly = new Podly();
         private Podly movingPoly = new Podly();
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              count = 0;
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              reset = new JButton("Reset");
              reset.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(reset);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         public static void main(String [] args)
              JFrame main = new poly();
              main.setSize(600, 600);
              main.setVisible(true);
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else if (test instanceof JButton) // Repaints if Reset Button is Pressed
                   repaint();
                   currentPoly.reset();
                   count = 0;
                   overflowed = false;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon // Class adds Color Fuctionality to Polygon class
              Color polyColor;
              void setColor(Color y)
              {polyColor = y;}
              Color getColor()
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   System.out.println("Canvas is called");
                   System.out.println(polyArray);
                   for (int i=0; i>count;i++)
                        System.out.println("Loop is going");
                        Podly y = polyArray;
                        g.setColor(y.getColor());
                        g.fillPolygon(y);
                        System.out.println(y);
                        System.out.println("Loop has filled in polygon"); // Test
                   System.out.println("painting complete");
         class Points extends MouseAdapter
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // Allows user to play again.
                             repaint();
                             currentPoly.reset();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  System.out.println("Gets before Check loop");
                                  for (int r=count-1;r>=0;r--)
                                       System.out.println("Inside For Check Loop");
                                       System.out.println(polyArray[r]);
                                       if (!polyArray[r].contains(x,y))          
                                            System.out.println("Point is found");
                                            movingPoly = polyArray[r];
                                            System.out.println("MovingPoly Defined");
                                            moving = true;
                                            System.out.println("Moving is true"); // test
                                            break;
                             else
                                  currentPoly.setColor(currentColor);
                                  currentPoly.addPoint(x,y);
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  currentPoly.reset();
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true;}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        System.out.println("Gets here");
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();

    Here is the updated code still with the color error I talked about above.
    :) Thanks for all the help everyone.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         Podly [] polyArray;
         private Podly currentPoly;
         private Podly movingPoly;
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private Color polyColor;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // Exits program on window close.
              polyArray = new Podly[5];
              count = 0;                                      // Set count to zero.
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         /* Button Listeners */
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon  // Class adds Color Fuctionality to Polygon class
              void setColor(Color y)  // sets the Polygon's color.
              {polyColor = y;}
              Color getColor()   // returns the Polygon's color.
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                        for (int i=0; i<count;i++)
                             g.setColor(polyArray.getColor());
                             g.fillPolygon(polyArray[i]);
         class Points extends MouseAdapter
              /* Listens for mouse press, constructs polygons, stores them in array. */
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // allows user to play again by resetting.
                             repaint();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  for (int r=count-1;r>=0;r--)
                                       if (polyArray[r].contains(x,y))          
                                            movingPoly = polyArray[r];
                                            moving = true;
                                            break; // exits for loop after Polygon with point is found.
                             else
                                  currentPoly = new Podly();
                                  currentPoly.addPoint(x,y); // Adds the first point.
                                  currentPoly.setColor(currentColor); // Sets the Polygon Color
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             /* Close the current Polygon at double click,
                             * then moves on to the next. */
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true; canvas.repaint();}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              /* Listens for mouse release */
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         /* Moves selected Polygon around */
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();
         public static void main(String [] args)
              JFrame poly = new poly();
              poly.setSize(600, 600);
              poly.setVisible(true);

  • Here is my GridBagLayout version of the code

         public void constructGUI()
               c= getContentPane();
              //Construct the menus and their listeners
              JMenu filemenu = new JMenu("File");
              JMenuItem saveas= new JMenuItem ("Save Amortization As");
              saveas.addActionListener(new ActionListener(){
                   public void actionPerformed (ActionEvent e)
                        JFileChooser filechooser = new JFileChooser ();
                        filechooser.setFileSelectionMode ( JFileChooser.FILES_ONLY);
                        int result = filechooser.showSaveDialog (null);
                        if (result== JFileChooser.CANCEL_OPTION)
                             return;
                        File filename = filechooser.getSelectedFile();
                        if (filename==null||filename.getName().equals (" "))
                             JOptionPane.showMessageDialog( null, "Invalid File Name", "Invalid FileName", JOptionPane.ERROR_MESSAGE );
                        else {
                             try
                                  System.out.println("I am ready to create the streams");
                                  FileOutputStream file = new FileOutputStream(filename, true);
                                  OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file));
                                  String info= "The data is based on"+"\n";
                                  filestream.write(info);
                                  System.out.println("I wrote the first string called info");
                                  String interestdata= "INTEREST:"+" "+interest+"\n";
                                  filestream.write(interestdata);
                                  String timedata="The amortization period is:"+" "+time+"\n";
                                  filestream.write(timedata);
                                  String loandata="The money borrowed is:"+" "+moneyFormat.format(loannumber)+"\n";
                                  filestream.write(loandata);
                                  String totals= "Total of Payments Made:"+" " +moneyFormat.format(totalpayments)+"\n"+"Total Interest Paid:"+"  "+moneyFormat.format(totalinterest)+"\n";
                                  filestream.write(totals);
                                  String filestring = "PAYMENT NUMBER"+"   " + "PAYMENT" + "   " + " PRINCIPLE" + "   " + "INTEREST" +"   " + " BALANCE" + "\n";
                                  filestream.write(filestring);
                                  double loannumberkf= loannumber;
                                  System.out.println(timenumber);
                                  for (int j=1; j<=timenumber ; j++ )
                                       double principlekf=payment-loannumberkf*z;
                                       double balancef=loannumberkf-principlekf;
                                       String display ="\n"+ Integer.toString(j)+"                " + moneyFormat.format(payment)+"        "+ moneyFormat.format(principlekf)+ "     "+moneyFormat.format(loannumberkf*z)+ "     "+ moneyFormat.format(balancef)+"\n";
                                       filestream.write(display);
                                       loannumberkf=loannumberkf-principlekf;
                                  filestream.flush();
                                  file.close();
                             catch ( IOException ioException )
                                  JOptionPane.showMessageDialog (null, "File Does not exist", "Invalid File Name", JOptionPane.ERROR_MESSAGE);
                        }//end of else
                 } //end anonymous inner class
              filemenu.add(saveas);
              JMenuItem exit= new JMenuItem ("Exit");
              exit.addActionListener( new ActionListener() {
                        public void actionPerformed (ActionEvent e)
                             System.exit(0);
                   } //end anonymous inner class
              ); // end call to ActionListener
              filemenu.add(exit);
              JMenuItem summaries=new JMenuItem ("Save Summaries As");
              MenuHandler menuhandler= new MenuHandler();
              summaries.addActionListener(menuhandler);
              filemenu.add(summaries);
              //construct the second JMenu
              JMenu colorchooser=new JMenu("Color Chooser");
              JMenuItem colorchooseritem=new JMenuItem("Choose Color");
              colorchooseritem.addActionListener (new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       color=JColorChooser.showDialog(Mortgagecalculation.this, "Choose a Color", color);
                                       c.setBackground(color);
                                       c.repaint();
                         ); //end of registration
              colorchooser.add(colorchooseritem);
              //third menu
              JMenu service = new JMenu("Services");
              JMenuItem s1= new JMenuItem ("Display Amortization");
              JMenuItem s2= new JMenuItem ("Calender");
              service.add(s1);
              service.add(s2);
              //Create menu bar and add the two JMenu objects
              JMenuBar menubar = new JMenuBar();
              setJMenuBar(menubar);
              menubar.add(filemenu); // end of menu construction
              menubar.add(colorchooser);
              menubar.add(service);
              //set the layout manager for the JFrame
              gbLayout = new GridBagLayout();
              c.setLayout(gbLayout);
              gbConstraints = new GridBagConstraints();
              //construct table and place it on the North part of the Frame
              JLabel tablelabel=new JLabel ("The Table below displays amortization values after you press O.K. on the payments window. Payments window appears after you enter the values for rate, period and loan");
              mydefaulttable = new DefaultTableModel();
                   mydefaulttable.addColumn("PAYMENT NUMBER");
                   mydefaulttable.addColumn ("PAYMENT AMOUNT");
                   mydefaulttable.addColumn ("PRINCIPLE");
                   mydefaulttable.addColumn ("INTEREST");
                   mydefaulttable.addColumn("LOAN BALANCE");
              Box tablebox=Box.createVerticalBox();   
              mytable=new JTable(mydefaulttable);
              tablelabel.setLabelFor(mytable);
              JScrollPane myscrollpane= new JScrollPane (mytable);
              tablebox.add(tablelabel);
              tablebox.add(myscrollpane);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 50;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.NORTH;
              addComponent(tablebox,0,0,3,1,GridBagConstraints.NORTH);
            //c.add (tablebox, BorderLayout.NORTH);
              //create center panel
              JLabel panellabel=new JLabel("Summarries");
              MyPanel panel =new MyPanel();
              panel.setSize (10, 50);
              panel.setBackground(Color.red);
              panellabel.setLabelFor(panel);
              Box panelbox=Box.createVerticalBox();
              panelbox.add(panellabel);
              panelbox.add(panel);
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
            //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.CENTER;
              addComponent(panelbox,1,1,1,1,GridBagConstraints.CENTER);
              //c.add (panelbox, BorderLayout.CENTER);
              //add time in the SOUTH part of the Frame
              Panel southpanel=new Panel();
              southpanel.setBackground(Color.magenta);
              Date time=new Date();
              String timestring=DateFormat.getDateTimeInstance().format(time);
              TextField timefield=new TextField("The Date and Time in Chicago is:"+" "+timestring, 50);
              southpanel.add(timefield);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 1;
              //gbConstraints.fill = GridBagConstraints.HORIZONTAL;
              gbConstraints.anchor = GridBagConstraints.SOUTH;
              addComponent(southpanel,0,2,3,1,GridBagConstraints.SOUTH);
              //c.add(southpanel, BorderLayout.SOUTH);
              //USE "BOX LAYOUT MANAGER" TO ARRANGE COMPONENTS LEFT TO RIGHT WITHIN THE SOUTH PART OF THE FRAME
              //Create a text area to output more information about the application.Place it in a box and place box EAST
              Font f=new Font("Serif", Font.ITALIC+Font.BOLD, 16);
              string="-If you would like to exit this program\n"+
              "-click on the exit menu item \n"+
                   "-if you would like to save the table as a text file \n"+
                   "-click on Save As menu item \n"+"-You can reenter new values for calculation\n"+
                   " as many times as you would like.\n"+
                   "-You can save the summaries also on a different file\n"+
                   "-Files are appended";
              JLabel infolabel= new JLabel ("Information About this Application", JLabel.RIGHT);
              JTextArea textarea=new JTextArea(25,25);
              textarea.setFont(f);
              textarea.append(string);
              infolabel.setLabelFor(textarea);
              Box box =Box.createVerticalBox();
              box.add(infolabel);
              box.add(new JScrollPane (textarea));
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHEAST;
              addComponent(box,2,1,1,1,GridBagConstraints.SOUTHEAST);
              //c.add(box, BorderLayout.EAST);
              //Create the text fields for entering data and place them in a box WEST
              Panel panelwest = new Panel();
              //create the first panelwest and place the text fields in it
              Box box1=Box.createVerticalBox();
              JLabel rate= new JLabel ("Enter Rate", JLabel.RIGHT);
              interestfield=new JTextField ("Enter Interest here and press Enter", 15);
              rate.setLabelFor(interestfield);
              box1.add(rate);
              box1.add(interestfield);
              JLabel period=new JLabel("Enter Amortization Periods", JLabel.RIGHT);
              timenumberfield=new JTextField("Enter amortization period in months and press Enter", 15);
              period.setLabelFor(timenumberfield);
              box1.add(period);
              box1.add(timenumberfield);
              JLabel loan=new JLabel("Enter Present Value of Loan", JLabel.RIGHT);
              loanamountfield =new JTextField ("Enter amount of loan and press Enter", 15);
              loan.setLabelFor(loanamountfield);
              box1.add(loan);
              box1.add(loanamountfield);
              JLabel submit = new JLabel("Press Submit Button to Calculate", JLabel.RIGHT);
              submitbutton= new JButton("SUBMIT");
              submit.setLabelFor(submitbutton);
              box1.add(submit);
              box1.add(submitbutton);
              panelwest.add(box1);
              //Add the panel to the content pane
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
              addComponent(panelwest,0,1,1,1,GridBagConstraints.SOUTHWEST);
              //c.add(panelwest, BorderLayout.WEST);
              //Event handler registration for text fields and submit button
              TextFieldHandler handler=new TextFieldHandler();
              interestfield.addActionListener(handler);
              timenumberfield.addActionListener(handler);
              loanamountfield.addActionListener(handler);
              submitbutton.addActionListener(handler);
              setSize(1000, 700);   
              setVisible(true);
              System.out.println("repainting table, constructor");
              System.out.println("I finished repainting. End of ConstructGUI");
         } // END OF CONSTUCTGUI
         // addComponent() is developed here
         private void addComponent(Component com,int row,int column,int width,int height,int ancor)
              //set gridx and gridy
              gbConstraints.gridx = column;
              gbConstraints.gridy = row;
              //set gridwidth and gridheight
              gbConstraints.gridwidth = width;
              gbConstraints.gridheight = height;
              gbConstraints.anchor = ancor;
              //set constraints
              gbLayout.setConstraints(com,gbConstraints);
              c.add(com);          
         

    Quit cross-posting (in different forums) every time you have a question.
    Quit multi-posting (asking the same questions twice) when you ask a question.
    Start responding to your old questions indicating whether the answers you have been given have been helpfull or not.
    Read the tutorial before asking a question. Start with [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use GridBag Layout. Of course its the most difficult Layout Manager to master so I would recommend you use various combinations of the other layout managers to achieve your desired results.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • My first menu: biting me in the Act..

    ..ionListener() . It's about time I added a menu to my [url http://r0k.us/graphics.SIHwheel.html]Interactive Color Wheel. Having never done menus in Java before, it's fighting me every stop of the way, even with the help of the tutorial. The good news is: I can build a menu that displays what I want, even if it looks funky. The bad news is: I cannot get it to do anything. I have tried two methods:
    ----- CNDfilelist.properties -----
    CND.file.01 = cnd_ntc.properties
    CND.name.01 = Name that Color
    CND.file.02 = cnd_resene2010.properties
    CND.name.02 = Resene 2010
    CND.file.03 = cnd_w3c.properties
    CND.name.03 = W3C Colors
    ----- from my pane constructor -----
         readCNDnames();  // successfully reads in the above
         JRadioButtonMenuItem item;
         ButtonGroup g = new ButtonGroup();
         JMenuBar menuBar = new JMenuBar();
         menuBar.setBorderPainted(false);
         menuBar.setPreferredSize(new Dimension(200, 14));
         JMenu dictionary = new JMenu("Color Lists");
         for (int i = 0; i < cndFileCount; i++) {
             item = new JRadioButtonMenuItem(cndFileList[1]);
         item.setActionCommand("cnd");
    //     item.addActionListener( new ActionListener() {
    //          public void actionPerformed(ActionEvent e) {
    //          changeCND(cndFileList[i][0]);
         if (i == 0) item.setSelected(true);
         g.add(item);
         dictionary.add(item);
         menuBar.add(dictionary);
         JMenu about = new JMenu("About");
         menuBar.add(about);
         add(menuBar, BorderLayout.PAGE_START);
    Two action methods have been attempted, traditional switchboard and anonymous. I've been using the switchboard approach, but with these JRadioButtonMenuItems I don't know what to put into the "cnd" clause of the class actionPerformed() method. It needs to load one of some indeterminate-until-runtime number color name dictionaries (from 1 to 99), but I don't know how to track back to see which actual item were selected. Alternatively, I could give each button a unique setActionCommand("cnd01"), ("cnd02"), etc., but i cannot imagine an elegant way to code for a variable number of such possiblities in the actionPerformed().
    So, that brings me to the anonymous listener approach, commented-out above. The problem is that the local variable i isn't actually available to the anonymous listener. The compiler complains:
    D:\progming\java\SIHwheel>javac -target 1.4 -source 1.4 SIHwheel.java
    SIHwheel.java:645: local variable i is accessed from within inner class; needs t
    o be declared final
                        changeCND(cndFileList[0]);
    ^
    1 error
    The message is actually funny; the very last thing i can be is final. There has got to be an elegant method to do this. What am I misssing?
    My other problem is the flow manager for the pane. I cannot seem to find the right one for what I need. I've tried several and am currently using :
    //     this.setLayout(new GridLayout(5, 1));
         this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    //     this.setLayout(new BorderLayout());
    //     this.setLayout(new GridBagLayout());I've even tried more than that, but the least problematic is the BoxLayout(). Here is a little picture:
    * http://r0k.us/rock/junk/SIHmenu.png
    The one problem BoxLayout is giving me is that it refuses to make the menu bar full pane width. You can see in the first code box that i'm telling it to be 200 wide, but it won't. It will change height, no problem, but not width. I've even tried adding:
    * menuBar.setMinimumSize(new Dimension(200, 14));
    but the width on that is ignored as well. You can see a remnant of my BorderLayout() attempt in
    * add(menuBar, BorderLayout.PAGE_START);
    BoxLayout ignores the 2nd parameter. BorderLayout gives me a full-width menu bar! But it funkily hides 2 of the pane's 5 components. They are supposed to lay right on top of each other:
         add(menuBar, BorderLayout.PAGE_START);
         add(sorts, BorderLayout.LINE_START);
         add(new JScrollPane(list), BorderLayout.LINE_START);
         add(spotPanel, BorderLayout.LINE_START);
         add(hexPanel, BorderLayout.PAGE_END);Instead it looks like this:
    * http://r0k.us/rock/junk/SIHborderLayoutProblem.png
    with both the sorts and scrollable list panel missing entirely. Only Spot, the Magic Color Dog comes out unscathed, but then, he's magic.
    In short, without the menuBar, BoxLayout was fine. But add the menBar , and BoxLayout refuses to do full pane width. Sigh, I think I'm going to take a nap -- been up since 4am.

    RichF wrote:
         JRadioButtonMenuItem item;
         ButtonGroup g = new ButtonGroup();
         JMenuBar menuBar = new JMenuBar();
         menuBar.setBorderPainted(false);
         menuBar.setPreferredSize(new Dimension(200, 14));
         JMenu dictionary = new JMenu("Color Lists");
         for (int i = 0; i < cndFileCount; i++) {
             final int j = i;  // magic necessary for anonymous actionPerformed
             item = new JRadioButtonMenuItem(cndFileList[1]);
         item.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              changeCND(cndFileList[j][0]);
         if (i == 0) item.setSelected(true);
         g.add(item);
         dictionary.add(item);
         menuBar.add(dictionary);
    You might find it easier to work wirh a [url http://tips4java.wordpress.com/2008/11/09/select-button-group/]Select Button Group[/url] which has methods for <tt>addPropertyChangeListener(...)</tt> and <tt>getSelectedIndex()</tt> that would allow you to write more concise code.
    db                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to clear the the rectangle........

    Hello,
    I'm doing a project in swings and i have drawn a rubberband rectangle in buffered image once the user clicks and drags mouse the dotted lines appear showing the boundary of rectangle and when the button is released the lines should become solid .
    But in my case after releasing the button the dotted lines will remain within the rectangle but i need only the outer lines of rectangle to be there.
    How to make those lines invisible which are in side the rectangle.
    Can anybody suggest some method to do it ?
    Thanks in advance,
    The code is:
    // Rubber1.java    basic rubber band for shape
    //                 Draw rectangle. left mouse down=first point     
    //                 Drag to second point. left mouse up=final point
    //                 right mouse changes color of first figure area
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Rubber1 extends JPanel
      int ax,ay,bx,by;     
      int winWidth = 500;
      int winHeight = 500;
      boolean tracking = false; // left button down, sense motion
      int startX = 0;
      int startY = 0;
      int currentX = 0;
      int currentY = 0;
      int num_fig = 0; // number of figures to draw
      int select = 0;  // the currently selected figure index
      Fig figure[] = new Fig[50]; // num_fig is number of figures to display
      BufferedImage BuffImage ;
      Graphics2D gb;
      Rubber1()
        //setTitle("Spiral");
        setSize(winWidth,winHeight);
        setBackground(Color.white);
        setForeground(Color.black);
        BuffImage = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
        gb = BuffImage.createGraphics();
        gb.setColor(Color.BLACK);
        /*addWindowListener(new WindowAdapter()
          public void windowClosing(WindowEvent e)
            System.exit(0);
        setVisible(true);
        this.addMouseListener (new mousePressHandler());
        this.addMouseListener (new mouseReleaseHandler());
        this.addMouseMotionListener (new mouseMotionHandler());
      class Fig // just partial structure, may add more
        int kind;           // kind of fig
        int x0, y0, x1, y1; // rectangle boundary
        double r, g, b;     // color values
        double width;
        Fig(){ kind=0; x0=0; y0=0; x1=0; y1=0;
                      r=0.0; g=0.0; b=5.0; width=0.0;}
         void mouseMotion(int x, int y)
            if(tracking)
             currentX = x;
             currentY = y;
             requestFocus();
             repaint();
          void startMotion(int x, int y)
            tracking = true;
             startX = x;
             startY = y;
             currentX = x;
             currentY = y; // zero size, may choose to ignore later
             requestFocus();
             repaint();
         void stopMotion(int x, int y)
           tracking = false; // no more rubber_rect
           // save final figure data for 'display' to draw
           currentX = x;
           currentY = y;
           figure[num_fig] = new Fig();
           figure[num_fig].kind = 1; /* just rectangles here */
           figure[num_fig].x0 = startX;
           figure[num_fig].y0 = startY;
           figure[num_fig].x1 = currentX;
           figure[num_fig].y1 = currentY;
           figure[num_fig].r = 1.0;
           figure[num_fig].g = 0.0;
           figure[num_fig].b = 0.0;
           figure[num_fig].width = 2.0;
           num_fig++;
           requestFocus();
           repaint();
      class mousePressHandler extends MouseAdapter
        public void mousePressed (MouseEvent e)
          int b;
          b = e.getButton();
          ax = e.getX();
          ay = e.getY();
           System.out.println("press x="+ax+"   y="+ay+" "); // debug print
          if(b==1) startMotion(ax, ay);  // right mouse
          if(b==3) pick(ax, ay);         // left mouse
        @Override
        public void mouseClicked(MouseEvent e)
             int n =0,o;
             if(MouseEvent.BUTTON3==e.getButton())
             n = e.getX();
             o = e.getY();
             menu( n , o);
        public void menu(int n ,int o)
             JFrame.setDefaultLookAndFeelDecorated(true);       
             JFrame frame = new JFrame("Parameters");
           // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            frame.add(panel,BorderLayout.SOUTH);
            JButton b1 = new JButton("PLOT");
            panel.add(b1);
          /*  b1.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent arg2)
                       Spiral spiral = new Spiral();
            b1.setMnemonic(KeyEvent.VK_P);
            JButton b2 = new JButton("CANCEL");
            panel.add(b2);
           b2.setMnemonic(KeyEvent.VK_C);
            b2.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent arg1)
                      System.exit(0);
            JMenuBar menubar = new JMenuBar();
            JMenu degmenu = new JMenu("Angle(D)");
            degmenu.add(new JSeparator());
            JMenu colmenu = new JMenu("Color");
           // colmenu.add(new JSeparator());
            JMenu spamenu = new JMenu("Spacing");
            //spamenu.add(new JSeparator());
            JMenuItem degItem1 = new JMenuItem("5");
            JMenuItem degItem2 = new JMenuItem("10");
            JMenuItem degItem3 = new JMenuItem("15"); 
            JMenuItem colItem1 = new JMenuItem("Color");
            colItem1.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent arg0)
                        // TODO Auto-generated method stub
                        ColorChooser chooseColor = new ColorChooser();
                        JFrame frame = new JFrame();
                        frame.setSize(450,330);
                        frame.add(chooseColor);
                        frame.setVisible(true);
                       //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            degmenu.add(degItem1);
            degmenu.add(degItem2);
            degmenu.add(degItem3);
            colmenu.add(colItem1);
            menubar.add(degmenu);
            menubar.add(colmenu);
            menubar.add(spamenu);
            frame.setJMenuBar(menubar);
            frame.setSize(180,120);
            frame.setVisible(true);  
            frame.setLocation( n+5 , o+5 );
      class mouseMotionHandler extends MouseMotionAdapter
        public void mouseDragged (MouseEvent e)
          int x, y;
          int b;
          b = e.getButton();
          x = e.getX();
          y = e.getY();
          mouseMotion(x, y);
         // rubberRect rub = new rubberRect();
      class mouseReleaseHandler extends MouseAdapter
        public void mouseReleased (MouseEvent e)
          int b; //int x, y;
          b  = e.getButton();
          bx = e.getX();
          by = e.getY();
          if(b==1) stopMotion(bx, by);
          System.out.println("press x=" +bx+"    y="+by+" ");
       public void rubberRect(Graphics2D gb, int x0, int y0, int x1 , int y1)
          // can apply to all figures
          // draw a rubber rectangle, mouse down, tracks mouse
           int x,y,x2,y2,x3,y3; // local coordinates
           x2=x0;
           x3=x1;
           if(x1<x0) {x2=x1; x3=x0;};
           y2=y0;
           y3=y1;
           if(y1<y0){y2=y1; y3=y0;};
             //gb.setColor(Color.black);
           for(x=x2; x<x3-3; x=x+8) // Java does not seem to have a
             {                        // dashed or stippled rectangle or line
               gb.drawLine(x, y0, x+4, y0);
               gb.drawLine(x, y1, x+4, y1);
           for(y=y2; y<y3-3; y=y+8)
               gb.drawLine(x0, y, x0, y+4);
               gb.drawLine(x1, y, x1, y+4);
      void fillRect(Graphics2D gb, Fig rect)
        int x, y;
        gb.setColor(new Color((float)rect.r, (float)rect.g, (float)rect.b));
        // g.setLineWidth(rect.width); ???
        x=rect.x0;
        if(rect.x1<rect.x0) x=rect.x1;;
        y=rect.y0;
        if(rect.y1<rect.y0) y=rect.y1;
        gb.drawRect(x, y, Math.abs(rect.x1-rect.x0),Math.abs(rect.y1-rect.y0));
        if(rect.width>1.0)
        gb.drawRect(x-1, y-1, Math.abs(rect.x1-rect.x0)+2,Math.abs(rect.y1-rect.y0)+2);
        //gb.clearRect(startX-10,startY-10,currentX-10,currentY-10);
      void pick(int x, int y)
        int i;
       // float t; search figures in list, select
        for(i=0; i<num_fig; i++)
          if(figure.x0 < figure[i].x1)
    if(x<figure[i].x0 || x>figure[i].x1) continue;
    if(figure[i].x1 < figure[i].x0)
    if(x<figure[i].x1 || x>figure[i].x0) continue;
    if(figure[i].y0 < figure[i].y1)
    if(y<figure[i].y0 || y>figure[i].y1) continue;
    if(figure[i].y1 < figure[i].y0)
    if(y<figure[i].y1 || y>figure[i].y0) continue;
    // select here by just changing color
    figure[select].r = 1.0;
    // figure[select].g = 0.0;
    select = i;
    figure[select].r = 0.0;
    // figure[select].g = 1.0;
    break;
    requestFocus();
    // repaint();
    protected void paintComponent(Graphics g)
    Graphics2D gb=(Graphics2D)g;
    //gb.setXORMode(getBackground());
    // gb.setXORMode(Color. gray); //border color
    if(tracking==true)rubberRect(gb,startX,startY,currentX,currentY);
    gb.drawImage(BuffImage,ax,ay,Color.white,this);
    for(int i=0;i<num_fig;i++)
    fillRect(gb, figure[i]);
    // gb.clearRect(startX-10,startY-10,currentX-10,currentY-10);
    public static void main(String args[])
         JFrame f = new JFrame();
         f.setSize(500,500);
         Rubber1 r = new Rubber1();
         f.add(r);
         f.setVisible(true);
    //new Rubber1();
    Edited by: sumukha on Nov 15, 2007 1:19 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Two things,
    1) Java does have dashed lines. Look into BasicStroke. You'll have to cast your Graphics object into a Graphics2D to use it, but it's quite simple to use.
    See http://java.sun.com/j2se/1.4.2/docs/guide/2d/spec/j2d-awt.html section 2.3.2.3.
    2) Rubber banding is much easier to do using XOR mode. The first drawing will use the difference between the color you're set at and the background. The second drawing over the same place with the same color will reverse the process. So to use it, you draw your rubber band, then to remove it, you draw over the old one without changing anything. You'll have to keep track of the last known position of the shape, but it's not too difficult once you get the hang of it. Use setPaintMode() to return to normal drawing. I couldn't find a good example on the net, so here's a simple example for a rectangle only:
       public void drawShape() {
          if (mCurrentRect != null) {
             Graphics2D g = (Graphics2D)getGraphics();
             if (mIsPermanent) {
                g.setPaintMode();
             } else {
                g.setXORMode(getBackground());
             g.draw(mCurrentRect);
             g.dispose();
       public void mousePressed(MouseEvent evt) {
          mCurrentRect = new Rectangle(evt.getX(), evt.getY(), 0, 0);
          mIsPermanent = false;
          drawShape();
       public void mouseDragged(MouseEvent evt) {
          if (mCurrentRect != null) {
             drawShape();      // Remove shape
             mCurrentRect.setRect(mCurrentRect.getX(), mCurrentRect.getY(), evt.getX(), evt.getY());
             drawShape();      // Redraw it
       public void mouseReleased(MouseEvent evt) {
          if (currentShape != null) {
             drawShape();      // Remove shape
             mCurrentRect.setRect(mCurrentRect.getX(), mCurrentRect.getY(), evt.getX(), evt.getY());
             mIsPermanent = true;
             drawShape();      // Redraw it
             mRectangleList.add(mCurrentRect); // iterate through in paintComponent to draw these
             mCurrentRect = null;
       }

  • Runtime help please

    Greetings,
    First off I will admit that this a part of a project for school. I am not asking for anyone to "give me code" or to "do it for me". I am having a problem tracing a runtime error with the below code. The error only occurs when you choose a selection from the jmenu (null pointer execption on line xyz). the jmenu is supposed to update the display in the JComboBox via the setSelectedItem() and the null pointer points towards the line for the setSelectedItem(). Any assistance in pointing me towards the source of the error is appreciated.
    source code follows:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class Polygon extends JFrame implements ActionListener
    {   // start Polygon Class
         /* Variable Declarations */
         Color color = Color.red;
         JComboBox comboBox;
         boolean moving;
         boolean overload;
         /* End Variable Declarations */
         Polygon()
         { //start Polygon contructor
              addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   }); // ends anon class for window closing (ends program)
         /* Creation of the MenuBar */
         JMenuBar menu = new JMenuBar();
         JMenu menuColor = new JMenu("Color");
         JMenuItem makeRed = new JMenuItem("Red");
              menuColor.add(makeRed);
              makeRed.addActionListener(this);
         JMenuItem makeBlue = new JMenuItem("Blue");
              menuColor.add(makeBlue);
              makeBlue.addActionListener(this);
         JMenuItem makeGreen = new JMenuItem("Green");
              menuColor.add(makeGreen);
              makeGreen.addActionListener(this);
         JMenuItem makeYellow = new JMenuItem("Yellow");
              menuColor.add(makeYellow);
              makeYellow.addActionListener(this);
         menu.add(menuColor);
         setJMenuBar(menu);
         /* End Creation of the MenuBar */
         /* Creation of the Combo box*/
         Object [] items = {"Red", "Blue", "Green", "Yellow"};
         JComboBox comboBox = new JComboBox(items);
         getContentPane().add(comboBox, BorderLayout.SOUTH);
         comboBox.addActionListener(new ActionListener()
                   { //start anon class
                        public void actionPerformed(ActionEvent e)
                             { //start action Performed
                                  JComboBox comboBox = (JComboBox)e.getSource();
                                  String comboString = (String)comboBox.getSelectedItem();
                                       if(comboString.equals("Red"))
                                  color = Color.red;
                                       else if(comboString.equals("Green"))
                                            color = Color.green;
                                       else if(comboString.equals("Blue"))
                                            color = Color.blue;
                                       else if(comboString.equals("Yellow"))
                                            color = Color.yellow;
                             } //end actionPerformed
                        } //end anon class
                   ); //end function call for anon class
         /* End Creation of the Combobox */
         }// end Polygon contructor
         public void actionPerformed(ActionEvent e)
         {  // begins Actions
              JMenuItem menu = (JMenuItem)e.getSource();
              String menuString = menu.getText();
         if(menuString.equals("Yellow"))
         color = Color.yellow;
         comboBox.setSelectedItem("Yellow");
         else if(menuString.equals("Red"))
         color = Color.red;
         comboBox.setSelectedItem("Red");
         else if(menuString.equals("Blue"))
         color = Color.blue;
         comboBox.setSelectedItem("Blue");
         else if(menuString.equals("Green"))
         color = Color.green;
         comboBox.setSelectedItem("Green");
         } //ends Actions
    public static void main (String []args)
         JFrame frame = new Polygon();
         frame.setTitle("Project 3");
         frame.setSize(300, 300);
         frame.setVisible(true);
    } //end main
    }//end Ploygon Class

    hi
    I checked ur code.
    the problem is that u have initialized objects more than one time un necesssarly.
    my friend for selecting an item from a combo box there are some methods iside java plz refer to them.
    do not use String .equal() ...
    i am sue that u will get ue souirce code copiled if u remove those problem,s.

  • Storing shape information in table

    Hi All,
    I have a Program which displays shape (rectangle,oval,etc) in the panel which is enclosed in a frame.. shape can be dragged and dropped anywhere on panel... also one can delete shape... Now I Want To Store All The Exiting Shapes (as they are added on panel ) in some structure say a table, and alongwith it, i also want to store additional information about shape, say its location currently on panel, its present color, etc so that i can use this information later in the program... how do i do implement this ?? Plz Help Me.. It would be great if you include the changes in the source code itself...
    thanks
    Here is the source code :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class ShapeDrawFrame extends javax.swing.JFrame {
        JCheckBoxMenuItem addLargeShapes;    
       JCheckBoxMenuItem addBorderedShapes; 
       JRadioButtonMenuItem red, green, blue,      
                            cyan, magenta, yellow, 
                            black, gray, white;  
       JPopupMenu popup;
        public ShapeDrawFrame() {
            super("Shape Draw");
            //initComponents();        
          ShapeCanvas canvas = new ShapeCanvas();
          setContentPane(canvas);
          /* Create the menu bar and the menus */
          JMenuBar menubar = new JMenuBar();
          setJMenuBar(menubar);
          JMenu addShapeMenu = new JMenu("Add");
          addShapeMenu.setMnemonic('A');
          menubar.add(addShapeMenu);
          JMenu shapeColorMenu = new JMenu("Color");
          shapeColorMenu.setMnemonic('C');
          menubar.add(shapeColorMenu);
          JMenu optionsMenu = new JMenu("Options");
          optionsMenu.setMnemonic('O');
          menubar.add(optionsMenu);
          /* Create menu items for adding shapes to the canvas,
             and add them to the "Add" menu.  The canvas serves
             as ActionListener for these menu items. */     
          JMenuItem rect = new JMenuItem("Rectangle");
          rect.setAccelerator( KeyStroke.getKeyStroke("ctrl R") );
          addShapeMenu.add(rect);
          rect.addActionListener(canvas);
          JMenuItem oval = new JMenuItem("Oval");
          oval.setAccelerator( KeyStroke.getKeyStroke("ctrl O") );
          addShapeMenu.add(oval);
          oval.addActionListener(canvas);
          JMenuItem roundrect = new JMenuItem("Round Rect");
          roundrect.setAccelerator( KeyStroke.getKeyStroke("ctrl D") );
          addShapeMenu.add(roundrect);
          roundrect.addActionListener(canvas);
          /* Create the JRadioButtonMenuItems that control the color
             of a newly added shape, and add them to the "Color"
             menu.  There is no ActionListener for these menu items.
             The canvas checks for the currently selected color when
             it adds a shape to the canvas.  A ButtonGroup is used
             to make sure that only one color is selected. */
          ButtonGroup colorGroup = new ButtonGroup();
          red = new JRadioButtonMenuItem("Red");
          shapeColorMenu.add(red);
          colorGroup.add(red);
          red.setSelected(true);
          green = new JRadioButtonMenuItem("Green");
          shapeColorMenu.add(green);
          colorGroup.add(green);
          blue = new JRadioButtonMenuItem("Blue");
          shapeColorMenu.add(blue);
          colorGroup.add(blue);
          cyan = new JRadioButtonMenuItem("Cyan");
          shapeColorMenu.add(cyan);
          colorGroup.add(cyan);
          magenta = new JRadioButtonMenuItem("Magenta");
          shapeColorMenu.add(magenta);
          colorGroup.add(magenta);
          yellow = new JRadioButtonMenuItem("Yellow");
          shapeColorMenu.add(yellow);
          colorGroup.add(yellow);
          black = new JRadioButtonMenuItem("Black");
          shapeColorMenu.add(black);
          colorGroup.add(black);
          gray = new JRadioButtonMenuItem("Gray");
          shapeColorMenu.add(gray);
          colorGroup.add(gray);
          white = new JRadioButtonMenuItem("White");
          shapeColorMenu.add(white);
          colorGroup.add(white);
          /* Create the "Clear" menu item, and add it to the
             "Options" menu.  The canvas will listen for events
             from this menu item. */
          JMenuItem clear = new JMenuItem("Clear");
          clear.setAccelerator( KeyStroke.getKeyStroke("ctrl C") );
          clear.addActionListener(canvas);
          optionsMenu.add(clear);
          optionsMenu.addSeparator();  // Add a separating line to the menu.
          /* Create the JCheckBoxMenuItems and add them to the Options
             menu.  There is no ActionListener for these items because
             the canvas class will check their state when it adds a
             new shape. */
          addLargeShapes = new JCheckBoxMenuItem("Add Large Shapes");
          addLargeShapes.setSelected(true);
          optionsMenu.add(addLargeShapes);
          addBorderedShapes = new JCheckBoxMenuItem("Add Shapes with Border");
          addBorderedShapes.setSelected(true);
          optionsMenu.add(addBorderedShapes);
          optionsMenu.addSeparator();
          /* Create a menu for background colors, and add it to the
             "Options" menu.  It will show up as a hierarchical sub-menu. */
          JMenu background = new JMenu("Background Color");
          optionsMenu.add(background);
          background.add("Red").addActionListener(canvas);
          background.add("Green").addActionListener(canvas);
          background.add("Blue").addActionListener(canvas);
          background.add("Cyan").addActionListener(canvas);
          background.add("Magenta").addActionListener(canvas);
          background.add("Yellow").addActionListener(canvas);
          background.add("Black").addActionListener(canvas);
          background.add("Gray").addActionListener(canvas);
          background.add("White").addActionListener(canvas);
          /* Create the pop-up menu and add commands for editing a
             shape.  This menu is not used until the user performs
             the pop-up trigger mouse gesture on a shape. */
          popup = new JPopupMenu();
          popup.add("Delete Shape").addActionListener(canvas);
          popup.add("Bring to Front").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Make Large").addActionListener(canvas);
          popup.add("Make Small").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Add Black Border").addActionListener(canvas);
          popup.add("Remove Black Border").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Set Color to Red").addActionListener(canvas);
          popup.add("Set Color to Green").addActionListener(canvas);
          popup.add("Set Color to Blue").addActionListener(canvas);
          popup.add("Set Color to Cyan").addActionListener(canvas);
          popup.add("Set Color to Magenta").addActionListener(canvas);
          popup.add("Set Color to Yellow").addActionListener(canvas);
          popup.add("Set Color to Black").addActionListener(canvas);
          popup.add("Set Color to Gray").addActionListener(canvas);
          popup.add("Set Color to White").addActionListener(canvas);
          /* Set the "DefaultCloseOperation" for the frame.  This determines
             what happens when the user clicks the close box of the frame.
             It is set here so that System.exit() will be called to end
             the program when the user closes the window. */
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          /* Set the size and location of the frame, and make it visible. */
          setLocation(20,50);
          setSize(550,420);
          show();       
       class ShapeCanvas extends JPanel
                         implements ActionListener, MouseListener, MouseMotionListener {
             // This class represents a "canvas" that can display colored shapes and
             // let the user drag them around.  It uses an off-screen images to
             // make the dragging look as smooth as possible.
          ArrayList shapes = new ArrayList();
               // holds a list of the shapes that are displayed on the canvas
          ShapeCanvas() {
               // Constructor: set background color to white
               // set up listeners to respond to mouse actions
             setBackground(Color.white);
             addMouseListener(this);
             addMouseMotionListener(this);
          public void paintComponent(Graphics g) {
               // In the paint method, all the shapes in ArrayList are
               // copied onto the canvas.
             super.paintComponent(g);  // First, fill with background color.
             int top = shapes.size();
             for (int i = 0; i < top; i++) {
                Shape s = (Shape)shapes.get(i);
                s.draw(g);
          public void actionPerformed(ActionEvent evt) {
                 // Called to respond to action events from the
                 // menus or pop-up menu.
             String command = evt.getActionCommand();
             if (command.equals("Clear")) {
                shapes.clear(); // Remove all items from the ArrayList
                repaint();
             else if (command.equals("Rectangle"))
                addShape(new RectShape());
             else if (command.equals("Oval"))
                addShape(new OvalShape());
             else if (command.equals("Round Rect"))
                addShape(new RoundRectShape());
             else if (command.equals("Red"))
                setBackground(Color.red);
             else if (command.equals("Green"))
                setBackground(Color.green);
             else if (command.equals("Blue"))
                setBackground(Color.blue);
             else if (command.equals("Cyan"))
                setBackground(Color.cyan);
             else if (command.equals("Magenta"))
                setBackground(Color.magenta);
             else if (command.equals("Yellow"))
                setBackground(Color.yellow);
             else if (command.equals("Black"))
                setBackground(Color.black);
             else if (command.equals("Gray"))
                setBackground(Color.gray);
             else if (command.equals("White"))
                setBackground(Color.white);
             else if (clickedShape != null) {
                    // Process a command from the pop-up menu.
                if (command.equals("Delete Shape"))
                   shapes.remove(clickedShape);
                else if (command.equals("Bring to Front")) {
                   shapes.remove(clickedShape);
                   shapes.add(clickedShape); 
                else if (command.equals("Make Large"))
                   clickedShape.setSize(100,60);
                else if (command.equals("Make Small"))
                   clickedShape.setSize(50,30);
                else if (command.equals("Add Black Border"))
                   clickedShape.setDrawOutline(true);
                else if (command.equals("Remove Black Border"))
                   clickedShape.setDrawOutline(false);
                else if (command.equals("Set Color to Red"))
                   clickedShape.setColor(Color.red);
                else if (command.equals("Set Color to Green"))
                   clickedShape.setColor(Color.green);
                else if (command.equals("Set Color to Blue"))
                   clickedShape.setColor(Color.blue);
                else if (command.equals("Set Color to Cyan"))
                   clickedShape.setColor(Color.cyan);
                else if (command.equals("Set Color to Magenta"))
                   clickedShape.setColor(Color.magenta);
                else if (command.equals("Set Color to Yellow"))
                   clickedShape.setColor(Color.yellow);
                else if (command.equals("Set Color to Black"))
                   clickedShape.setColor(Color.black);
                else if (command.equals("Set Color to Gray"))
                   clickedShape.setColor(Color.gray);
                else if (command.equals("Set Color to White"))
                   clickedShape.setColor(Color.white);
                repaint();
          } // end actionPerformed()
          void addShape(Shape shape) {
                 // Add the shape to the canvas, and set its size, color
                 // and whether or not it should have a black border.  These
                 // properties are determined by looking at the states of
                 // various menu items.  The shape is added at the top-left
                 // corner of the canvas.
             if (red.isSelected())
                shape.setColor(Color.red);
             else if (blue.isSelected())
                shape.setColor(Color.blue);
             else if (green.isSelected())
                shape.setColor(Color.green);
             else if (cyan.isSelected())
                shape.setColor(Color.cyan);
             else if (magenta.isSelected())
                shape.setColor(Color.magenta);
             else if (yellow.isSelected())
                shape.setColor(Color.yellow);
             else if (black.isSelected())
                shape.setColor(Color.black);
             else if (white.isSelected())
                shape.setColor(Color.white);
             else
                shape.setColor(Color.gray);
             shape.setDrawOutline( addBorderedShapes.isSelected() );
             if (addLargeShapes.isSelected())
                shape.reshape(3,3,100,60);
             else
                shape.reshape(3,3,50,30);
             shapes.add(shape);
             repaint();
          } // end addShape()
          // -------------------- This rest of this class implements dragging ----------------------
          Shape clickedShape = null;  // This is the shape that the user clicks on.
                                      // It becomes the draggedShape is the user is
                                      // dragging, unless the user is invoking a
                                      // pop-up menu.  This variable is used in
                                      // actionPerformed() when a command from the
                                      // pop-up menu is processed.
          Shape draggedShape = null;  // This is null unless a shape is being dragged.
                                      // A non-null value is used as a signal that dragging
                                      // is in progress, as well as indicating which shape
                                      // is being dragged.
          int prevDragX;  // During dragging, these record the x and y coordinates of the
          int prevDragY;  //    previous position of the mouse.
          public void mousePressed(MouseEvent evt) {
                // User has pressed the mouse.  Find the shape that the user has clicked on, if
                // any.  If there is no shape at the position when the mouse was clicked, then
                // ignore this event.  If there is then one of three things will happen:
                // If the event is a pop-up trigger, then the pop-up menu is displayed, and
                // the user can select from the pop-up menu to edit the shape.  If the user was
                // holding down the shift key, then bring the clicked shape to the front, in
                // front of all the other shapes.  Otherwise, start dragging the shape.
             if (draggedShape != null) {
                  // A drag operation is already in progress, so ignore this click.
                  // This might happen if the user clicks a second mouse button before
                  // releasing the first one(?).
                return;
             int x = evt.getX();  // x-coordinate of point where mouse was clicked
             int y = evt.getY();  // y-coordinate of point
             clickedShape = null;  // This will be set to the clicked shape, if any.
             for ( int i = shapes.size() - 1; i >= 0; i-- ) { 
                    // Check shapes from front to back.
                Shape s = (Shape)shapes.get(i);
                if (s.containsPoint(x,y)) {
                   clickedShape = s;
                   break;
             if (clickedShape == null) {
                   // The user did not click on a shape.
                return;
             else if (evt.isPopupTrigger()) {
                  // The user wants to see the pop-up menu
                popup.show(this,x-10,y-2);
             else if (evt.isShiftDown()) {
                  // Bring the clicked shape to the front
                shapes.remove(clickedShape);
                shapes.add(clickedShape);
                repaint();
             else {
                  // Start dragging the shape.
                draggedShape = clickedShape;
                prevDragX = x;
                prevDragY = y;
          public void mouseDragged(MouseEvent evt) {
                 // User has moved the mouse.  Move the dragged shape by the same amount.
             if (draggedShape == null) {
                    // User did not click a shape.  There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
          public void mouseReleased(MouseEvent evt) {
                 // User has released the mouse.  Move the dragged shape, and set
                 // draggedShape to null to indicate that dragging is over.
                 // If the shape lies completely outside the canvas, remove it
                 // from the list of shapes (since there is no way to ever move
                 // it back on screen).  However, if the event is a popup trigger
                 // event, then show the popup menu instead.
             if (draggedShape == null) {
                   // User did not click on a shape. There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             if (evt.isPopupTrigger()) {
                   // Check whether the user is trying to pop up a menu.
                   // (This should be checked in both the mousePressed() and
                   // mouseReleased() methods.)
                popup.show(this,x-10,y-2);
             else {
                draggedShape.moveBy(x - prevDragX, y - prevDragY);
                if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height ||
                        draggedShape.left + draggedShape.width < 0 ||
                        draggedShape.top + draggedShape.height < 0 ) {  // shape is off-screen
                   shapes.remove(draggedShape);  // remove shape from list of shapes
                repaint();
             draggedShape = null;  // Dragging is finished.
          public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
          public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
          public void mouseMoved(MouseEvent evt) { }
          public void mouseClicked(MouseEvent evt) { }
       }  // end class ShapeCanvas
       // ------- Nested class definitions for the abstract Shape class and three -----
       // -------------------- concrete subclasses of Shape. --------------------------
       static abstract class Shape {
             // A class representing shapes that can be displayed on a ShapeCanvas.
             // The subclasses of this class represent particular types of shapes.
             // When a shape is first constructed, it has height and width zero
             // and a default color of white.
          int left, top;      // Position of top left corner of rectangle that bounds this shape.
          int width, height;  // Size of the bounding rectangle.
          Color color = Color.white;  // Color of this shape.
          boolean drawOutline;  // If true, a black border is drawn on the shape
          void reshape(int left, int top, int width, int height) {
                // Set the position and size of this shape.
             this.left = left;
             this.top = top;
             this.width = width;
             this.height = height;
          void setSize(int width, int height) {
                // Set the size of this shape
             this.width = width;
             this.height = height;
          void moveBy(int dx, int dy) {
                 // Move the shape by dx pixels horizontally and dy pixels vertically
                 // (by changing the position of the top-left corner of the shape).
             left += dx;
             top += dy;
          void setColor(Color color) {
                 // Set the color of this shape
             this.color = color;
          void setDrawOutline(boolean draw) {
                 // If true, a black outline is drawn around this shape.
             drawOutline = draw;
          boolean containsPoint(int x, int y) {
                // Check whether the shape contains the point (x,y).
                // By default, this just checks whether (x,y) is inside the
                // rectangle that bounds the shape.  This method should be
                // overridden by a subclass if the default behavior is not
                // appropriate for the subclass.
             if (x >= left && x < left+width && y >= top && y < top+height)
                return true;
             else
                return false;
          abstract void draw(Graphics g); 
                // Draw the shape in the graphics context g.
                // This must be overridden in any concrete subclass.
       }  // end of class Shape
       static class RectShape extends Shape {
             // This class represents rectangle shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRect(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRect(left,top,width,height);
       static class OvalShape extends Shape {
              // This class represents oval shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillOval(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawOval(left,top,width,height);
          boolean containsPoint(int x, int y) {
                // Check whether (x,y) is inside this oval, using the
                // mathematical equation of an ellipse.
             double rx = width/2.0;   // horizontal radius of ellipse
             double ry = height/2.0;  // vertical radius of ellipse
             double cx = left + rx;   // x-coord of center of ellipse
             double cy = top + ry;    // y-coord of center of ellipse
             if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
                return true;
             else
               return false;
       static class RoundRectShape extends Shape {
              // This class represents rectangle shapes with rounded corners.
              // (Note that it uses the inherited version of the
              // containsPoint(x,y) method, even though that is not perfectly
              // accurate when (x,y) is near one of the corners.)
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRoundRect(left,top,width,height,width/3,height/3);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRoundRect(left,top,width,height,width/3,height/3);
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShapeDrawFrame().setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }

    Kartik_Nibjiya wrote:
    I Want To Keep Track Of Each Shape Throughout as long as i dont exit my program and Each Of Its Individual Properties... How Do I DO That ??Well, in your programm you have the structure "shapes" where you keep track of each shape object containing each of its induvidual properties. So I don't understand what else you might want.

  • Menus, Tabs and Tree Views I need some help

    heya,
    I am quite new here! I was searching desperately on a solution on how to fix my code. I need to do a menu in Java and bellow two boxes, one in which I will display a static tree structure (on the left side of the window) and one where I have some tabs (on the irght side of the window).
    Now, today I was playing around with the tree structure view and also trying to use modules in my code for a more easy debugging and understanding later on and I managed to screw up the functionality for good :D.
    Please some help, where am I going wrong and what is missing in my application.
    Here are my 4 files:
    ______File ModulMeniu____________
    package modules;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JTabbedPane;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.ImageIcon;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.net.URL;
    import java.io.IOException;
    public class ModulMeniu extends JPanel {
    protected Action loadConfigurationAction, saveConfigurationAction, stopAction, continueAction, exitAction, newFilterAction, allFiltersSentAction;
    protected Action currentFilterAction, allComputersAction, probesAction, deleteAction, resetAction, hideComputersAction, backgroundAction;
    protected Action computerAction, filterAction, searchFilterByNameAction, searchPackageByPositionAction, deleteFilterAndRuleAction ;
    public ModulMeniu() {
    //Creates the actions shared by the toolbar and menu.
    loadConfigurationAction = new LoadConfigurationAction("Load Configuration",
    "This allows to load a previous configuration.",
    new Integer(KeyEvent.VK_L));
    saveConfigurationAction = new SaveConfigurationAction("Save Configuration",
    "This allows to save the current configuration.",
    new Integer(KeyEvent.VK_S));
    stopAction = new StopAction( "Stop",
    "This stops the Client.",
    new Integer(KeyEvent.VK_T));
    continueAction = new ContinueAction( "Continue",
    "This continues the traffic observing where we left on.",
    new Integer(KeyEvent.VK_C));
    exitAction = new ExitAction( "Exit",
    "This exits the Application.",
    new Integer(KeyEvent.VK_E));
    newFilterAction = new NewFilterAction( "New Filter",
    "This creates a new filter.",
    new Integer(KeyEvent.VK_N));
              allFiltersSentAction = new AllFiltersSentAction( "All Filters Sent",
    "This displays all the filters sent.",
    new Integer(KeyEvent.VK_A));
    currentFilterAction = new CurrentFilterAction( "Current Filter",
    "This displays the current filter.",
    new Integer(KeyEvent.VK_C));
    allComputersAction = new AllComputersAction( "All Computers",
    "This displays all the computers in the network.",
    new Integer(KeyEvent.VK_L));
    probesAction = new ProbesAction( "Probes",
    "This displays all the probes in the network.",
    new Integer(KeyEvent.VK_P));
    deleteAction = new DeleteAction( "Delete",
    "This deletes the filter.",
    new Integer(KeyEvent.VK_D));
    resetAction = new ResetAction( "Reset",
    "This resets the client.",
    new Integer(KeyEvent.VK_R));
    hideComputersAction = new HideComputersAction( "Hide Computers",
    "This hides given computers.",
    new Integer(KeyEvent.VK_H));
    backgroundAction = new BackgroundAction( "Background",
    "This sets the background color.",
    new Integer(KeyEvent.VK_B));
    computerAction = new ComputerAction( "Computer",
    "This sets the computer color.",
    new Integer(KeyEvent.VK_C));
    filterAction = new FilterAction( "Filter",
    "This sets the filter color.",
    new Integer(KeyEvent.VK_F));
    searchFilterByNameAction = new SearchFilterByNameAction( "Search Filter By Name",
    "This searches a filter by its name.",
    new Integer(KeyEvent.VK_F));
    deleteFilterAndRuleAction = new DeleteFilterAndRuleAction( "Delete Filter And Rule",
    "This deletes a filter or a rule.",
    new Integer(KeyEvent.VK_D));
    public JMenuBar createMenuBar() {
    JMenuItem menuItem = null;
    JMenuBar menuBar;
    //Create the menu bar.
    menuBar = new JMenuBar();
    //Create the first menu.
    JMenu fileMenu = new JMenu("File");
    JMenu setMenu = new JMenu("Set");
    JMenu viewMenu = new JMenu("View");
    JMenu optionsMenu = new JMenu("Options");
    JMenu colorsMenu = new JMenu("Colors");
    JMenu searchMenu = new JMenu("Search");
    JMenu deleteMenu = new JMenu("Delete");
    Action[] actions1 = {loadConfigurationAction, saveConfigurationAction, stopAction, continueAction, exitAction};
    for (int i = 0; i < actions1.length; i++) {
    menuItem = new JMenuItem(actions1);
    fileMenu.add(menuItem);
    Action[] actions2 = {newFilterAction};
    menuItem = new JMenuItem(actions2[0]);
    setMenu.add(menuItem);
    Action[] actions3 = {allFiltersSentAction, currentFilterAction, allComputersAction, probesAction};
    for (int j = 0; j < actions3.length; j++) {
    menuItem = new JMenuItem(actions3[j]);
    viewMenu.add(menuItem);
    Action[] actions4 = {deleteAction, resetAction, hideComputersAction};
    for (int i = 0; i < actions4.length; i++) {
    menuItem = new JMenuItem(actions4[i]);
    optionsMenu.add(menuItem);
    Action[] actions5 = {backgroundAction, computerAction, filterAction};
    for (int i = 0; i < actions5.length; i++) {
    menuItem = new JMenuItem(actions5[i]);
    colorsMenu.add(menuItem);
    Action[] actions6 = {searchFilterByNameAction};
    menuItem = new JMenuItem(actions6[0]);
    searchMenu.add(menuItem);
    Action[] actions7 = {deleteFilterAndRuleAction};
    menuItem = new JMenuItem(actions7[0]);
    deleteMenu.add(menuItem);
    //Set up the menu bar.
    menuBar.add(fileMenu);
    menuBar.add(setMenu);
    menuBar.add(viewMenu);
    menuBar.add(optionsMenu);
    menuBar.add(colorsMenu);
    menuBar.add(searchMenu);
    menuBar.add(deleteMenu);
    return menuBar;
    public class LoadConfigurationAction extends AbstractAction {
    public LoadConfigurationAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class SaveConfigurationAction extends AbstractAction {
    public SaveConfigurationAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class StopAction extends AbstractAction {
    public StopAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class ContinueAction extends AbstractAction {
    public ContinueAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class ExitAction extends AbstractAction {
    public ExitAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class NewFilterAction extends AbstractAction {
    public NewFilterAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class AllFiltersSentAction extends AbstractAction {
    public AllFiltersSentAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class CurrentFilterAction extends AbstractAction {
    public CurrentFilterAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class AllComputersAction extends AbstractAction {
    public AllComputersAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class ProbesAction extends AbstractAction {
    public ProbesAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class DeleteAction extends AbstractAction {
    public DeleteAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class ResetAction extends AbstractAction {
    public ResetAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class HideComputersAction extends AbstractAction {
    public HideComputersAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class BackgroundAction extends AbstractAction {
    public BackgroundAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class ComputerAction extends AbstractAction {
    public ComputerAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class FilterAction extends AbstractAction {
    public FilterAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class SearchFilterByNameAction extends AbstractAction {
    public SearchFilterByNameAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    public class DeleteFilterAndRuleAction extends AbstractAction {
    public DeleteFilterAndRuleAction(String text,String desc, Integer mnemonic) {
    super(text);
    putValue(SHORT_DESCRIPTION, desc);
    putValue(MNEMONIC_KEY, mnemonic);
    public void actionPerformed(ActionEvent e) {
    ___FIle ModulTabbedArea________
    //pls consider I have all the imports of the first file
    public class ModulTabbedArea extends JPanel{
         public JTabbedPane tabbedPane;
         public ModulTabbedArea(){
         public JTabbedPane createTabbedArea(){
    Border paneEdge = BorderFactory.createEmptyBorder(0,10,10,10);
    JPanel IP = new JPanel();
    IP.setBorder(paneEdge);
    IP.setLayout(new BoxLayout(IP,BoxLayout.Y_AXIS));
    JPanel TCP = new JPanel();
    TCP.setBorder(paneEdge);
    TCP.setLayout(new BoxLayout(TCP,BoxLayout.Y_AXIS));
    JPanel UDP = new JPanel();
    UDP.setBorder(paneEdge);
    UDP.setLayout(new BoxLayout(UDP,BoxLayout.Y_AXIS));
    JPanel ICMP = new JPanel();
    ICMP.setBorder(paneEdge);
    ICMP.setLayout(new BoxLayout(ICMP,BoxLayout.Y_AXIS));
    JPanel ARP = new JPanel();
    ARP.setBorder(paneEdge);
    ARP.setLayout(new BoxLayout(ARP,BoxLayout.Y_AXIS));
    JPanel RARP = new JPanel();
    RARP.setBorder(paneEdge);
    RARP.setLayout(new BoxLayout(RARP,BoxLayout.Y_AXIS));
    JPanel UNKNOWN = new JPanel();
    UNKNOWN.setBorder(paneEdge);
    UNKNOWN.setLayout(new BoxLayout(UNKNOWN,BoxLayout.Y_AXIS));
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("IP", null, IP, null);
    tabbedPane.addTab("TCP", null, TCP, null);
    tabbedPane.addTab("UDP", null, UDP, null);
    tabbedPane.addTab("ICMP", null, ICMP, null);
    tabbedPane.addTab("ARP", null, ARP, null);
    tabbedPane.addTab("RARP", null, RARP, null);
    tabbedPane.addTab("UNKNOWN", null, UNKNOWN, null);
    return(tabbedPane);
    ___File ModulTree____
    //all the imports and the import of the package above
    public class ModulTree extends JPanel implements TreeSelectionListener {
    public JTree tree;
    private boolean DEBUG = false;
    public ModulTree() {
    //Create the nodes.
    DefaultMutableTreeNode top =new DefaultMutableTreeNode("Computers:");
    createNodes(top);
    //Create a tree that allows one selection at a time.
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
    //Listen for when the selection changes.
    tree.addTreeSelectionListener(this);
    /** Required by TreeSelectionListener interface. */
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
    tree.getLastSelectedPathComponent();
    if (node == null) return;
    Object nodeInfo = node.getUserObject();
    if (node.isLeaf()) {
    IPInfo ipAndName = (IPInfo)nodeInfo;
    if (DEBUG){           
    if (ipAndName.name==""){
         System.out.println(ipAndName.ip+ ": \n ");
    else {
    System.out.print(ipAndName.ip + ipAndName.name + ": \n ");
    if (DEBUG) {
    System.out.println(nodeInfo.toString());
    private class IPInfo {
    public String ip;
    public String name;
    public IPInfo(String adresaIP, String numeleComputerului) {
    ip=adresaIP;
    name=numeleComputerului;
    public String toString() {
    return ip + name;
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode ipAndName = null;
    category = new DefaultMutableTreeNode("Computers in the Network");
    top.add(category);
    ipAndName = new DefaultMutableTreeNode(new IPInfo
    ("216.27.61.137",
    "Artemis"));
    category.add(ipAndName);
    ipAndName = new DefaultMutableTreeNode(new IPInfo
    ("216.32.61.132",
    "Venus"));
    category.add(ipAndName);
    ipAndName = new DefaultMutableTreeNode(new IPInfo
    ("216.132.61.11",
    "Zeus"));
    category.add(ipAndName);
    category = new DefaultMutableTreeNode("Probes in the Network");
    top.add(category);
    ipAndName = new DefaultMutableTreeNode(new IPInfo
    ("10.11.11.1",
    "Probe1"));
    category.add(ipAndName);
    ipAndName = new DefaultMutableTreeNode(new IPInfo
    ("10.11.1.1",
    "Probe2"));
    category.add(ipAndName);
    __File ModulMain___
    //all the imports and imports also modules.*
    public class ModulMain extends JFrame{
         public ModulMain(){
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Sistem grafic de monitorizare a unei retele");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create/set menu bar and content pane.
    ModulMeniu menu = new ModulMeniu();
    frame.setJMenuBar(menu.createMenuBar());
    //Create the scroll pane and add the tree to it.
    JScrollPane treeView = new JScrollPane(tree);
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setLeftComponent(treeView);
    splitPane.setRightComponent(tabbedPane);
    Dimension minimumSize = new Dimension(100, 50);
    tabbedPane.setMinimumSize(minimumSize);
    treeView.setMinimumSize(minimumSize);
    splitPane.setDividerLocation(100); //XXX: ignored in some releases
    //of Swing. bug 4101306
    //workaround for bug 4101306:
    //treeView.setPreferredSize(new Dimension(100, 100));
    splitPane.setPreferredSize(new Dimension(500, 300));
    //Add the split pane to this panel.
    add(splitPane);
    menu.setOpaque(true); //content panes must be opaque
    frame.setContentPane(menu);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    This is it guys! The code is not hard, just long and I need to deliver this project and I just dunno what to do to it to make it work :(. I appreciate any help I can get :p.
    THANK YOU for your time!
    Cristina

    hey friend,
    i don't have solution to your problem but i am facing the same problem in my project, i need to fetch filenames from folder and show it in a tree view. if you have any solution then please refer me with code..!1
    thanx in advance..

  • G.drawLine problem...

    I'm trying to make it so you click and option from the menu bar which will then open a JDialogBox, you enter text, it turns it into a string, then use g.drawline to ad it to the JPanel.
    Heres my code:
    // Scribble.java //
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    * This JFrame subclass is a simple "paint" application.
    public class Scribble extends JFrame {   
       * The main method instantiates an instance of the class, sets it size, and
       * makes it visible on the screen
      public static void main(String[] args) {
        Scribble scribble = new Scribble();
        scribble.setSize(500, 300);
        scribble.setVisible(true);
      // The scribble application relies on the ScribblePane2 component developed
      // earlier. This field holds the ScribblePane2 instance it uses.
      ScribblePane2 scribblePane;
       * This constructor creates the GUI for this application.
      public Scribble() {
        super("Scribble"); // Call superclass constructor and set window title
        // Handle window close requests
        this.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        // All content of a JFrame (except for the menubar) goes in the
        // Frame's internal "content pane", not in the frame itself.
        // The same is true for JDialog and similar top-level containers.
        Container contentPane = this.getContentPane();
        // Create the main scribble pane component,
        // a background color, and add it to the content pane
        scribblePane = new ScribblePane2();
        scribblePane.setBackground(Color.white);
        contentPane.add(scribblePane);
        // Create a menubar and add it to this window. Note that JFrame
        // handles menus specially and has a special method for adding them
        // outside of the content pane.
        JMenuBar menubar = new JMenuBar(); // Create a menubar
        this.setJMenuBar(menubar); // Display it in the JFrame
        // Create menus and add to the menubar
        JMenu filemenu = new JMenu("File");
        JMenu colormenu = new JMenu("Color");
        JMenu textmenu = new JMenu("Text");
        menubar.add(filemenu);
        menubar.add(colormenu);
        menubar.add(textmenu);
        // Create some Action objects for use in the menus and toolbars.
        // An Action combines a menu title and/or icon with an ActionListener.
        // These Action classes are defined as inner classes below.
        Action open = new OpenAction();
        Action save = new SaveAction();
        Action clear = new ClearAction();
        Action select = new SelectColorAction();
        Action text = new TextAction();
        // Populate the menus using Action objects
        filemenu.add(open);
        filemenu.add(save);
        filemenu.add(clear);
        colormenu.add(select);
        textmenu.add(text);
    private final static int//initialization
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,             
                     OVAL = 3,              
                     ROUNDRECT = 4,         
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOSI, heightOSI;   
      private int mouseX, mouseY;   // The location of the mouse.
          private int begnX, begnY;     // The previous location of the mouse.
          private int startngX, startngY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int shape;    // What type of figure is being drawn.  This is
                                 //    specified by the shapeChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the shape that is
                                    // being drawn.
          private void drawShape(Graphics g, int shape, int x1, int y1, int x2, int y2) {
               if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
      //This inner class defines the "open" action to open an image file
      class OpenAction extends AbstractAction {
        public OpenAction() {
          super("Open");
        public void actionPerformed(ActionEvent e) {
          scribblePane.open();
    //This inner class defines the "save" action to save as .jpg
      class SaveAction extends AbstractAction {
        public SaveAction() {
          super("Save As");
        public void actionPerformed(ActionEvent e) {
          scribblePane.save();
      /** This inner class defines the "clear" action that clears the scribble */
      class ClearAction extends AbstractAction {
        public ClearAction() {
          super("Clear"); // Specify the name of the action
        public void actionPerformed(ActionEvent e) {
          scribblePane.clear();
        //This inner class defines an Action that sets the current drawing color of
        //the ScribblePane2 component.
      class ColorAction extends AbstractAction {
        Color color;
        public ColorAction(Color color) {
        this.color = color;
        public void actionPerformed(ActionEvent e) {
          scribblePane.setColor(color); // Set current drawing color
       // This inner class defines an Action that uses JColorChooser to allow the
       // user to select a drawing color
      class SelectColorAction extends AbstractAction {
        public SelectColorAction() {
          super("Select Color...");
        public void actionPerformed(ActionEvent e) {
          Color color = JColorChooser.showDialog(Scribble.this,
              "Select Drawing Color", scribblePane.getColor());
          if (color != null)
            scribblePane.setColor(color);
      class TextAction extends AbstractAction {
        public TextAction() {
          super("Paste Text");
        public void actionPerformed(ActionEvent e) {
        scribblePane.text();
    // A simple JPanel subclass that uses event listeners to allow the user to
    // scribble with the mouse. Note that scribbles are not saved or redrawn.
    class ScribblePane2 extends JPanel {
      public ScribblePane2() {
        // Give the component a preferred size
        setPreferredSize(new Dimension(450, 200));
        // Register a mouse event handler defined as an inner class
        // Note the call to requestFocus(). This is required in order for
        // the component to receive key events.
        addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            moveto(e.getX(), e.getY()); // Move to click position
            requestFocus(); // Take keyboard focus
        // Register a mouse motion event handler defined as an inner class
        // By subclassing MouseMotionAdapter rather than implementing
        // MouseMotionListener, we only override the method we're interested
        // in and inherit default (empty) implementations of the other methods.
        addMouseMotionListener(new MouseMotionAdapter() {
          public void mouseDragged(MouseEvent e) {
            lineto(e.getX(), e.getY()); // Draw to mouse position
        // Add a keyboard event handler to clear the screen on key 'C'
        addKeyListener(new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_C)
              clear();
      /** These are the coordinates of the the previous mouse position */
      protected int last_x, last_y;
      /** Remember the specified point */
      public void moveto(int x, int y) {
        last_x = x;
        last_y = y;
      /** Draw from the last point to this point, then remember new point */
      public void lineto(int x, int y) {
        Graphics g = getGraphics(); // Get the object to draw with
        g.setColor(color); // Tell it what color to use
        g.drawLine(last_x, last_y, x, y); // Tell it what to draw
        moveto(x, y); // Save the current point
       * Clear the drawing area, using the component background color. This method
       * works by requesting that the component be redrawn. Since this component
       * does not have a paintComponent() method, nothing will be drawn. However,
       * other parts of the component, such as borders or sub-components will be
       * drawn correctly.
      public void open() { //Function to open file
        JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
        int status = fileChooser.showOpenDialog(null);
          if (status == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
      public void save() { //Function to save file [needs work]
        JFileChooser fileChooser = new JFileChooser(".");
          fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
          int status = fileChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION) {
              File selectedFile = fileChooser.getSelectedFile();
      public void clear() {
        repaint();
      /** This field holds the current drawing color property */
      Color color = Color.black;
      /** This is the property "setter" method for the color property */
      public void setColor(Color color) {
        this.color = color;
      /** This is the property "getter" method for the color property */
      public Color getColor() {
        return color;
      public void text() {
        String inputValue = JOptionPane.showInputDialog("Enter yee olde string...");
        System.out.println("String entered is:" + inputValue);
      //  g.drawString(inputValue, startngX, startngY);
      //  String text = text.getText();
      public void paintComponent(Graphics g) {
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && shape != CURVE) {
                g.setColor(dragColor);
                drawShape(g,shape,startngX,startngY,mouseX,mouseY);
          private void checkOSI() {
             if (OSI == null || widthOSI != getSize().width || heightOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOSI = getSize().width;
                heightOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOSI, heightOSI);
                OSG.dispose();
    }when i try and do this:
      public void text(Graphics g) {
        String inputValue = JOptionPane.showInputDialog("Enter yee olde string...");
        System.out.println("String entered is:" + inputValue);
        g.drawString(inputValue, startngX, startngY);It says i can't put Graphics g there, not sure why :|
    Any help would be great! Thanks :)

    ...alex wrote:
    -Kayaman- wrote:
    So you write the method to accept a Graphics object as a parameter, then you try to call it without passing a parameter.
    GEE WIZ, I WONDER WHAT COULD BE THE PROBLEM?wow... thanks... that really helps me considering i'm posting in the "New To Java" section.Don't mention it.
    >
    As for the OSI = null, this is part of a group assignment. All the code between the /////////////'s is from another group member, i haven't even looked at the code yet as i just pasted it in and don't need to worry about it until i can get it the program to compile with drawLine.Well, you can get mental brownie points by telling him that it doesn't free any memory to explicitly assign it to null, especially since you're assigning it again on the next line.
    There is almost never a need to explicitly set something to null like that.

  • Own definition of Icon for JMenuItem

    Every time I try to add ColorIcon to JMenuItem it eats name space. How can I separate name from icon?
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Toolkit;
    import javax.swing.AbstractAction;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    public class Test extends JFrame {
         public Test() {
              JMenuBar menu = new JMenuBar();
              JMenu mFile = new JMenu("File");
              menu.add(mFile);
              JMenu mColor = new JMenu("Color");
              mFile.add(mColor);
              mColor.add(new TakeAction(Color.RED, "This is red"));
              setJMenuBar(menu);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              setPreferredSize(new Dimension(screenSize.width/2, screenSize.height/2));
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         public static void main(String[] args) {
              new Test();
         public class TakeAction extends AbstractAction implements ActionListener{
              public TakeAction (Color color, String name) {
                   super(name);
                   putValue(SMALL_ICON, new ColorIcon(color));
              @Override
              public void actionPerformed(ActionEvent e) {
         public class ColorIcon implements Icon {
             private int width = 15;
             private int height = 15;
             private Color color;
             public ColorIcon(Color color) {
                  this.color = color;
              @Override
              public int getIconHeight() {
                   return 0;
              @Override
              public int getIconWidth() {
                   return 0;
              @Override
              public void paintIcon(Component c, Graphics g, int x, int y) {
                   Graphics2D g2d = (Graphics2D) g.create();
                      g2d.setColor(color);
                      g2d.fillOval(3, 3, width-3, height-3);
                          g2d.dispose();
    }Edited by: Giraphant on Dec 30, 2010 3:23 AM
    Edited by: Giraphant on Dec 30, 2010 3:24 AM

    private int width = 15;
    private int height = 15;
    @Override
    public int getIconHeight() {
      return 0;
    @Override
    public int getIconWidth() {
      return 0;
    }Does this make sense to you?

  • Help Plz! AWT to Swing Conversion

    Hey everyone, I'm new to java and trying to convert this AWT program to Swing, I got no errors, the menu shows but they dont work !! Could somebody please help me? thanks alot!
    Current Under-Construction Code: (no errors)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class zipaint extends JFrame implements ActionListener,      ItemListener,
    MouseListener, MouseMotionListener, WindowListener {
    static final int WIDTH = 800;     // Sketch pad width
    static final int HEIGHT = 600;     // Sketch pad height
    int upperLeftX, upperLeftY;     // Rectangle upper left corner coords.
    int width, height;          // Rectangle size
    int x1, y1, x2, y2, x3, y3, x4, y4; // Point coords.
    boolean fillFlag = false; //default filling option is empty
    boolean eraseFlag = false; //default rubber is off
    String drawColor = new String("black"); //default drawing colour is black
    String drawShape = new String("brush"); //default drawing option is brush
    Image background; //declear image for open option
    private FileDialog selectFile = new FileDialog( this,
    "Select background (.gif .jpg)",
    FileDialog.LOAD );
    // Help
    String helpText = "Draw allows you to sketch different plane shapes over a " +
    "predefined area.\n" + "A shape may be eother filled or in outline, " +
    "and in one of eight different colours.\n\n" + "The position of the " +
    "mouse on the screen is recorded in the bottom left-hand corner of the " +
    "drawing area. The choice of colour and shape are disoplayed also in the " +
    "left-habnd corner of the drawing area.\n\n" + "The size of a shape is " +
    "determined by the mouse being dragged to the final position and " +
    "released. The first click of the mouse will generate a reference dot on " +
    "the screen. This dot will disapear after the mouse button is released.\n\n" +
    "Both the square and the circle only use the distance measured along the " +
    "horizontal axis when determining the size of a shape.\n\n" + "Upon " +
    "selecting erase, press the mouse button, and move the mouse over the " +
    "area to be erased. releasing the mouse button will deactivate erasure.\n\n" +
    "To erase this text area choose clearpad from the TOOLS menu.\n\n";
    // Components
    JTextField color = new JTextField();
    JTextField shape = new JTextField();
    JTextField position = new JTextField();
    CheckboxGroup fillOutline = new CheckboxGroup();
    JTextArea info = new JTextArea(helpText,0,0/*,JTextArea.JSCROLLBARS_VERTICAL_ONLY*/);
    JFrame about = new JFrame("About Zi Paint Shop");
    // Menues
    String[] fileNames = {"Open","Save","Save as","Exit"};
    String[] colorNames = {"black","blue","cyan","gray","green","magenta","red","white","yellow"};
    String[] shapeNames = {"brush","line","square","rectangle","circle","ellipse"};
    String[] toolNames = {"erase","clearpad"};
    String[] helpNames = {"Help","about"};
    public zipaint(String heading) {
    super(heading);
    getContentPane().setBackground(Color.white);
    getContentPane().setLayout(null);
    /* Initialise components */
    initialiseTextFields();
    initializeMenuComponents();
    initializeRadioButtons();
    addWindowListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    /* Initialise Text Fields */
    private void initialiseTextFields() {
    // Add text field to show colour of figure
    color.setLocation(5,490);
    color.setSize(80,30);
    color.setBackground(Color.white);
    color.setText(drawColor);
    getContentPane().add(color);
    // Add text field to show shape of figure
    shape.setLocation(5,525);
    shape.setSize(80,30);
    shape.setBackground(Color.white);
    shape.setText(drawShape);
    getContentPane().add(shape);
    // Add text field to show position of mouse
    position.setLocation(5,560);
    position.setSize(80,30);
    position.setBackground(Color.white);
    getContentPane().add(position);
    // Set up text field for help
    info.setLocation(150,250);
    info.setSize(500,100);
    info.setBackground(Color.white);
    info.setEditable(false);
    private void initializeMenuComponents() {
    // Create menu bar
    JMenuBar bar = new JMenuBar();
    // Add colurs menu
    JMenu files = new JMenu("Files");
    for(int index=0;index < fileNames.length;index++)
    files.add(fileNames[index]);
    bar.add(files);
    files.addActionListener(this);
    // Add colurs menu
    JMenu colors = new JMenu("COLORS");
    for(int index=0;index < colorNames.length;index++)
    colors.add(colorNames[index]);
    bar.add(colors);
    colors.addActionListener(this);
    // Add shapes menu
    JMenu shapes = new JMenu("SHAPES");
    for(int index=0;index < shapeNames.length;index++)
    shapes.add(shapeNames[index]);
    bar.add(shapes);
    shapes.addActionListener(this);
    // Add tools menu
    JMenu tools = new JMenu("TOOLS");
    for(int index=0;index < toolNames.length;index++)
    tools.add(toolNames[index]);
    bar.add(tools);
    tools.addActionListener(this);
    // Add help menu
    JMenu help = new JMenu("HELP");
    for(int index=0;index < helpNames.length;index++)
    help.add(helpNames[index]);
    bar.add(help);
    help.addActionListener(this);
    // Set up menu bar
    setJMenuBar(bar);
    /* Initilalise Radio Buttons */
    private void initializeRadioButtons() {
    // Define checkbox
    Checkbox fill = new Checkbox("fill",fillOutline,false);
    Checkbox outline = new Checkbox("outline",fillOutline,true);
    // Fill buttom
    fill.setLocation(5,455);
    fill.setSize(80,30);
    getContentPane().add(fill);
    fill.addItemListener(this);
    // Outline button
    outline.setLocation(5,420);
    outline.setSize(80,30);
    getContentPane().add(outline);
    outline.addItemListener(this);
    /* Action performed. Detects which item has been selected from a menu */
    public void actionPerformed(ActionEvent e) {
    Graphics g = getGraphics();
    String source = e.getActionCommand();
    // Identify chosen colour if any
    for (int index=0;index < colorNames.length;index++) {
    if (source.equals(colorNames[index])) {
    drawColor = colorNames[index];
    color.setText(drawColor);
    return;
    // Identify chosen shape if any
    for (int index=0;index < shapeNames.length;index++) {
    if (source.equals(shapeNames[index])) {
    drawShape = shapeNames[index];
    shape.setText(drawShape);
    return;
    // Identify chosen tools if any
    if (source.equals("erase")) {
    eraseFlag= true;
    return;
    else {
    if (source.equals("clearpad")) {
    remove(info);
    g.clearRect(0,0,800,600);
    return;
    if (source.equals("Open")) {
    selectFile.setVisible( true );
    if( selectFile.getFile() != null )
    String fileLocation = selectFile.getDirectory() + selectFile.getFile();
    background = Toolkit.getDefaultToolkit().getImage(fileLocation);
    paint(getGraphics());
    if (source.equals("Exit")) {
    System.exit( 0 );
    // Identify chosen help
    if (source.equals("Help")) {
    getContentPane().add(info);
    return;
    if (source.equals("about")) {
    displayAboutWindow(about);
    return;
    public void paint(Graphics g)
    super.paint(g);
    if(background != null)
    Graphics gc = getGraphics();
    gc.drawImage( background, 0, 0, this.getWidth(), this.getHeight(), this);
    /* Dispaly About Window: Shows iformation aboutb Draw programme in
    separate window */
    private void displayAboutWindow(JFrame about) {
    about.setLocation(300,300);
    about.setSize(350,160);
    about.setBackground(Color.cyan);
    about.setFont(new Font("Serif",Font.ITALIC,14));
    about.setLayout(new FlowLayout(FlowLayout.LEFT));
    about.add(new Label("Author: Zi Feng Yao"));
    about.add(new Label("Title: Zi Paint Shop"));
    about.add(new Label("Version: 1.0"));
    about.setVisible(true);
    about.addWindowListener(this);
    // ----------------------- ITEM LISTENERS -------------------
    /* Item state changed: detect radio button presses. */
    public void itemStateChanged(ItemEvent event) {
    if (event.getItem() == "fill") fillFlag=true;
    else if (event.getItem() == "outline") fillFlag=false;
    // ---------------------- MOUSE LISTENERS -------------------
    /* Blank mouse listener methods */
    public void mouseClicked(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    /* Mouse pressed: Get start coordinates */
    public void mousePressed(MouseEvent event) {
    // Cannot draw if erase flag switched on.
    if (eraseFlag) return;
    // Else set parameters to 0 and proceed
    upperLeftX=0;
    upperLeftY=0;
    width=0;
    height=0;
    x1=event.getX();
    y1=event.getY();
    x3=event.getX();
    y3=event.getY();
    Graphics g = getGraphics();
    displayMouseCoordinates(x1,y1);
    public void mouseReleased(MouseEvent event) {
    Graphics g = getGraphics();
    // Get and display mouse coordinates
    x2=event.getX();
    y2=event.getY();
    displayMouseCoordinates(x2,y2);
    // If erase flag set to true reset to false
    if (eraseFlag) {
    eraseFlag = false;
    return;
    // Else draw shape
    selectColor(g);
    if (drawShape.equals("line")) g.drawLine(x1,y1,x2,y2);
    else if (drawShape.equals("brush"));
    else drawClosedShape(drawShape,g);
    /* Display Mouse Coordinates */
    private void displayMouseCoordinates(int x, int y) {
    position.setText("[" + String.valueOf(x) + "," + String.valueOf(y) + "]");
    /* Select colour */
    private void selectColor(Graphics g) {
    for (int index=0;index < colorNames.length;index++) {
    if (drawColor.equals(colorNames[index])) {
    switch(index) {
    case 0: g.setColor(Color.black);break;
    case 1: g.setColor(Color.blue);break;
    case 2: g.setColor(Color.cyan);break;
    case 3: g.setColor(Color.gray);break;
    case 4: g.setColor(Color.green);break;
    case 5: g.setColor(Color.magenta);break;
    case 6: g.setColor(Color.red);break;
    case 7: g.setColor(Color.white);break;
    default: g.setColor(Color.yellow);
    /* Draw closed shape */
    private void drawClosedShape(String shape,Graphics g) {
    // Calculate correct parameters for shape
    upperLeftX = Math.min(x1,x2);
    upperLeftY = Math.min(y1,y2);
    width = Math.abs(x1-x2);
    height = Math.abs(y1-y2);
    // Draw appropriate shape
    if (shape.equals("square")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,width);
    else g.drawRect(upperLeftX,upperLeftY,width,width);
    else {
    if (shape.equals("rectangle")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,height);
    else g.drawRect(upperLeftX,upperLeftY,width,height);
    else {
    if (shape.equals("circle")) {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,width);
    else g.drawOval(upperLeftX,upperLeftY,width,width);
    else {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,height);
    else g.drawOval(upperLeftX,upperLeftY,width,height);
    /* Mouse moved */
    public void mouseMoved(MouseEvent event) {
    displayMouseCoordinates(event.getX(),event.getY());
    /* Mouse dragged */
    public void mouseDragged(MouseEvent event) {
    Graphics g = getGraphics();
    x2=event.getX();
    y2=event.getY();
    x4=event.getX();
    y4=event.getY();
    displayMouseCoordinates(x1,y1);
    if (eraseFlag) g.clearRect(x2,y2,10,10);
    else {
    selectColor(g);
    if(drawShape.equals("brush")) g.drawLine(x3,y3,x4,y4);
    x3 = x4;
    y3 = y4;
    // ---------------------- WINDOW LISTENERS -------------------
    /* Blank methods for window listener */
    public void windowClosed(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    public void windowOpened(WindowEvent event) {}
    /* Window Closing */
    public void windowClosing(WindowEvent event) {
    if (event.getWindow() == about) {
    about.dispose();
    return;
    else System.exit(0);
    Code End
    Thanks again!
    class ziapp {
    /* Main method */
    public static void main(String[] args) {
    zipaint screen = new zipaint("Zi Paint Shop");
    screen.setSize(zipaint.WIDTH,zipaint.HEIGHT);
    screen.setVisible(true);

    First of all use the [url http://forum.java.sun.com/features.jsp#Formatting]Formatting Tags when posting code to the forum. I'm sure you don't code with every line left justified so we don't want to read unformatted code either.
    Hey everyone, I'm new to java and trying to convert this AWT program to SwingInstead of converting the whole program, start with something small, understand how it works and then convert a different part of the program. You can start by reading this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus.
    From a quick glance of your code it looks like you are not adding an ActionListener to your JMenuItems. You are adding them to the JMenu.
    Other observations:
    1) Don't mix AWT with Swing components. You are still using CheckBox
    2) Don't override paint(). When using Swing you should override paintComponent();
    3) Use LayoutManagers. Using a null layout does not allow for easy maintenance of the gui. Right now you are using 800 x 600 as your screen size. Most people are probably using at least 1024 x 768 screen sizes. When using LayoutManagers you would suggest component sizes by using setPreferredSize(), not setSize().

  • MouseMotionAdapter problem

    Greetings,
    This is for a school project, and i would like to get some help tracking down my last error. It is a compile error in the following line of code:
    panel.addMouseMotionListener(new Move());
    The error that i get states that the MouseMotionListener cannot be applied to Polygons.Move
    If i comment out the line the program works just fine. the purpose of the Move class is to allow the user to reposition the drawn polygon. Any suggestions as why this is not allowing me to add the listener?
    For the ease of assistance, i have included the full program code below.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Polygon.*;
    public class Polygons extends JFrame implements
    ActionListener
    { //starts Polygon Class (main class of the program)
    /* variable delcarations */
    Point start;
    boolean newPolygon;
    JPanel panel;
    JComboBox comboBox;
    Color color;
    ColoredPolygon show[];
    int size;
    boolean moving;
    boolean overflow;
    ColoredPolygon movePolygon;
    /* end variable declarations */
    Polygons()
    { //starts Polygon constructor
    /* variable delcarations */
    newPolygon = true;
    color = Color.blue;
    show = new ColoredPolygon[5];
    size = 0;
    moving = false;
    overflow = false;
    /* end variable declarations */
    setTitle("Polygon Project");
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    }); // ends anon class for window closing (ends program)
    /* Creation of the Combo box*/
    Object [] items = {"Red", "Blue", "Green", "Yellow"};
    comboBox = new JComboBox(items);
    //getContentPane().add(comboBox, BorderLayout.SOUTH);
    comboBox.addActionListener(new ActionListener()
    { //start anon class
    public void actionPerformed(ActionEvent e)
    { //start action Performed
    /* Created in an anon class due to the creation of the
    combo box only needing to be done once /
    JComboBox box = (JComboBox)e.getSource();
    String comboString =
    (String)box.getSelectedItem();
    if(comboString.equals("Red"))
    color = Color.red;
    else if(comboString.equals("Green"))
    color = Color.green;
    else if(comboString.equals("Blue"))
    color = Color.blue;
    else if(comboString.equals("Yellow"))
    color = Color.yellow;
    } //end actionPerformed
    } //end anon class
    ); //end function call for anon class
    /* End Creation of the Combobox */
    /* Panel information */
    JPanel jp = new JPanel();
    jp.setBackground(Color.black);
    jp.add(comboBox);
    getContentPane().add(jp, BorderLayout.SOUTH);
    panel = new Draw();
    panel.setBackground(Color.white);
    panel.addMouseListener(new Mouse());
    /* error is below this comment */
    panel.addMouseMotionListener(new Move());/* error is above this comment */
    getContentPane().add(panel, BorderLayout.CENTER);
    /* End Panel information */
    /* Creation of the MenuBar */
    JMenuBar menu = new JMenuBar();
    JMenu menuColor = new JMenu("Color");
    JMenuItem makeRed = new JMenuItem("Red");
    menuColor.add(makeRed);
    makeRed.addActionListener(this);
    JMenuItem makeBlue = new JMenuItem("Blue");
    menuColor.add(makeBlue);
    makeBlue.addActionListener(this);
    JMenuItem makeGreen = new JMenuItem("Green");
    menuColor.add(makeGreen);
    makeGreen.addActionListener(this);
    JMenuItem makeYellow = new JMenuItem("Yellow");
    menuColor.add(makeYellow);
    makeYellow.addActionListener(this);
    menu.add(menuColor);
    setJMenuBar(menu);
    /* End Creation of the MenuBar */
    } //ends Polygon constructor
    public void actionPerformed(ActionEvent ae)
    { //starts actionPerformed
    JMenuItem menuSource = (JMenuItem)ae.getSource();
    String menuString = menuSource.getText();
    if(menuString.equals("Yellow"))
    color = Color.yellow;
    comboBox.setSelectedItem("Yellow");
    else if(menuString.equals("Red"))
    color = Color.red;
    comboBox.setSelectedItem("Red");
    else if(menuString.equals("Blue"))
    color = Color.blue;
    comboBox.setSelectedItem("Blue");
    else if(menuString.equals("Green"))
    color = Color.green;
    comboBox.setSelectedItem("Green");
    } //ends actionPerformed
    class ColoredPolygon extends Polygon
    { //starts ColoredPolygon
    private Color color;
    Color getColor()
    return color;
    ColoredPolygon()
    color = color.black;
    ColoredPolygon(Color color1)
    color = color1;
    } //ends ColoredPolygon
    class Mouse extends MouseAdapter
    class Mouse extends MouseAdapter //caputers mouse
    clicks and conversts the loction of the
    // click to "x, y" coordinates in the variables
    m, n.
    { //start Mouse class
    private ColoredPolygon polys;
    public void mousePressed(MouseEvent me)
    { //starts MousePressed
    int m = me.getX();
    int n = me.getY();
    if(newPolygon)
    start = new Point(m, n);
    if(me.isShiftDown())
    Point point = new Point(m, n);
    for (int i = size - 1; i >= 0; i--)
    if(!show.contains(point))
    //continue;
    movePolygon = show;
    moving = true;
    //break;
    else
    polys = new ColoredPolygon(color);
    polys.addPoint(m, n);
    newPolygon = false;
    else
    polys.addPoint(m, n);
    Graphics g = panel.getGraphics();
    g.setColor(color);
    g.drawLine(start.x, start.y, m, n);
    start.move(m, n);
    if(me.getClickCount() == 2)
    /*if a double click is performed, then che1ck for
    overflow and a new polygon is
    drawn if overflow is false */
    Graphics g1 = panel.getGraphics();
    g1.setColor(color);
    g1.fillPolygon(polys);
    if (size >= show.length)
    overflow = true;
    panel.repaint();
    else
    show[size] = polys;
    size++;
    newPolygon = true;
    Mouse()
    } //ends mousePressed
    public void mouseReleased(MouseEvent me)
    if(me.isShiftDown())
    moving = false;
    } //ends Mouse class
    class Move extends MouseAdapter
    { //starts Move class
    public void mouseDragged(MouseEvent me)
    if(moving && me.isShiftDown())
    /* checks for Mouse draggin and the shift key being
    depressed to move the polygon */
    int m = me.getX();
    int n = me.getY();
    movePolygon.translate(m - start.x, n - start.y);
    panel.repaint();
    start.move(m, n);
    Move()
    } //ends Move class
    class Draw extends JPanel // does the actual drawing
    //on the screen
    { //start Draw class
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    if(overflow)
    Font font = new Font("Serif", 0, 48);
    g.setFont(font);
    g.drawString("Overflow", 100, 100);
    else
    for (int x = 0; x < size; x++)
    { //for loop start
    ColoredPolygon cpoly = show[x];
    g.setColor(cpoly.getColor());
    g.fillPolygon(cpoly);
    } //for loop end
    Draw()
    } //ends Draw class
    public static void main(String args[])
    Polygons project = new Polygons();
    project.setSize(600, 500);
    project.setVisible(true);
    } // ends Polygon Class (main class of the program)

    addMouseMotionListener() must be passed an instance of
    MouseMotionListener. Can you make the Move class
    implement the MouseMotionListener interface?That's it. Move extends MouseAdapter which implements MouseListener, the addMouseMotionListener method expects a MouseMotionListener, in which case you would need to extend MouseMotionAdapter. whew, that's alot of mouses....err mice.

  • Color of item selected in JMenu

    Hi All,
    I want to change the default highlight color whenever i select any item in JMenu.
    By default whenever i select any item in JMenu, it gets highlighted in blue color .i want to override this behavior to set my own highlight color
    Pls advise

    Thanks for your reply but it is not solving my problem
    I am able to change the foreground with this line
    UIManager.put("MenuItem.selectionForeground", Color.RED);
    but background still remains 'BLUE' after putting
    UIManager.put("MenuItem.selectionBackground", Color.RED);
    Pls advise,
    Note:-I am using Mac Machine

Maybe you are looking for

  • Ipad not recognized by windows neither iTunes after error in the iOS5 upgrade

    The iOS5 upgrade was stopped due to an error. Since then the iPad is not being recognized by windows neither iTunes. I've re-installed iTunes, the file usbaapl.sys is at windows\system32\drivers and Common Files\Apple\Mobile Device Support\Drivers fo

  • Adding a Lightroom Gallery on an iweb site- that does NOT use .mac

    I've been checking all past posts but only find references to adding a Lightroom Gallery in iweb if the user has mobile me/uses a .mac account. Someone else has asked this same question on July 20 and received no answers so far. Both of us using iweb

  • Row and Colum in CR

    Hi all experts, 1st table Doc No               Remark 1                        Test Unit 2                        Reject 2nd table ExpCode     ExpName 1     Acc 2     Hr 3rd table DocNo                   ExpCode               Amount 1                

  • Barcode reader with SAP

    Hi Gurus, i want to use barcode truck  but i dont any idea how to use in SAP Can anyone make a suggestion ?

  • Multiple plugins in one project

    Hi, I want to have two plugins in one (visual studio) project (on windows). I know the pipl should have two blocks with two different entry points, but what is the entry point? And how can I know what filter should I run? Thanks, Inbal