Question

In: Computer Science

Simple Painting GUI Apps You are just developing the GUI app. Your mission in this exercise...

Simple Painting GUI Apps


You are just developing the GUI app.

Your mission in this exercise is to implement a very simple Java painting application. Rapid Prototyping

The JFrame is an example that can support the following functions:

* Draw curves, specified by a mouse drag.

* Draw filled rectangles or ovals, specified by a mouse drag (don't worry about dynamically drawing the shape during the drag - just draw the final shape indicated).

* Shape selection (line, rectangle or oval) selected by a combo box OR menu.

* Color selection using radio buttons OR menu.

* Line thickness using a combo box OR menu.

* A CLEAR button.

Some other tips to get you started:

* Put import java.awt.*; and import java.awt.event.*; at the top of your java source.

* To find the mouse coordinates of a mouse event (e.g., a click), use the int getX() and int getY() methods on the MouseEvent object.

* Remember that getGraphics() returns a Graphics object that represents one set of drawing parameter settings for the JFrame (there is no global Graphics object!).

* Heres a code snippet to draw a blue dot at X=10, Y=100 on the JFrame:

Graphics G=getGraphics();

G.setColor(Color.BLUE);

G.drawRect(10,100,1,1);

* Here's the mouse dragged handler we wrote in class for a (lame) painting function on the JFrame:

private void myMouseDragged(java.awt.event.MouseEvent evt) {

int x=evt.getX();

int y=evt.getY();

java.awt.Graphics G=getGraphics();

G.drawRect(x, y, 1, 1);

}

* And another snippet to find out which item was selected from a combo box:

public void actionPerformed(ActionEvent e) {

JComboBox cb=(JComboBox)e.getSource();

String itemName=(String)cb.getSelectedItem();

}

Solutions

Expert Solution

//----------------- RapidPrototyping.java ----------------

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//Class that paints according to the user wish.
public class RapidPrototyping extends JFrame implements MouseListener,ItemListener,ActionListener,MouseMotionListener {
  
   //panel to hold color,shapes and thickness components
   JPanel panel;
   //shapes combobox
   JComboBox shapes;
   //color radio buttons
   JRadioButton red, green, blue;
   //thickness combobox
   JComboBox thicknesses;
   //clear button.
   JButton clear;
   JPanel center;
  
   /*values of each selection*/
   Color color;
   int thickness;
   String shape;

   //start and end positions of mouse start and end positions of drag.
   int startX, startY;
   int endX, endY;
   boolean startSet;

   final String shapesList[] = { "RECTANGLE", "OVAL", "LINE" };

   final String thicknessesList[] = { "3", "6", "9", "12", "15" };

   RapidPrototyping() {
       //initialize values.
       setSize(600, 400);
       setLayout(new BorderLayout());

       panel = new JPanel(new FlowLayout());

       JLabel shapeLabel = new JLabel("Shape :");
       shapes = new JComboBox(shapesList);

       JLabel colorLabel = new JLabel("Color :");
       red = new JRadioButton("Red");
       green = new JRadioButton("Green");
       blue = new JRadioButton("Blue");
       ButtonGroup g = new ButtonGroup();
       g.add(red);
       g.add(blue);
       g.add(green);

       JLabel thicknessLabel = new JLabel("thickness :");
       thicknesses = new JComboBox(thicknessesList);

       clear = new JButton("Clear");
      
       center = new JPanel();
      
       //add elements to panel
       panel.add(shapeLabel);
       panel.add(shapes);
  
  
  
       panel.add(colorLabel);
       panel.add(red);
       panel.add(green);
       panel.add(blue);

       panel.add(thicknessLabel);
       panel.add(thicknesses);

       panel.add(clear);
       add(panel, BorderLayout.NORTH);
       add(center,BorderLayout.CENTER);
      
       /*Listeners*/
       addMouseListener(this);
       //adding mouse motionlistener is good but there is a drawback in that.
       //code will draw a shape without dragging.
       //it takes the previous point location and the curred dragged position.
       red.addItemListener(this);
       blue.addItemListener(this);
       green.addItemListener(this);
      
       shapes.addActionListener(this);
      
       clear.addActionListener(this);
      
       thicknesses.addActionListener(this);

       /* Default Values Setting */
       color = Color.RED;
       red.setSelected(true);
      
       thickness = 3;
       shape = "RECTANGLE";
       startSet = false;
      
      
   }
   //action listener
   public void actionPerformed(ActionEvent ae)
   {
       //set shape value on shapes selection changed.
       if(ae.getSource() == shapes)
       {
           shape = ""+shapes.getItemAt(shapes.getSelectedIndex());
       }
       //repaint the frame if clear button clicked.
       else if(ae.getSource() == clear)
       {
           repaint();
       }
       //change the thickness value.
       else if(ae.getSource() == thicknesses)
       {
           try
           {
               thickness = Integer.parseInt(""+thicknesses.getItemAt(thicknesses.getSelectedIndex()));
           }
           catch(Exception e)
           {
               thickness = 3;
           }
       }
   }
   //set color value according to the selection in color selectin of radio buttons.
   public void itemStateChanged(ItemEvent ie)
   {
       if(ie.getSource() == red)
       {
           color = Color.RED;
       }
       else if(ie.getSource() == blue)
       {
           color = Color.BLUE;
       }
       else if(ie.getSource() == green)
       {
           color = Color.GREEN;
       }
   }
   //mouse pressed is the first step in clicking mouse.
   //when a button is presesd this will invoke
   public void mousePressed(MouseEvent e)
   {
       //if the start point is not set
       if(startSet == false)
       {
           //then set start point as current mouse location
           startX = e.getX();
           startY = e.getY();
           startSet = true;
          
       }
   }

   // this function is invoked when the mouse is released
   public void mouseReleased(MouseEvent e)
   {
       //when mouse click is released .set end point.
       if(startSet)
       {
           endX = e.getX();
           endY = e.getY();
           startSet = false;
           //call drawShape() to draw current shape.
           drawShape();
          
       }
   }
   //when mouse is dragged in right to left or bottom to up
   //we have to change the start and end points for drawing rectangel and oval
   //because they take start position and width,height(not end position like line).
   public void checkAndSwap()
   {
       //swap value of x and y
       if(startX > endX)
       {
           int temp = startX;
           startX = endX;
           endX = temp;
       }
       if(startY > endY)
       {
           int temp = startY;
           startY = endY;
           endY = temp;
       }
   }
   //method drawShape() that draws current selected properties of paint
   //and draws them .
   public void drawShape()
   {
      
       //Graphics2D will be more useful than Graphics class.
       Graphics2D g2 = (Graphics2D) getGraphics();
       g2.setStroke(new BasicStroke(thickness));
       g2.setColor(color);
       //cal width and height
       int width = Math.abs(endX-startX);
       int height = Math.abs(endY-startY);
       System.out.println("\nThickness: "+thickness);
      
       //if shape is rectangle draw shape
       if(shape.equals(("RECTANGLE")))
       {
           //check and swap call only for rectangle and oval
           checkAndSwap();
           System.out.printf("Drawing %s : at -> %d %d with width and height %d,%d end point: %d %d\n",shape,startX,startY,width,height,endX,endY);
           //fillRect with following fields.
           g2.fillRect(startX,startY,width,height);
          
       }
       else if(shape.equals("OVAL"))
       {
           checkAndSwap();
           System.out.printf("Drawing %s : at -> %d %d with width and height %d,%d end point: %d %d\n",shape,startX,startY,width,height,endX,endY);
           g2.fillOval(startX,startY,width,height);
       }
       else
       {
           System.out.printf("Drawing %s : at -> %d %d end point: %d %d\n",shape,startX,startY,width,height,endX,endY);
           g2.drawLine(startX, startY, endX, endY);
       }
              
   }
   // this function is invoked when the mouse exits the component
   public void mouseExited(MouseEvent e)
   {

   }

   // this function is invoked when the mouse enters the component
   public void mouseEntered(MouseEvent e)
   {

   }

   // this function is invoked when the mouse is pressed or released
   public void mouseClicked(MouseEvent e)
   {
      
         
   }
   //MouseMotionListener methods are not used.
   public void mouseDragged(MouseEvent e)
   {
   }
   public void mouseMoved(MouseEvent e)
   {
   }
   //create jframe object and set its properties.
   public static void main(String[] args) {
       RapidPrototyping frame = new RapidPrototyping();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setVisible(true);
       frame.setResizable(false);
       frame.setTitle("Rapid Prototyping");
   }
}
//Sorry for the curve drawing. code will print all the shapes except.Curve drawing is big concept i //literally dont know about it.

//if you have any doubts please comment.

//output

//and drawing shapes will also be drawn at components shapes,radio buttons.it will remove when //clear button is pressed.


Related Solutions

using Java Your mission in this exercise is to implement a very simple Java painting application....
using Java Your mission in this exercise is to implement a very simple Java painting application. Rapid Prototyping The JFrame is an example that can support the following functions: 1. Draw curves, specified by a mouse drag. 2. Draw filled rectangles or ovals, specified by a mouse drag (don't worry about dynamically drawing the shape during the drag - just draw the final shape indicated). 3. Shape selection (line, rectangle or oval) selected by a combo box OR menu. 4....
Your company makes apps for the smartphone/tablet market. Create an idea for a new app, and...
Your company makes apps for the smartphone/tablet market. Create an idea for a new app, and discuss how this new app would be introduced to your market. Choose an app for one of these markets: 1-business; 2-health; 3-education; 4-sports; or 5-shopping.
Using C# Windows App Form Create a simple calculator using +,-,*,/ Please show code GUI Code...
Using C# Windows App Form Create a simple calculator using +,-,*,/ Please show code GUI Code for calculator menus radio button input text boxes
Assignment 4 - Writing Exercise - Developing a mobile phone app On-the-Go Software, a start-up company...
Assignment 4 - Writing Exercise - Developing a mobile phone app On-the-Go Software, a start-up company in your community, would like to develop a new mobile phone app that will be profitable. As part of the company’s preliminary planning, the CEO, Etta Hawkins, has hired you to research the most popular apps for iPhones and other mobile devices and to analyze why you believe these apps are successful. As you research, identify who is buying these apps and hypothesize why....
Your company is developing two web apps, one for voice calls over the internet (VoIP), and...
Your company is developing two web apps, one for voice calls over the internet (VoIP), and another for streaming music. Between TCP and UDP, explain which protocol you would use for each app and why.
Your family's house painting business has decided to try this "EOQ thing" you just learned in...
Your family's house painting business has decided to try this "EOQ thing" you just learned in SCMS 3510. So you open the financials and note the following information: Three-year average paint consumption: 2090 gallons per year You use a small warehouse to hold your equipment and paint. From your cost accounting class, you estimate that your holding cost per gallon of paint is $1.65 per year. Buying the materials needed requires more time than you thought. The part-time person whose...
Marketing Plan exercise 1. What is your mission? Are you looking for part-time or temporary experience...
Marketing Plan exercise 1. What is your mission? Are you looking for part-time or temporary experience to enhance your résumé, a career stepping-stone, or a full-time, long-term career choice? (This mission will help you set the stage for the rest of your plan.) 2. What are your strengths and weaknesses? Make an honest self-issues often come up during job interviews. What about opportunity marketplace? Who are your competitors? Do you have a competitive advantage? List any special leadership skills, international...
1. You have just been appointed to evaluate some of the social programs. Your mission, which...
1. You have just been appointed to evaluate some of the social programs. Your mission, which you have no choice but to accept, is to reform De- mogrants and Employment Insurance (EI) because they are presently not a§ordable and rife with ine¢ ciencies. One fundamental issue that underlies the reform of demogrants and Employment Insurance (EI) is the conáicting objectives of providing adequate income protection on one hand and providing a more e¢ cient incentive structure on the other hand....
You are developing a simple linear regression analysis model. The simple correlation coefficient between y and...
You are developing a simple linear regression analysis model. The simple correlation coefficient between y and x is -0.72. What do you know must be true about b1. The least squares estimator of B1? Why? In a multiple linear regression analysis with k = 3. From the t test associated with B1, you conclude that B1 = 0. When you do the f test will you reject or fail to reject the null hypothesis? Why? In a simple bilinear regression...
Take Five Systems, a new start-up, is developing a new iPhone application (“app”) and provides you...
Take Five Systems, a new start-up, is developing a new iPhone application (“app”) and provides you with the following assumptions: Development and testing of the new app will take four months. Month five is the first month of revenue generation. Initial monthly app sales of 5,000 downloads at a price of $2.99 Unit sales will grow at 15% per month for months six through twelve and then will be flat thereafter The app will become obsolete and will need to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT