Question

In: Computer Science

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. Color selection using radio buttons OR menu.

5. Line thickness using a combo box OR menu.

6. A CLEAR button.

some tips are:-

>> 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



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

class paintGUI extends JComponent {

// Image in which we're going to draw
        private Image image;
// Graphics2D object ==> used to draw on
        private Graphics2D g2;
// Mouse coordinates
        private int currentX, currentY, oldX, oldY;

        public paintGUI() {
                setDoubleBuffered(false);
                addMouseListener(new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                                // save coord x,y when mouse is pressed
                                oldX = e.getX();
                                oldY = e.getY();
                                System.out.println("Mouse pressed");
                        }
                });

                addMouseMotionListener(new MouseMotionAdapter() {
                        public void mouseDragged(MouseEvent e) {
                                System.out.println("Mouse dragged");
                                
                                // coord x,y when drag mouse
                                currentX = e.getX();
                                currentY = e.getY();
                        }
                });
        }

        protected void paintComponent(Graphics g) {
                if (image == null) {
                        // image to draw null ==> we create
                        image = createImage(getSize().width, getSize().height);
                        g2 = (Graphics2D) image.getGraphics();

                        // clear draw area
                        clear();
                }

                g.drawImage(image, 0, 0, null);
                repaint();
        }

        // now we create exposed methods
        public void clear() {
                g2.clearRect(0, 0, getSize().width, getSize().height);
                repaint();
        }

        public void thin() {
                g2.setStroke(new BasicStroke(3));
        }

        public void thick() {
                g2.setStroke(new BasicStroke(10));
        }

        public void red() {
                // apply red color on g2 context
                g2.setPaint(Color.red);
        }

        public void black() {
                g2.setPaint(Color.black);
        }

        public void magenta() {
                g2.setPaint(Color.magenta);
        }

        public void drawLine() {
                System.out.println("Drawing line");
                g2.drawLine(oldX, oldY, currentX, currentY);
                repaint();
        }

        public void drawRectangle() {
                System.out.println("Drawing rectangle");
                g2.drawRect(oldX, oldY, Math.abs(currentX - oldX), Math.abs(currentY - oldY));
                g2.fillRect(oldX, oldY, Math.abs(currentX - oldX), Math.abs(currentY - oldY));
                repaint();
        }

}

public class GUIPaint {

        JButton clearBtn, blackBtn, redBtn, magentaBtn, filledRectangleBtn, lineBtn, thinBtn, thickBtn;
        paintGUI paintGUI;
        ActionListener actionListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                        if (e.getSource() == clearBtn) {
                                paintGUI.clear();
                        } else if (e.getSource() == thinBtn) {
                                paintGUI.thin();
                        } else if (e.getSource() == thickBtn) {
                                paintGUI.thick();
                        } else if (e.getSource() == blackBtn) {
                                paintGUI.black();
                        } else if (e.getSource() == redBtn) {
                                paintGUI.red();
                        } else if (e.getSource() == magentaBtn) {
                                paintGUI.magenta();
                        } else if (e.getSource() == filledRectangleBtn) {
                                paintGUI.drawRectangle();
                        } else if (e.getSource() == lineBtn) {
                                paintGUI.drawLine();
                        }
                }
        };

        public static void main(String[] args) {
                new GUIPaint().show();
        }

        public void show() {
                // create main frame
                JFrame frame = new JFrame("Swing Paint");
                Container content = frame.getContentPane();
                // set layout on content pane
                content.setLayout(new BorderLayout());
                // create draw area
                paintGUI = new paintGUI();

                // add to content pane
                content.add(paintGUI, BorderLayout.CENTER);

                // create controls to apply colors and call clear feature
                JPanel controls = new JPanel();

                clearBtn = new JButton("Clear");
                clearBtn.addActionListener(actionListener);
                blackBtn = new JButton("Black");
                blackBtn.addActionListener(actionListener);
                redBtn = new JButton("Red");
                redBtn.addActionListener(actionListener);
                magentaBtn = new JButton("Magenta");
                magentaBtn.addActionListener(actionListener);

                lineBtn = new JButton("Line");
                lineBtn.addActionListener(actionListener);
                filledRectangleBtn = new JButton("Filled Rectangle");
                filledRectangleBtn.addActionListener(actionListener);

                thickBtn = new JButton("Thick Line");
                thickBtn.addActionListener(actionListener);
                thinBtn = new JButton("Thin Line");
                thinBtn.addActionListener(actionListener);

                controls.add(lineBtn);
                controls.add(filledRectangleBtn);
                controls.add(thinBtn);
                controls.add(thickBtn);
                controls.add(blackBtn);
                controls.add(redBtn);
                controls.add(magentaBtn);
                controls.add(clearBtn);

                // add to content pane
                content.add(controls, BorderLayout.NORTH);

                frame.setSize(800, 800);
                // can close frame
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                // show the swing paint result
                frame.setVisible(true);

        }

}
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

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...
USING JAVA and NOTTT using BufferedReader or BufferedWriter Write an application that implements a simple text...
USING JAVA and NOTTT using BufferedReader or BufferedWriter Write an application that implements a simple text editor. Use a text field and a button to get the file. Read the entire file as characters and display it in a TextArea. The user will then be able to make changes in the text area. Use a Save button to get the contents of the text area and write that over the text in the original file. Hint: Read each line from...
Java - Design and implement an application that creates a histogram that allows you to visually...
Java - Design and implement an application that creates a histogram that allows you to visually inspect the frequency distribution of a set of values. The program should read in an arbitrary number of integers that are in the range 1 to 100 inclusive; then produce a chart similar to the one below that indicates how many input values fell in the range 1 to 10, 11 to 20, and so on. Print one asterisk for each value entered. Sample...
Implement and test a TaskList application in Java that will allow a client to manage information...
Implement and test a TaskList application in Java that will allow a client to manage information about daily tasks.  A task has a task name, is scheduled on a specific day of the week and can have a comment attached to it. Together, the task name and day uniquely identify a task. There may be tasks with the same name scheduled for different days of the week. The application should allow the client to start with an empty TaskList and then...
Design and implement a relational database application of your choice using MS Workbench on MySQL a)...
Design and implement a relational database application of your choice using MS Workbench on MySQL a) Declare two relations (tables) using the SQL DDL. To each relation name, add the last 4 digits of your Student-ID. Each relation (table) should have at least 4 attributes. Insert data to both relations (tables); (15%) b) Based on your expected use of the database, choose some of the attributes of each relation as your primary keys (indexes). To each Primary Key name, add...
In simple Java language algorithm: Implement a static stack class of char. Your class should include...
In simple Java language algorithm: Implement a static stack class of char. Your class should include two constructors. One (no parameters) sets the size of the stack to 10. The other constructor accepts a single parameter specifying the desired size of the stack a push and pop operator an isEmpty and isFull method . Both return Booleans indicating the status of the stack Using the stack class you created in problem 1), write a static method called parse that parses...
Write a program in Java Design and implement simple matrix manipulation techniques program in java. Project...
Write a program in Java Design and implement simple matrix manipulation techniques program in java. Project Details: Your program should use 2D arrays to implement simple matrix operations. Your program should do the following: • Read the number of rows and columns of a matrix M1 from the user. Use an input validation loop to make sure the values are greater than 0. • Read the elements of M1 in row major order • Print M1 to the console; make...
programing language JAVA: Design and implement an application that reads a sentence from the user, then...
programing language JAVA: Design and implement an application that reads a sentence from the user, then counts all the vowels(a, e, i, o, u) in the entire sentence, and prints the number of vowels in the sentence. vowels may be upercase
Develop a Java application using Parboiled library to write aparser for a customer form. Your...
Develop a Java application using Parboiled library to write a parser for a customer form. Your program should include a grammar for the parser and display the parse tree with no errors.The customer form should include the following structure:First name, middle name (optional), last nameStreet address, city, state (or province), countryPhone numberRules• First name, middle name and last name should start with an uppercase letter followed by lower case letters. Middle name is an optional input meaning such an input...
Using your solution or your instructor's solution from the Module 8 ungraded practice exercise, implement a...
Using your solution or your instructor's solution from the Module 8 ungraded practice exercise, implement a unit test for the Pair class by adding a main method. Create three small constituent classes (I created PeanutButter, Jelly, and Mustard classes) and insert various combinations of them into an array of Pair objects. Thoroughly test the equals(), hashCode(), and toString() methods from the Pair class with your main method. Note: override the toString() method in each of your constituent classes so they...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT