7 Replies - 404 Views - Last Post: 12 October 2013 - 12:13 PM Rate Topic: -----

#1 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Getting Circle Class to draw in MainWindow when Selected.

Posted 05 October 2013 - 02:43 PM

I've been looking at many Java tutorials trying to implement a GUI using Swing and my code seems a bit chaotic atm. I'm relatively new to Java and I'm instructed to use Swing to in my current project and its been overwhelming. I've gotten a window, a text input I even managed to get shapes to draw all in my MainWindow class but I'm trying to get a shape (circle) to draw when the user choses Draw Circle from the Drop Down menu. Once I choose Draw circle I get all the exceptions you see below. What is the most direct and effective way to get it to draw?

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Mainwindow.addShape(Mainwindow.java:192)
at Mainwindow.actionPerformed(Mainwindow.java:158)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.window.dispatchEventImpl(window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Here is my code thus far.

Shape class
import javax.swing.*;
import java.awt.*;
public abstract class Shape extends JFrame{

    public int xValue, yValue;
    public int top,left;
    public Color color = Color.white;
    
    /*public Shape(int xV, int yV){
          xV=xValue;
          yV=yValue;
     }*/

    public 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.xValue = width;
         this.yValue = 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;
      }

      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+xValue && y >= top && y < top+yValue)
            return true;
         else
            return false;
      }

      abstract void draw(Graphics g);
            // Draw the shape in the graphics context g.
            // This must be overriden in any concrete subclass
}


Circle Class
import java.awt.*;
public class Circle extends Shape{

    private int radius;

   
    void draw(Graphics g) {
         g.setColor(color);
         g.fillOval(left,top,xValue,yValue);
         //g.setColor(Color.black);
         g.drawOval(left,top,xValue,yValue);
      }
    /*public Circle(int xValue, int yValue, int radius){

        super(xValue,yValue);
        this.radius = radius;
    }*/
}


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


public class MainWindow extends JFrame implements ActionListener
{
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    private JPanel redPanel;
    private JPanel whitePanel;
    private JPanel bluePanel;

    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";

    Color currentColor = Color.red;
    Shape[] shapes = new Shape[10];

    public MainWindow( )
    {
        super("Menu Demonstration");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        //setLayout(new GridLayout(1, 3));
        //setLayout(new BoxLayout( , BoxLayout.Y_AXIS));
        setBackground(Color.white);
        //creats canvas
        Canvas canvas = new Canvas();
        canvas.setSize(120,120);
        //canvas.setBackground(Color.white);

        JPanel bottom = new JPanel();   // a Panel to hold the control buttons
       // bottom.setLayout(new GridLayout(1,4,3,3));
       // bottom.add(rectButton);
       // bottom.add(ovalButton);
       // bottom.add(roundRectButton);
       // bottom.add(colorChoice);

        //getContentPane().setLayout(new BorderLayout(3,3));
        //getContentPane().add("Center",canvas);              // add canvas and controls to the applet
        //getContentPane().add("South",bottom);


        String[] colorBoarder = { "Red", "Green", "Blue", "Yellow", "Black", "White" };



        redPanel = new JPanel( );
        redPanel.setBackground(Color.LIGHT_GRAY);
        add(redPanel);

        whitePanel = new JPanel( );
        //whitePanel.setBackground(Color.LIGHT_GRAY);
        //add(whitePanel);

        bluePanel = new JPanel( );
        //bluePanel.setBackground(Color.LIGHT_GRAY);
        //add(bluePanel);

//Adds menu and thier selections
        JMenu shapeColor = new JMenu("Shape Color");

        JMenuItem redChoice = new JMenuItem("Fill Red");
        redChoice.addActionListener(this);
        shapeColor.add(redChoice);

        JMenuItem whiteChoice = new JMenuItem("Fill White");
        whiteChoice.addActionListener(this);
        shapeColor.add(whiteChoice);

        JMenuItem blueChoice = new JMenuItem("Fill Blue");
        blueChoice.addActionListener(this);
        shapeColor.add(blueChoice);

        JMenu shapeType = new JMenu("Shape Type");

        JMenuItem circle = new JMenuItem("Draw Circle");
        circle.addActionListener(this);
        shapeType.add(circle);

        JMenuItem rectangle  = new JMenuItem("Draw Rectangle");
        rectangle.addActionListener(this);
        shapeType.add(rectangle);

        JMenuItem rightTriangle  = new JMenuItem("Draw Right Triangle");
        rightTriangle.addActionListener(this);
        shapeType.add(rightTriangle);

        JMenuBar bar = new JMenuBar( );
        bar.add(shapeColor);
        bar.add(shapeType);
        setJMenuBar(bar);
        
        textField = new JTextField(10);
        textField.addActionListener(this);


        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        //textField.setPreferredSize( new Dimension( 100, 24 ) );

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
        //Combo Box
        JComboBox petList = new JComboBox(colorBoarder);
        petList.setSelectedIndex(4);
        petList.addActionListener(this);

        add(petList, BorderLayout.PAGE_START);
       // setBorder(BorderFactory.createEmptyBorder(20,20,20,20));


    }

   public void actionPerformed(ActionEvent e)
    {
        String buttonString = e.getActionCommand( );

        if (buttonString.equals("Fill Red"))
             redPanel.setBackground(Color.RED);
        else if (buttonString.equals("Fill White"))
            whitePanel.setBackground(Color.WHITE);
        else if (buttonString.equals("Fill Blue"))
            bluePanel.setBackground(Color.BLUE);
        else if (buttonString.equals("Draw Circle"))
            addShape(new Circle());// to add the shape when chosen
        else
            System.out.println("Unexpected error.");


        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        textArea.setCaretPosition(textArea.getDocument().getLength());


    }

      public void paintComponent(Graphics g) {
           // In the paint method, all the shapes in ArrayList are
           // copied onto the canvas.

         g.setColor(getBackground());
         g.fillRect(0,0,getSize().width,getSize().height);
         int top = shapes.length;
         for (int i = 0; i < top; i++) {
            Shape s = (Shape)shapes[i];
            s.draw(g);
         }
    }
    void addShape(Shape shape) {
             // Add the shape to the canvas, and set its size/position and color.
             // The shape is added at the top-left corner, with size 80-by-50.
             // Then redraw the canvas to show the newly added shape.
         shape.setColor(currentColor);
         shape.reshape(3,3,80,50);
         shapes[4].add(shape);
         repaint();

    }
     /*public void paint(Graphics g){
          
        g.drawOval(400, 300, 60, 60); //FOR CIRCLE

        //g.setColor(colorFill);
        g.fillRect(10, 500, 100, 200);
        //g.setColor(colorBorder);
        g.drawRect(10, 500, 100, 200); // FOR SQUARE

        //g.drawPolyline(, , 100, 200); // FOR RECT
     }*/
}


Is This A Good Question/Topic? 0
  • +

Replies To: Getting Circle Class to draw in MainWindow when Selected.

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 05 October 2013 - 05:53 PM

Your stack trace says:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Mainwindow.addShape(Mainwindow.java:192)


so you have a null pointer exception in class MainWindow in method addShape() at line 192

Weird the MainWindow class you posted has only 189 lines and the addShape() method ends at line 175
so there is a discrepancy between the program you ran and the one you posted
Was This Post Helpful? 1
  • +
  • -

#3 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 05 October 2013 - 09:31 PM

View Postpbl, on 05 October 2013 - 05:53 PM, said:

Your stack trace says:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Mainwindow.addShape(Mainwindow.java:192)


so you have a null pointer exception in class MainWindow in method addShape() at line 192

Weird the MainWindow class you posted has only 189 lines and the addShape() method ends at line 175
so there is a discrepancy between the program you ran and the one you posted


Could it be that I went from the example using an Arraylist to using an array (can't use arraylist).

I managed to get rid of some excess code and I'm not sure if I have my constructors set up correctly for the job.

MainWindow
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author George
 */
/*import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class MainWindow extends JFrame implements ActionListener
{
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    private JPanel redPanel;
    private JPanel whitePanel;
    private JPanel bluePanel;

    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";

    Color currentColor = Color.red;
    Shape[] shapes = new Shape[10];

    public MainWindow( )
    {
        super("Menu Demonstration");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        //setLayout(new GridLayout(1, 3));
        //setLayout(new BoxLayout( , BoxLayout.Y_AXIS));
        setBackground(Color.white);
        //creates canvas
        Canvas canvas = new Canvas();
        canvas.setSize(120,120);
        //canvas.setBackground(Color.white);

        JPanel bottom = new JPanel();   // a Panel to hold the control buttons
       // bottom.setLayout(new GridLayout(1,4,3,3));
       // bottom.add(rectButton);
       // bottom.add(ovalButton);
       // bottom.add(roundRectButton);
       // bottom.add(colorChoice);

        //getContentPane().setLayout(new BorderLayout(3,3));
        //getContentPane().add("Center",canvas);              // add canvas and controls to the applet
        //getContentPane().add("South",bottom);


        String[] colorBoarder = { "Red", "Green", "Blue", "Yellow", "Black", "White" };



        redPanel = new JPanel( );
        redPanel.setBackground(Color.LIGHT_GRAY);
        add(redPanel);

        whitePanel = new JPanel( );
        //whitePanel.setBackground(Color.LIGHT_GRAY);
        //add(whitePanel);

        bluePanel = new JPanel( );
        //bluePanel.setBackground(Color.LIGHT_GRAY);
        //add(bluePanel);

//Adds menu and thier selections
        JMenu shapeColor = new JMenu("Shape Color");

        JMenuItem redChoice = new JMenuItem("Fill Red");
        redChoice.addActionListener(this);
        shapeColor.add(redChoice);

        JMenuItem whiteChoice = new JMenuItem("Fill White");
        whiteChoice.addActionListener(this);
        shapeColor.add(whiteChoice);

        JMenuItem blueChoice = new JMenuItem("Fill Blue");
        blueChoice.addActionListener(this);
        shapeColor.add(blueChoice);

        JMenu shapeType = new JMenu("Shape Type");

        JMenuItem circle = new JMenuItem("Draw Circle");
        circle.addActionListener(this);
        shapeType.add(circle);

        JMenuItem rectangle  = new JMenuItem("Draw Rectangle");
        rectangle.addActionListener(this);
        shapeType.add(rectangle);

        JMenuItem rightTriangle  = new JMenuItem("Draw Right Triangle");
        rightTriangle.addActionListener(this);
        shapeType.add(rightTriangle);

        JMenuBar bar = new JMenuBar( );
        bar.add(shapeColor);
        bar.add(shapeType);
        setJMenuBar(bar);
        
        textField = new JTextField(10);
        textField.addActionListener(this);


        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        //textField.setPreferredSize( new Dimension( 100, 24 ) );

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
        //Combo Box
        JComboBox colorBoarderList = new JComboBox(colorBoarder);
        colorBoarderList.setSelectedIndex(4);
        colorBoarderList.addActionListener(this);

        add(colorBoarderList, BorderLayout.PAGE_START);
       // setBorder(BorderFactory.createEmptyBorder(20,20,20,20));


    }

   public void actionPerformed(ActionEvent e)
    {
        String buttonString = e.getActionCommand( );

        if (buttonString.equals("Fill Red"))
             redPanel.setBackground(Color.RED);
        else if (buttonString.equals("Fill White"))
            whitePanel.setBackground(Color.WHITE);
        else if (buttonString.equals("Fill Blue"))
            bluePanel.setBackground(Color.BLUE);
        else if (buttonString.equals("Draw Circle"))
            addShape(new Circle());// to add the shape when chosen
        else
            System.out.println("Unexpected error.");


        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        textArea.setCaretPosition(textArea.getDocument().getLength());


    }

      public void paintComponent(Graphics g) {
           // In the paint method, all the shapes in ArrayList are
           // copied onto the canvas.

         g.setColor(getBackground());
         g.fillRect(0,0,getSize().width,getSize().height);
         int top = shapes.length;
         for (int i = 0; i < top; i++) {
            Shape s = (Shape)shapes[i];
            s.draw(g);
         }
    }
    void addShape(Shape shape) {
             // Add the shape to the canvas, and set its size/position and color.
             // The shape is added at the top-left corner, with size 80-by-50.
             // Then redraw the canvas to show the newly added shape.
         shape.setColor(currentColor);
         shape.reshape(3,3,80,50);
         shapes[4].add(shape);
         repaint();

    }
     /*public void paint(Graphics g){
          
        g.drawOval(400, 300, 60, 60); //FOR CIRCLE

        //g.setColor(colorFill);
        g.fillRect(10, 500, 100, 200);
        //g.setColor(colorBorder);
        g.drawRect(10, 500, 100, 200); // FOR SQUARE

        //g.drawPolyline(, , 100, 200); // FOR RECT
     }*/
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author George
 */
import java.awt.*;
public class Circle extends Shape{

    private int radius;

    public Circle(){

        super();
        radius = 0;
    }
    void draw(Graphics g) {
         g.setColor(color);
         g.fillOval(left,top,xValue,yValue);
         //g.setColor(Color.black);
         g.drawOval(left,top,xValue,yValue);
      }

}






/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author George
 */
import javax.swing.*;
import java.awt.*;
public abstract class Shape extends JFrame{

    public int xValue, yValue;
    public int top,left;
    public Color color = Color.white;
    
   public Shape(){
          xValue=0;
          yValue=0;
          top=0;
          left=0;
     }

    public 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.xValue = width;
         this.yValue = height;
      }

      void setColor(Color color) {
             // Set the color of this shape
         this.color = color;
      }


      abstract void draw(Graphics g);
            // Draw the shape in the graphics context g.
            // This must be overriden in any concrete subclass
}



as for the null pointer, I'm not sure what to do to get shapes[4].add(shape) to work properly. That was orginally an array list from this example.

http://math.hws.edu/.../ShapeDraw.java

but I was trying to do the same thing with just an array. Did I miss something from the example?
Was This Post Helpful? 0
  • +
  • -

#4 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 05 October 2013 - 10:05 PM

Yea so I switched it back to an arraylist and it doesn't result in errors but it still won't draw on the screen. So now I have to figure out how to make the arraylist part an array and get it to draw.

I'll probably focus on getting it to draw and then figure out how to switch the array list to a regular painful array.
Was This Post Helpful? 0
  • +
  • -

#5 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1428
  • View blog
  • Posts: 3,171
  • Joined: 05-April 11

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 05 October 2013 - 11:25 PM

Why does your Shape class extend JFrame? There is no need for your Shape class to extend any of the JComponents
This line just doesn't make sense
shapes[4].add(shape);


You take the shape at index 4... always.. and try and add another shape to it? Why not add it as a new shape to the array. That way you won't get a nullpointer on the line

JFrame does not have a method with the signature void paintComponent(Graphics g)
Add an @Override annotation to let the compiler warn you
@Override
public void paintComponent(Graphics g) {


Instead of your JTextArea, you should use a JPanel and paint onto that. A JPanel has a paintComponent method that you can override :)
Was This Post Helpful? 0
  • +
  • -

#6 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 11 October 2013 - 08:28 PM

So this is where i am at right now. I know you said Shape shouldn't extend anything but I think I need JPanel to do my frame.add(s). I managed to make it draw with my currently excluded paintComponent but now that I am not using paintComponent and I am trying to do it via Circle class extending shape I still can't get it to draw :(


import java.awt.*;
import javax.swing.*;
public abstract class Shape extends JPanel{

    public int xValue, yValue,area,perimeter;
    public Color color = Color.white;
    
   public Shape(){
          xValue=0;
          yValue=0;
          area=0;
          perimeter=0;

     }


      void setColor(Color color) {
             // Set the color of this shape
         this.color = color;
      }


      abstract void draw(Graphics g);
            // Draw the shape in the graphics context g.
            // This must be overriden in any concrete subclass

}


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

public class MainWindow //implements ActionListener
{
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    JFrame frame;
    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";
   // Shape[] shapeArray = new Shape[1];

    //JPanel jp = new JPanel();

    Color currentColor = Color.red;

    public MainWindow( ){

        frame = new JFrame("Menu Demonstration");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setLayout(new FlowLayout(-2,10,10));
       // frame.setLayout(new GridLayout(1, 3));
        //setLayout(new BoxLayout( , BoxLayout.Y_AXIS));
        //setBackground(Color.LIGHT_GRAY);;

        String[] colorBoarder = { "Red", "Green", "Blue", "Yellow", "Black", "White" };

//Adds menu and thier selections
//Select Fill
        JMenu shapeColor = new JMenu("Shape Color");
        

        JMenuItem redChoice = new JMenuItem("Fill Red");
        //redChoice.addActionListener(this);
        shapeColor.add(redChoice);

        JMenuItem whiteChoice = new JMenuItem("Fill White");
        //whiteChoice.addActionListener(this);
        shapeColor.add(whiteChoice);
        whiteChoice.setOpaque(true);

        JMenuItem blueChoice = new JMenuItem("Fill Blue");
        //blueChoice.addActionListener(this);
        shapeColor.add(blueChoice);
//Draw Shapes
        JMenu shapeType = new JMenu("Shape Type");

        JMenuItem circle = new JMenuItem("Draw Circle");
                circle.addActionListener(new ActionListener() {
            Integer index;
            int x,y,r;

            @Override
            public void actionPerformed(ActionEvent e) {
                JPanel pn = new JPanel();
                JTextField xInput = new JTextField(5);
                JTextField yInput = new JTextField(5);
                JTextField rInput = new JTextField(5);
                pn.add(xInput);
                pn.add(yInput);
                pn.add(rInput);
                int result = JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
                if (result == JOptionPane.OK_OPTION) {
                   //don't forget to throw/catch exception here
                    x = Integer.parseInt(xInput.getText());
                    index = Integer.parseInt(xInput.getText());
                    y = Integer.parseInt(yInput.getText());
                    System.out.println(yInput.getText());
                    r = Integer.parseInt(rInput.getText());
                }
                toDraw(index.toString(),x,y,r,null);
            }
        });
        shapeType.add(circle);

        JMenuItem rectangle  = new JMenuItem("Draw Rectangle");
        //rectangle.addActionListener(this);
        shapeType.add(rectangle);

        JMenuItem rightTriangle  = new JMenuItem("Draw Right Triangle");
        //rightTriangle.addActionListener(this);
        shapeType.add(rightTriangle);

        JMenuBar bar = new JMenuBar( );
        bar.add(shapeColor);
        bar.add(shapeType);
        frame.setJMenuBar(bar);

    }
   
    void toDraw(String p, int x, int y,int r,Graphics g) {
        //shapeArray[1] = new Circle(p,x,y,r);
        //frame.add(shapeArray[1]);
        //Circle d = new Circle(p,x,y,r);
        Shape s = new Circle(p,x,y,r);
        
        frame.add(s);
        s.draw(g);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.revalidate();
        frame.repaint();

    }

   /*public void actionPerformed(ActionEvent e)
    {
        String buttonString = e.getActionCommand( );

        //if (buttonString.equals("Fill Red"))
             //redPanel.setBackground(Color.RED);
        //else if (buttonString.equals("Fill Blue"))
            //bluePanel.setBackground(Color.BLUE);
        //if(buttonString.equals("Draw Circle"))
            //addShape(new Circle());// to add the shape when chosen
        //else
            //System.out.println("Unexpected error.");


        //String text = textField.getText();
        //textArea.append(text + newline);
        //textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        //textArea.setCaretPosition(textArea.getDocument().getLength());


    }*/
    
   /*class Draw extends JPanel {

    String inp;
    int xValue;
    int yValue;
    int radius;

    public Draw(String gn, int x, int y,int r) {
        inp = gn;
        xValue = x;
        yValue = y;
        radius = r;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        //Graphics2D g2 = (Graphics2D) g;

        drawCircle(g, xValue, yValue, radius);
        //g2.drawString(inp, x + (x / 2), x + (x / 2));
    }
    public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
 
        cg.drawOval(xCenter-r, yCenter-r, 2*r, 2*r);
 
    }//end drawCircle

   }*/
}


import java.awt.*;
public class Circle extends Shape{

    public int radius;

    public Circle(String gn, int x, int y,int r) {
        //inp = gn;
        super.xValue = x;
        super.yValue = y;
        this.radius = r;
    }
//@Override
    public void draw(Graphics g) {
        //super.paintComponent(g);

        drawCircle(g, xValue, yValue, radius);
        //g2.drawString(inp, x + (x / 2), x + (x / 2));
    }
    public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {

        cg.drawOval(xCenter-r, yCenter-r, 2*r, 2*r);

    }//end drawCircle

}

Was This Post Helpful? 0
  • +
  • -

#7 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 11 October 2013 - 09:07 PM

Actually I got it to draw by calling the object.draw() in a JPanel with paintComponent;

But my inserted x and y are not working. Looking into it.
Was This Post Helpful? 0
  • +
  • -

#8 nonlin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-October 13

Re: Getting Circle Class to draw in MainWindow when Selected.

Posted 12 October 2013 - 12:13 PM

Now I'm using actionPerofmred override for every button that I want to perform an action. However, it seems doing it this way, it is calling actionPerformed statements from other buttons as well.

Is this normal behavior? What is the best way around it?

For instance, I call Fill Yellow which causes colorChoice to be color.yellow but in doing so it uses toDraw method and draws over the shape even though I only call toDraw() in my drawCircle.Actionlistener.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1