Question

In: Computer Science

Java 2D Drawing Application. The application will contain the following elements: a) an Undo button to...

Java 2D Drawing Application.

The application will contain the following elements:

a) an Undo button to undo the last shape drawn.

b) a Clear button to clear all shapes from the drawing.

c) a combo box for selecting the shape to draw, a line, oval, or rectangle.

d) a checkbox which specifies if the shape should be filled or unfilled.

e) a checkbox to specify whether to paint using a gradient.

f) two JButtons that each show a JColorChooser dialog to allow the user to choose the first and second color in the gradient.

g) a text field for entering the Stroke width.

h) a text field for entering the Stroke dash length.

I) a checkbox for specifying whether to draw a dashed or solid line.

j) a JPanel on which the shapes are drawn.

k) a status bar JLabel at the bottom of the frame that displays the current location of the mouse on the draw panel.

If the user selects to draw with a gradient, set the Paint on the shape to be a gradient of the two colors chosen by the user. If the user does not chose to draw with a gradient, then Paint with a solid color of the 1st Color. The following code can build a gradient paint object:

Paint paint = new GradientPaint(0, 0, color1, 50, 50, color2, true);

To set the stroke for a line to be drawn, you can use the following code:

if (dashCheckBox.isSelected())

{

stroke = new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashLength, 0);

} else

{

stroke = new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);

}

Where the first stroke line build a dashed line and dashLength is a one element float array with the dash length in the first element. The second stroke line build an undashed line with the line width specified from the GUI.

Note: When dragging the mouse to build a new shape, the shape should be drawn as the mouse is dragged.

A template project has been provided for you in Canvas in Java2DDrawingApplicationTemplate.zip. This project contains a MyShapes hierarchy that is a complete shape hierarchy for drawing a line, rectangle or oval. You must use this MyShapes hierarchy. A template for the Drawing Application Frame is also provided along with a template for the DrawPanel inner class. You do not need to use these templates if you so choose.

In the paintComponent(Graphics g) method of the DrawPanel, to loop through and draw each shape created by the user, you will loop through an ArrayList of MyShapes, that you built, and call the draw(Graphics2D g2d) method for each shape. The draw method is already implemented in the MyShapes hierarchy.

Note: You do not need to build an event handler for each component in the top two lines of the frame. You only need to create event handlers for the buttons. You can get the values out of all the other components in the top two lines, when the user presses the mouse button on the DrawPanel. At that time, you have all the information you need to build a new Myshapes object.

*Note: Please Do Not Use the One from Github. I have worked on the code a little bit I’m unable to get the code to draw objects and get coordinates of the mouse when moving in the drawPanel. In the comments below, I have attached different classes that I have created for the code. In addition to this file, I have six more classes so a total of 7 files and the names are 1. MyBoundedShapes
2. MyLine
3. MyOval
4. MyRectangle
5. MyShapes
6. Java2dDrawingApplication
7. DrawingApplicationFrame (current code)*


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package a5;

/**
*
* @author dhruvi
*/
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class DrawingApplicationFrame extends JFrame {
static ArrayList<String> itemsDrawn;
  
// Create the panels for the top of the application. One panel for each
// line and one to contain both of those panels.
private final JPanel topPanel = new JPanel();
private final JPanel first_line_panel = new JPanel();
private final JPanel second_line_panel = new JPanel();
private DrawPanel drawPanel = new DrawPanel();
private final JPanel statusPanel = new JPanel();
  
// create the widgets for the firstLine Panel.
private final JButton undo = new JButton("Undo");
private final JButton clear = new JButton("Clear");
private final JLabel shape = new JLabel("Shapes:");
public JComboBox shapes = new JComboBox<>(new String[] {"Oval", "Rectangle", "Line"});
private final JCheckBox filled = new JCheckBox("Filled");

//create the widgets for the secondLine Panel.
private final JCheckBox gradient = new JCheckBox("Use Gradient");
private final JButton foreground = new JButton("1st Color");
private final JButton background = new JButton("2nd Color");
private final JCheckBox dashed = new JCheckBox("Dashed");
private final JLabel width = new JLabel("Line Width:");
private final JTextField lineWidth = new JTextField("10");
private final JLabel length = new JLabel("Dash Length:");
private final JTextField dashLength = new JTextField("15");
static JLabel mousePos = new JLabel("( , )");

// Variables for drawPanel.
  
//public MouseHandler mouseHandler = new MouseHandler();
private int mouseX = 0;
private int mouseY = 0;
  
// add status label
  
// Constructor for DrawingApplicationFrame
public DrawingApplicationFrame() {
  
// add topPanel to North, drawPanel to Center, and statusLabel to South
topPanel.setLayout(new BorderLayout());
first_line_panel.setLayout(new FlowLayout());
second_line_panel.setLayout(new FlowLayout());
drawPanel.setLayout(new BorderLayout());
statusPanel.setLayout(new BorderLayout());
  
// add widgets to panels
// firstLine widgets
first_line_panel.add(undo);
first_line_panel.add(clear);
first_line_panel.add(shape);
first_line_panel.add(shapes);
first_line_panel.add(filled);
  
// secondLine widgets
second_line_panel.add(gradient);
second_line_panel.add(foreground);
second_line_panel.add(background);
second_line_panel.add(width);
second_line_panel.add(lineWidth);
second_line_panel.add(length);
second_line_panel.add(dashLength);
second_line_panel.add(dashed);
  
// add top panel of two panels
topPanel.add(first_line_panel, "North");
topPanel.add(second_line_panel, "South");
  
drawPanel.setVisible(true);
drawPanel.setBackground(Color.WHITE);
  
statusPanel.add(mousePos, BorderLayout.WEST);
statusPanel.setVisible(true);

super.add(topPanel, "North");
super.add(drawPanel, "Center");
super.add(statusPanel, "South");
  
//add listeners and event handlers
// Create event handlers, if needed
clear.addActionListener((ActionEvent arg0) -> {
itemsDrawn = new ArrayList<>();
drawPanel.repaint();
});
  
undo.addActionListener((ActionEvent arg0) -> {
if (itemsDrawn.size() != 0) {
itemsDrawn.remove(itemsDrawn.size() - 1);
drawPanel.repaint();
}
});
  
foreground.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
foreground.setBackground(JColorChooser.showDialog(null, "Pick your color", Color.BLACK));
}
});
  
background.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
background.setBackground(JColorChooser.showDialog(null, "Pick your color", Color.BLACK));
}
});
}

// Create a private inner class for the DrawPanel.   
private class DrawPanel extends JPanel {
public DrawPanel(){
itemsDrawn = new ArrayList<>();
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
  
//loop through and draw each shape in the shapes arraylist
for (MyShapes Shape : itemsDrawn) {
Shape.paint(this, g2d);
}
}
}
  
private class MouseHandler extends MouseAdapter implements MouseMotionListener {
  
public void mousePressed(MouseEvent event) {
Paint paint;
repaint();
}

public void mouseReleased(MouseEvent event) {
repaint();
}

@Override
public void mouseDragged(MouseEvent event) {
shapeObject.setEndPoint(event.getPoint());
repaint();
statusPanel.setText("(" + event.getX() + "," + event.getY() + ")");
}

@Override
public void mouseMoved(MouseEvent event) {
String position = "(" + event.getPoint().x + "," + event.getPoint().y + ")";
mousePos.setText(position);
}
}
}
}

Solutions

Expert Solution

Here is the solution. Please do upvote thank you.

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.GridLayout;

import java.awt.Label;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import java.util.ArrayList;
import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JPanel;
public class MyPanel extends JPanel implements MouseListener,

MouseMotionListener {
static ArrayList<String> itemsDrawn;

static String shape, color;
public static void main(String[] args) {

JFrame frame = new JFrame("Java 2D Drawing");
frame.setSize(500, 500);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BorderLayout borderLayout = new BorderLayout();

frame.setLayout(borderLayout);
final JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 4, 0, 0));
  

JButton clear = new JButton("Clear");

panel.add(clear);

JButton undo = new JButton("Undo");

panel.add(undo);

String[] itemTypes = { "Oval", "Rectangle", "Line" };

JComboBox<String> shapeChooser = new JComboBox<>(itemTypes);

panel.add(shapeChooser);

shape = "Oval";

String[] colors = { "Red", "Green", "Blue", "Black" };

JComboBox<String> colorChooser = new JComboBox<>(colors);

panel.add(colorChooser);

color = "Red";
frame.add(panel,BorderLayout.PAGE_START);
final MyPanel myPanel = new MyPanel();

frame.add(myPanel,BorderLayout.CENTER);
shapeChooser.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

JComboBox<String> cb = (JComboBox<String>) e.getSource();

shape = (String) cb.getSelectedItem();

}

});
colorChooser.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

JComboBox<String> cb = (JComboBox<String>) e.getSource();

color = (String) cb.getSelectedItem();

}

});
clear.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent arg0) {

// TODO Auto-generated method stub

itemsDrawn = new ArrayList<>();

myPanel.repaint();

}

});

undo.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent arg0) {

// TODO Auto-generated method stub

if (itemsDrawn.size() != 0) {

itemsDrawn.remove(itemsDrawn.size() - 1);

myPanel.repaint();

}

}

});
frame.setVisible(true);

}
/**

*

*/

private static final long serialVersionUID = 5509155261502497671L;
Point start, end;
public MyPanel() {

start = end = null;

addMouseListener(this);

addMouseMotionListener(this);

itemsDrawn = new ArrayList<>();

}
@Override

public void paint(Graphics g) {

// TODO Auto-generated method stub

super.paint(g);

int counter;

String[] temp;
for (counter = 0; counter < itemsDrawn.size(); counter++) {

temp = itemsDrawn.get(counter).split(" ");

if (temp[1].equals("Red")) {

g.setColor(Color.RED);

} else if (temp[1].equals("Green")) {

g.setColor(Color.GREEN);

} else if (temp[1].equals("Blue")) {

g.setColor(Color.BLUE);

} else if (temp[1].equals("Black")) {

g.setColor(Color.BLACK);

}
if (temp[0].equals("Oval")) {
g.fillOval(

Integer.parseInt(temp[2]) > Integer.parseInt(temp[4]) ? Integer

.parseInt(temp[4]) : Integer.parseInt(temp[2]),

Integer.parseInt(temp[3]) > Integer.parseInt(temp[5]) ? Integer

.parseInt(temp[5]) : Integer.parseInt(temp[3]),

Math.abs(Integer.parseInt(temp[4])

- Integer.parseInt(temp[2])), Math.abs(Integer

.parseInt(temp[5]) - Integer.parseInt(temp[3])));

} else if (temp[0].equals("Rectangle")) {

g.fillRect(

Integer.parseInt(temp[2]) > Integer.parseInt(temp[4]) ? Integer

.parseInt(temp[4]) : Integer.parseInt(temp[2]),

Integer.parseInt(temp[3]) > Integer.parseInt(temp[5]) ? Integer

.parseInt(temp[5]) : Integer.parseInt(temp[3]),

Math.abs(Integer.parseInt(temp[4])

- Integer.parseInt(temp[2])), Math.abs(Integer

.parseInt(temp[5]) - Integer.parseInt(temp[3])));

} else if (temp[0].equals("Line")) {

g.drawLine(Integer.parseInt(temp[2]),

Integer.parseInt(temp[3]), Integer.parseInt(temp[4]),

Integer.parseInt(temp[5]));

}

}

if (start != null && end != null) {

if (color.equals("Red")) {

g.setColor(Color.RED);

} else if (color.equals("Green")) {

g.setColor(Color.GREEN);

} else if (color.equals("Blue")) {

g.setColor(Color.BLUE);

} else if (color.equals("Black")) {

g.setColor(Color.BLACK);

}
if (shape.equals("Oval")) {

g.fillOval(start.x > end.x ? end.x : start.x,

start.y > end.y ? end.y : start.y,

Math.abs(end.x - start.x), Math.abs(end.y - start.y));

} else if (shape.equals("Rectangle")) {

g.fillRect(start.x > end.x ? end.x : start.x,

start.y > end.y ? end.y : start.y,

Math.abs(end.x - start.x), Math.abs(end.y - start.y));

} else if (shape.equals("Line")) {

g.drawLine(start.x, start.y, end.x, end.y);

}

}

}
@Override

public void mouseDragged(MouseEvent arg0) {

// TODO Auto-generated method stub

end = arg0.getPoint();

repaint();

}
@Override

public void mouseMoved(MouseEvent arg0) {

// TODO Auto-generated method stub
}
@Override

public void mouseClicked(MouseEvent arg0) {

// TODO Auto-generated method stub
}
@Override

public void mouseEntered(MouseEvent arg0) {

// TODO Auto-generated method stub
}
@Override

public void mouseExited(MouseEvent arg0) {

// TODO Auto-generated method stub
}
@Override

public void mousePressed(MouseEvent arg0) {

// TODO Auto-generated method stub

start = arg0.getPoint();

}
@Override

public void mouseReleased(MouseEvent arg0) {

// TODO Auto-generated method stub
if (start != null && end != null) {

itemsDrawn.add(shape + " " + color + " " + start.x + " " + start.y

+ " " + end.x + " " + end.y);
}

start = null;

end = null;

}
}


Related Solutions

Using any existing 2D or 3D graphics library ( Java 2D, Java 3D, draw a scene...
Using any existing 2D or 3D graphics library ( Java 2D, Java 3D, draw a scene within one of the following categories: Satire or humor Promote a cause You are free to create whatever you choose but it must conform to the following guidelines.   Show evidence of at least four colors. Have a textual composition on the finished product. Imagery or images Scene composition of at least six (6) elements One of the following 1) Shadows or Glows. May be...
Please write in JAVA 1. Given the following array-based ADT list called colorList whose elements contain...
Please write in JAVA 1. Given the following array-based ADT list called colorList whose elements contain strings             red, orange, yellow, blue, indigo, violet write the statement to insert the String element “pink” to the end of the list. Assume the front of the list is on the left. 2. Outline the basic steps to remove a node from the beginning of a list. Completed answers will be given an immediate upvote :)
what is the difference between 2d and 3d drawing of the dipole equipotential contours?
what is the difference between 2d and 3d drawing of the dipole equipotential contours?
Modify the following 'MessageBoxes' application so it uses a single action listener for each button. This...
Modify the following 'MessageBoxes' application so it uses a single action listener for each button. This will require you to separate the single action listener logic into multiple listeners, one for each button. Then modify the code to provide additional options to two or more buttons. /* * The source code for this assignment started with * a sample from "Thinking in Java" 3rd ed. page 825 * by Bruce Eckel. I have finished adding the rest of the action...
Use Java GUI create following: Task 1: A basic UI with a button and a TextField,...
Use Java GUI create following: Task 1: A basic UI with a button and a TextField, when you press the button, set the button text to the current text field contents. Task 2: set the text field text to the mouse coordinates when that same button is pushed.
Create a JavaFX program in java that does the following items: Display a drawing area of...
Create a JavaFX program in java that does the following items: Display a drawing area of dimension 500 x 400, with a black background. Provides a radio button group to allow the user to select one of the following three colors: red, green, and blue. Upon startup, the red radio button should be selected. Each time the user clicks in the drawing area, a circle of size 10 of the color selected by the radio button group in item 2...
1/ Certain style properties (in CSS) are passed down from elements to the elements they contain...
1/ Certain style properties (in CSS) are passed down from elements to the elements they contain (their descendents). Inheritance Ancestors Parents Descendents 2/ A characteristic of the element, such as size, color, thickness, and so on. Style rule Property Selector rule Value 3/ The part of a style rule that identifies the element or elements to be affected. Value Declaration Selector Property 4/ How the document is delivered to the user, whether rendered on a computer or mobile device screen,...
This is in Java 1. Create an application called registrar that has the following classes: a....
This is in Java 1. Create an application called registrar that has the following classes: a. A student class that minimally stores the following data fields for a student:  Name  Student id number  Number of credits  Total grade points earned             And this class should also be provides the following methods:  A constructor that initializes the name and id fields  A method that returns the student name field  A method that returns the student...
In Java Which of the following is true? a.ArrayLists are constructed of nodes that include elements...
In Java Which of the following is true? a.ArrayLists are constructed of nodes that include elements and references to other elements b.LinkedLists are constructed of nodes that include elements and references to other elements c.ArrayLists are, by definition, lists of arrays d.LinkedLists are, be definition, lists of links Which of the following statements is correct in most cases? a.Accessing an element in an array by index is less expensive than accessing an element by index in a LinkedList b.Accessing an...
[jAVA] Assume the following array is defined and initialized (it will already contain numbers before your...
[jAVA] Assume the following array is defined and initialized (it will already contain numbers before your code runs): public static void main( String [ ] args ) { int [ ] numbers = . . . ; // An array of integers 1) Provide code that will print the entire contents of numbers in reverse order (from the end to the beginning) 2) Provide code that will print true if the numbers are in strictly ascending order (that is, if...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT