Question

In: Computer Science

The question I have is that I want to draw without having to drag and then...

The question I have is that I want to draw without having to drag and then clicking the button whether I want a line or rectangle. It should work first by hitting either the line or rectangle button and then making a drag on the panel with mouse, then after releasing the drag it creates the graphic.

Here is my current code.

package Mod1;
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);

    }

}

Solutions

Expert Solution

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

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;
        
        private String shape = "line";

        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");
                        }
                        
                        public void mouseReleased(MouseEvent e) {
                                // save coord x,y when mouse is pressed
                                currentX = e.getX();
                                currentY = e.getY();
                                
                                if(shape.equals("line")) {
                                        drawLine();
                                } else if(shape.equals("rectangle")) {
                                        drawRectangle();
                                }
                        }
                });
        }

        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();
                        
                        thin();
                }

                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 setShape(String shape) {
                this.shape = shape;
        }
        
        public void drawLine() {
                g2.drawLine(oldX, oldY, currentX, currentY);
                repaint();
        }

        public void drawRectangle() {
                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.setShape("rectangle");
                        } else if (e.getSource() == lineBtn) {
                                paintGUI.setShape("line");
                        }
                }
        };

        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

I want to draw a sphere and I want to rotate it, How can I do...
I want to draw a sphere and I want to rotate it, How can I do it in JOGL? ( I am working on a program to visualize the sun ) please provide a pic of the code.
I have searched the percentage of each question, but I want to know why there are...
I have searched the percentage of each question, but I want to know why there are differences? a. What's the percentage of loans out of total assets for Bank of America and Central Bank? What explains such a significant difference? BOA:40.2%, Central Bank:67%. b. What's the percentage of total deposits out of total liabilities (including capital) for Bank of America and Central Bank? Again, why do you think there is a significant difference? BOA:66.1%, Central Bank:89%.
I have created a MinHeap program without using arrays. Below is the followup question : The...
I have created a MinHeap program without using arrays. Below is the followup question : The heap class is a collection. Determine the correct location in your language’s collection class hierarchy. Find all methods that you need to implement in order to add your class in the language’s collection class hierarchy. What does this mean and how to implement it?
(I have posted this question three times without any answer! please answer it. I really need...
(I have posted this question three times without any answer! please answer it. I really need the answer) Using openERP open-source (Odoo 10) systems, you will have to build HR & Finance business processes into the system. You will have to build ( a University or any company of your choosing) HR business processes using one of the tool you found interesting. You will have to find out improvements of the process Add the business rules to the processes You...
I just want this answer to be in simple and easy words without missing the key...
I just want this answer to be in simple and easy words without missing the key words, to be easy for memorizing and understanding for my test.. please help We, as engineers, do not injure directly or indirectly the prospect of another engineer. In the same time, we shall be faithful and honest with our client and employer. In discharging our duty and carrying our works, we shall bear in mind that fair and honest dealing with all parties is...
I have to do a discussion about this question and I'm having trouble finding legitimate sources:...
I have to do a discussion about this question and I'm having trouble finding legitimate sources: "How can we ensure that farmers and ranchers, not government agencies, are driving the management of natural resources?" Anything would be appreciated!
Hello, I am just having a hard time understanding this question. The question is below. I...
Hello, I am just having a hard time understanding this question. The question is below. I am not supposed to write a program but instead in regular english sentence form just name the methods, fields, and variables I would use for this loan class. Im not really sure what a loan class means as well, thank you for your help. USING JAVA Given a Loan class, name the necessary fields and methods that we would need in this class. Be...
Hi, I want to programm a c++ gamr without the using of any array. only by...
Hi, I want to programm a c++ gamr without the using of any array. only by using FUNCTIONS, WHILE LOOPS, FOR LOOPS, IF ELSE, SRADN() and RAND(), BREAK STATEMENT, CIN and COUT. Please help me out.
So, I have this Matlab program that I have made for a lab, and despite having...
So, I have this Matlab program that I have made for a lab, and despite having different frequencies, when I go to plot them, the graphs look exactly the same. Can someone tell me why that is? I also need to know how to determine the digital frequencies(rad/sec) and how many samples per period of both of the waves? Thank you Code: N = 100; % Total number of time domain samples in simulation. A1 = 1; % Amplitude of...
A couple of questions that I want to understand better. How to draw a class diagram?...
A couple of questions that I want to understand better. How to draw a class diagram? What a clean object hierarchy diagram looks like? How to instantiate objects? What {cohesive, decoupled, information hiding, inheritance, and polymorphic} mean and why we strive to achieve them? When to implement a list with an array and when to implement it with a linked list When to use a list, stack, or queue?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT