freehand drawline using mouse events - java

may i know if there is any formula for drawing lines? currently i am implementing a freehand draw line in java, however the code below when drawn it is not what im expecting.
i have tried g.drawLine(arg0.getX(), arg0.getY(), arg0.getX(), arg0.getY()); , however the line drawn is not continous rather it is drawing points, i read that it is because the mouse drag happens at intervals, if so how should i record the points?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class STDrawingArea extends JPanel implements MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
public STDrawingArea()
{
setPreferredSize(new Dimension(1280, 700));
setBounds(0, 0, 1280, 700);
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
xDragged = xPressed;
yDragged = yPressed;
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
#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
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
xReleased = arg0.getX();
yReleased = arg0.getY();
System.out.println("xReleased: "+xPressed+" ,yReleased: "+yPressed);
}
}

A simple way to do this might be:
Maintain a List of Points in your component
In the mouseDragged() method, get the point (MouseEvent#getPoint()) and add it to your list
Override the paintComponent() method of the JPanel
Iterate over all points in your list of points
Draw lines between each pair of points (except the first and last, of course)
For example, you might make the following changes:
private ArrayList<Point> points = new ArrayList<Point>();
//...
public void mouseDragged(MouseEvent arg0) {
points.add(arg0.getPoint());
repaint(); //request Swing to refresh display as soon as it can
}
//...
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < points.size() - 2; i++)
{
Point p1 = points.get(i);
Point p2 = points.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}

Some slight Changes are required
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xDragged, yDragged, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
and
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
xDragged=xPressed;
yDragged=yPressed;
}
I have compiled and executed this code and found its perfectly working..:-)

Try This. It's working. There is no need to use the Point class and iterate the 'for' loop, If you wanna simply make a Freehand Drawing.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class STDrawingArea extends JPanel implements MouseListener,MouseMotionListener,ActionListener
{
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private JButton clear;
public STDrawingArea()
{
setPreferredSize(new Dimension(1200, 500));
setBounds(0, 0, 480, 500);
//setBackground(Color.YELLOW);
clear=new JButton("CLEAR");
add(clear);
clear.setBounds(540, 5, 100, 25);
clear.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
setOpaque(false);
repaint();
}
}
#Override
protected void paintComponent(Graphics g)
{
g.drawLine(xPressed,yPressed,xDragged,yDragged);
xPressed=xDragged;
yPressed=yDragged;
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
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
setOpaque(true);
xPressed = arg0.getX();
yPressed = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class Frame4 extends JFrame
{
private STDrawingArea da;
public Frame4()
{
da=new STDrawingArea();
da.setBackground(Color.YELLOW);
da.setLayout(new BorderLayout());
add(da);
}
}
public class FreeHandDrwing
{
public static void main(String s[])
{
Frame4 ob=new Frame4();
ob.setVisible(true);
ob.setBounds(100, 100, 1200, 500);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Related

Regarding adding of Rectangle when mouse is clicked on JFrame

I am a beginner. I am trying to add filled rectangle or any other graphic on JFrame using multiple inner classes. I am getting debugging errors. What are the problems here?. If this is a wrong way. Please tell me how to do the same using JFrame and JPanel only.
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class RainBow{
JFrame frame;
public static void main(String[] args){
RainBow bow = new RainBow();
bow.go();
}
public class Paint extends JPanel{
public void paintComponent(Graphics g){
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
}
public void go(){
frame.addMouseListener(new ListenMouse());
frame.setSize(400, 400);
frame.setVisible(true);
}
public class ListenMouse implements MouseListener{
public void mosueClicked(MouseEvent a){
Paint p = new Paint();
frame.getContentPane().add(p);
frame.setVisible(true);
}
#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
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
}
The code posted has multiple problems. See this working example with explanations in comments.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class RainBow {
JFrame frame;
boolean paintRectangle = false;
public static void main(String[] args) {
RainBow bow = new RainBow();
bow.go();
}
public class Paint extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); // should always be done
if (paintRectangle) {
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
}
}
public void go() {
frame = new JFrame(); // otherwise NPE
Paint paint = new Paint();
paint.addMouseListener(new ListenMouse()); // add listner to paint
frame.add(paint); // add paint at start-up
frame.setSize(400, 400);
frame.setVisible(true);
// ensures JVM shuts down when frame is closed.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public class ListenMouse extends MouseAdapter {
// this method is incorrectly spelled!
public void mosueClicked(MouseEvent a) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
/* requires special handling to add components on the fly */
//Paint p = new Paint();
paintRectangle = true;
frame.repaint(); // forces the Paint to be painted as well.
}
}
}

MouseExited not fired when mouse exits button

I have a JPanel in a GridLayout that I add buttons to. I want to implement some kind of effect on buttons when the mouse is entered and when the mouse exits the button . The mouseEntered event is correctly fired when the mouse hovers over the button , however , when the mouse leaves the button the mouseExited event is not fired. How can I fix this issue?
Custom JButton
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class CustomButton extends JButton implements MouseListener{
Dimension scaled;
public CustomButton(String text){
super(text);
setContentAreaFilled(false);
setBorderPainted(false);
addMouseListener(this);
}
#Override
public void invalidate() {
super.invalidate();
scaled = getSize();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 20, 20);
g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 20, 20);
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("entered the view");
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("exited the view");
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Don't use a MouseListener, rather add a ChangeListener to the JButton's model and react to changes in its rollover state,... isRollover()
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestRollover extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
JButton button = new JButton("Button");
public TestRollover() {
add(button);
button.getModel().addChangeListener(new ChangeListener() {
private boolean rollover = false;
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover() != rollover) {
System.out.println("Rollover: " + model.isRollover());
rollover = model.isRollover();
}
}
});
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouse entered");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("mouse exited");
}
});
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
TestRollover mainPanel = new TestRollover();
JFrame frame = new JFrame("TestRollover");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Changing a color of circle after mousePressed

I have to change a color of spot to 'red' when mousePressed, then it should be back to its original color when mouseRelease. This is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PanelTwo extends JPanel implements MouseListener{
public Spot spot = new Spot(100,100,20);
//public Color f = new Color(250,0,0);
public PanelTwo(){
super();
setLayout (new FlowLayout());
//setOpaque(true);
addMouseListener(this);
}
public void paintComponent(Graphics g){
spot.draw(g);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
spot.x=e.getX();
spot.y=e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
And there is another code with information about my shape
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Spot {
public int x,y,r;
public Color c= new Color(100,150,200);
public Color f = new Color(250,0,0);
public Spot(int X, int Y, int R){
x=X; y=Y; r=R;
}
public void draw(Graphics g){
g.setColor(c);
g.fillOval(x-r, y-r, 2*r, 2*r);
}
}
So, I want to change the color of this ball after I press my mouse, and after I release - it should come back to the original color.
When mousePressed is called, record the original color of spot and change its color
When mouseReleased is called, reset spot to its original color
i assume that the two colors in your class is the color when it is clicked and released. you can't change the color because you are setting the Graphics.setColor() method to a specific color which is c . try to make it more flexible.
public class Spot {
public int x,y,r;
public Color c= new Color(100,150,200);
public Color f = new Color(250,0,0);
//make the default color to c
public Color currentColor = c;
public Spot(int X, int Y, int R){
x=X; y=Y; r=R;
}
public void draw(Graphics g){
g.setColor(currentColor);
g.fillOval(x-r, y-r, 2*r, 2*r);
}
}
and in your mousePressed or mouseReleased just change the currentColor
#Override
public void mousePressed(MouseEvent e) {
spot.x=e.getX();
spot.y=e.getY();
spot.currentColor = spot.f;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
spot.x=e.getX();
spot.y=e.getY();
spot.currentColor = spot.c;
repaint();
}

Paint a rect on Jpanel with paintcomponent doesn't work

I want to draw a rect on a DrawPanel. This rect should be a object.
When I add it the place will be grey but the paintcomponent will not paint, so I see nothing.
The class Drawpanel.java will be add on the contentpane, the contentpane is on the JFrame.
import java.awt.event.*;
import java.awt.*;
import javax.swing.JPanel;
public class DrawPanel extends JPanel implements MouseListener{
private static final long serialVersionUID = 6725416157621860479L;
public DrawPanel() {
addMouseListener(this);
this.setLayout(null);
setPreferredSize(new Dimension(500, 500));
}
Graphics2D g2d = null;
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g2d = (Graphics2D)g;
System.out.println("paint!!!!!!!");
for (int i = 0; i < 1500; i++) {
if (i %10 == 0) {
g2d.setColor(new Color(242, 242, 242));
g2d.drawLine(0, i, 1500, i);// _
g2d.drawLine(i, 0, i, 1500);// |
}
}
g2d.setColor(Color.BLUE);
}
#Override
public void mouseClicked(MouseEvent arg0) {
if (START.modus != 4) {
return;
}
System.out.println("X_" + arg0.getX() + " | Y_"+arg0.getY());
int x = (arg0.getX()) - (arg0.getX()%10);
int y = (arg0.getY()) - (arg0.getY()%10);
System.out.println("x_" + x + " " + "y_" + y);
Dia d = new Dia(x, y);
d.setBounds(x, y, 50, 50);
add(d);
}
#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
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
The object which will not be painted is:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Dia extends JPanel implements MouseListener {
private Point startcoord;
private int sizex = 50;
private int sizey = 20;
public Dia(int x, int y) {
super();
addMouseListener(this);
this.startcoord = new Point(x, y);
setPreferredSize(new Dimension(sizex, sizey));
}
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
System.out.println("Diaaaaa1");
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(0, 0, 50, 50);
// g.setColor(Color.RED);
g.drawRect(0, 0, sizex, sizey);
g.setColor(Color.GREEN);
g.drawString("TEST", 3, 3);
System.out.println("Diaaaaa");
}
public Point getStartcoord() {
return startcoord;
}
public void setStartcoord(Point startcoord) {
this.startcoord = startcoord;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("diac");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
Dia c = new Dia(10, 10);
//c.textsize();
JFrame a = new JFrame();
a.setVisible(true);
a.setSize(new Dimension(100, 100));
JPanel b = new JPanel();
a.add(b);
b.add(c);
}
}
When I start the main in the dia class I see nothing. Why dia will not start the paintcomponent method?
Really its simple you override another method paintComponents() but you need paintComponent(). Change that and all will be work.

Drawing Graphics is too slow

So, I have this project, and you can draw images in it. I wanted people to be able to draw on it, but at first it was too slow when I was using repaint() So i used the repaint(Rectangle r) tool. It's better, but still not the speed i was looking for.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingPad extends JPanel implements MouseListener,MouseMotionListener,ListSelectionListener{
public Color[][] picture = new Color[601][601];
public Color selected;
public String action;
public Maker m;
private static final long serialVersionUID = 1L;
public DrawingPad(Maker m){
this.m = m;
this.setPreferredSize(new Dimension(600,600));
this.setVisible(true);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
picture[x][y]=Color.WHITE;
}
}
}
public void addColor(int x, int y){
try{
picture[x][y]=selected;
repaint(new Rectangle(x,y,x,y));
}catch (Exception e){
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.clearRect(0, 0, 600, 600);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
g.setColor(picture[x][y]);
g.drawLine(x, y, x, y);
}
}
}
#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
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
for (int x = -1;x<=1;x++){
for (int y = -1;y<=1;y++){
this.addColor(e.getX()+x, e.getY()+y);
}
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource()==m.seeit){
selected = m.colors[m.seeit.getSelectedIndex()];
}else{
action=(String) m.actions.getSelectedValue();
}
}
}
You might want to look into drawing that which will not be changed into a BufferedImage, and then displaying that BufferedImage in the paintComponent method as a background image.
For example, please have a look at this link and also this one.

Categories

Resources