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();
}
Related
I am working on program wich is drawing a grid of cells. Each cell has specified color and one of four states:
STARTCELL //marked by yellow color
ENDCELL //marked by red color
EMPTYCELL //marked by white color
BLOCKEDCELL // marked by black color
At the beginning there are one yellow cell, and one red cell and the rest of them is white.
I wanted to be able to change the colors and states of cells by clicking on them and after some research I found the solution:
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
for (Cell item : gridCells) {
if (item.getCellShape().contains(e.getPoint())&& item.getCellState()==CellState.EMPTYCELL) {
item.setCellColor(mouseColor);
if(mouseColor==startCellColor){
item.setCellState(CellState.STARTCELL);
}else if(mouseColor==endCellColor){
item.setCellState(CellState.ENDCELL);
}else{
item.setCellState(CellState.BLOCKEDCELL);
}
}
}
repaint();
}
The only problem is there should be only one STARTCELL
and one ENDCELLat the time and I can't find a way to properly change states of non clicked cells.
I tried many times and ended up with this:
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
for (Cell item : gridCells) {
if (item.getCellShape().contains(e.getPoint())&& item.getCellState()==CellState.EMPTYCELL) {
item.setCellColor(mouseColor);
if(mouseColor==startCellColor){
gridCells.get(numberOfStartCell-1).setCellColor(cellColor);
gridCells.get(numberOfStartCell-1).setCellState(CellState.EMPTYCELL);
numberOfStartCell=item.getNumberOfCell();
item.setCellState(CellState.STARTCELL);
}else if(mouseColor==endCellColor){
item.setCellState(CellState.ENDCELL);
}else{
item.setCellState(CellState.BLOCKEDCELL);
}
areaTest.setText(Integer.toString(numberOfStartCell));
}
}
repaint();
}
Unfortunately it doesn't work correctly. After the first click the color of the new cell changes to yellow the old one became white, and value of variable numberOfStartCell also changes. But after the second click and so on the only part wich changes is numberOfStartCell.
Here is MCV:
Nothing to explain in first two classes i guess.
Class Main
import java.awt.EventQueue;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame();
}
});
}
}
Class MyFrame
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class MyFrame extends JFrame {
int width = 750;
int height = 750;
MyPanel panel;
public MyFrame() {
super("Przeszukiwanie");
setSize(width,height);
setResizable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double ScreenHeight = screenSize.getHeight();
int x = ((int)screenWidth-width)/2;
int y = ((int)ScreenHeight-height)/2;
setLocation(x,y);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
panel=new MyPanel();
add(panel);
pack();
}
}
Class MyPanel takes care of event handling and GUI.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class MyPanel extends JPanel implements ActionListener{
private JButton createButton;
private ButtonGroup cellColorGroup;
private JRadioButton startingNode;
private JRadioButton endingNode;
private JRadioButton obstacleNode;
private JTextField rows;
private JTextField columns;
private JLabel labelRows;
private JLabel labelColumns;
private String strRowsField;
private String strColumnsField;
private JPanel panelButtons;
private GridPanel panelGrid;
private JPanel panelSettings;
public MyPanel(){
setPreferredSize(new Dimension(700, 600));
setLayout(new BorderLayout());
strRowsField="10";
strColumnsField="10";
panelButtons=new JPanel();
panelSettings=new JPanel();
panelGrid=new GridPanel(Integer.parseInt(strColumnsField),Integer.parseInt(strRowsField));
panelSettings.setLayout(new GridLayout(6,2));
createButton= new JButton("Create");
cellColorGroup=new ButtonGroup();
startingNode=new JRadioButton("Strating Node");
endingNode=new JRadioButton("Ending Node");
obstacleNode=new JRadioButton("Remove/Add Obstacle", true);
cellColorGroup.add(startingNode);
cellColorGroup.add(endingNode);
cellColorGroup.add(obstacleNode);
createButton.addActionListener(this);
startingNode.addActionListener(this);
endingNode.addActionListener(this);
obstacleNode.addActionListener(this);
columns=new JTextField(strColumnsField,2);
rows=new JTextField(strRowsField,2);
labelRows=new JLabel("Number of rows");
labelColumns= new JLabel("Number of columns");
panelButtons.add(createButton);
panelSettings.add(labelColumns);
panelSettings.add(columns);
panelSettings.add(labelRows);
panelSettings.add(rows);
panelSettings.add(startingNode);
panelSettings.add(endingNode);
panelSettings.add(obstacleNode);
add(panelButtons,BorderLayout.SOUTH);
add(panelGrid,BorderLayout.WEST);
add(panelSettings,BorderLayout.EAST);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == createButton) {
panelGrid.setcNodes(Integer.parseInt(columns.getText()));
panelGrid.setrNodes(Integer.parseInt(rows.getText()));
panelGrid.getGridCells().clear();
panelGrid.repaint();
}else if(e.getSource() == startingNode){
panelGrid.setMouseColor(panelGrid.getStartCellColor());
}else if(e.getSource() == endingNode){
panelGrid.setMouseColor(panelGrid.getEndCellColor());
}else if(e.getSource() == obstacleNode){
panelGrid.setMouseColor(panelGrid.getObstacleCellColor());
}
}
}
Class GridPanel takes care of drawing nodes, edges and cells.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JPanel;
public class GridPanel extends JPanel implements MouseListener, MouseMotionListener {
private int cNodes;//Number of nodes across
private int rNodes;//Number of nodes along
private int nodeX;//X coordinate of the first node
private int nodeY;//Y coordinate of the first node
private int width=330;
private int height=330;
private int circleX;//Center of circle X
private int circleY;//Center of circle Y
private Color cellColor;
private Color startCellColor;
private Color endCellColor;
private Color obstacleCellColor;
private Color mouseColor;
private int numberOfStartCell;
private ArrayList<Cell> gridCells;
public GridPanel(int cNodes, int rNodes){
setPreferredSize(new Dimension(width,height));
this.cNodes=cNodes;
this.rNodes=rNodes;
if(cNodes>rNodes){
nodeX=width/(cNodes+1);//Calculation of the x coordinate value of the first node
nodeY=height/(cNodes+1);//Calculation of the y coordinate value of the first node
}else{
nodeX=width/(rNodes+1);
nodeY=height/(rNodes+1);
}
circleX=nodeX;
circleY=nodeY;
cellColor=Color.WHITE;
startCellColor=Color.YELLOW;
endCellColor=Color.RED;
obstacleCellColor=Color.BLACK;
gridCells=new ArrayList<Cell>();
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawCells(g2d);
}
public void drawCells(Graphics2D g2d){
int number=0;
int c=0;
for(int i=0; i<rNodes; i++){
for(int j=0; j<cNodes; j++){
number++;
if(i==0 && j==cNodes-1){
gridCells.add(new Cell(circleX,circleY,nodeX,endCellColor,new Rectangle2D.Double(circleX-(nodeX/2),circleY-(nodeX/2),nodeX,nodeX),CellState.ENDCELL,number));
}
else if(i==rNodes-1 && j==0){
gridCells.add(new Cell(circleX,circleY,nodeX,startCellColor,new Rectangle2D.Double(circleX-(nodeX/2),circleY-(nodeX/2),nodeX,nodeX),CellState.STARTCELL,number));
numberOfStartCell=number;
}
else {
gridCells.add(new Cell(circleX,circleY,nodeX,cellColor,new Rectangle2D.Double(circleX-(nodeX/2),circleY-(nodeX/2),nodeX,nodeX),CellState.EMPTYCELL,number));
}
g2d.setPaint(gridCells.get(c).getCellColor());
g2d.fill(gridCells.get(c).getCellShape());
g2d.setPaint(Color.BLACK);
g2d.draw(gridCells.get(c).getCellShape());
if(j<(cNodes-1)){
circleX+=nodeX;
}
c++;
}
circleX=nodeX;
if(i<(rNodes-1)){
circleY+=nodeY;
}
}
circleX=nodeX;
circleY=nodeY;
}
public void setMouseColor(Color mouseColor) {
this.mouseColor = mouseColor;
}
public void setcNodes(int cNodes) {
this.cNodes = cNodes;
}
public void setrNodes(int rNodes) {
this.rNodes = rNodes;
}
public Color getObstacleCellColor() {
return obstacleCellColor;
}
public Color getStartCellColor() {
return startCellColor;
}
public Color getEndCellColor() {
return endCellColor;
}
public ArrayList<Cell> getGridCells() {
return gridCells;
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
for (Cell item : gridCells) {
if (item.getCellShape().contains(e.getPoint())&& item.getCellState()==CellState.EMPTYCELL) {
item.setCellColor(mouseColor);
if(mouseColor==startCellColor){
gridCells.get(numberOfStartCell-1).setCellColor(cellColor);
gridCells.get(numberOfStartCell-1).setCellState(CellState.EMPTYCELL);
numberOfStartCell=item.getNumberOfCell();
item.setCellState(CellState.STARTCELL);
}else if(mouseColor==endCellColor){
item.setCellState(CellState.ENDCELL);
}else{
item.setCellState(CellState.BLOCKEDCELL);
}
}
}
repaint();
}
#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
}
}
Class Cell has information about cells (state, color, number..).
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public class Cell implements Shape{
private int centerX;
private int centerY;
private double side;
private Color cellColor;
private double x;
private double y;
private Shape cellShape;
private CellState cellState;
private int numberOfCell;
public Cell(int centerX, int centerY, int side, Color cellColor,Shape cellShape, CellState cellState,int numberOfCell){
super();
this.centerX=centerX;
this.centerY=centerY;
this.side=side;
this.cellColor=cellColor;
this.cellShape=cellShape;
this.cellState=cellState;
this.numberOfCell=numberOfCell;
}
public Shape getCellShape() {
return cellShape;
}
public int getNumberOfCell() {
return numberOfCell;
}
public Color getCellColor() {
return cellColor;
}
public void setCellColor(Color cellColor) {
this.cellColor = cellColor;
}
public void setCellShape(Shape cellShape) {
this.cellShape = cellShape;
}
public double getSide() {
return side;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public CellState getCellState() {
return cellState;
}
public void setCellState(CellState cellState) {
this.cellState = cellState;
}
#Override
public boolean contains(Point2D p) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(Rectangle2D r) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(double x, double y) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(double x, double y, double w, double h) {
// TODO Auto-generated method stub
return false;
}
#Override
public Rectangle getBounds() {
// TODO Auto-generated method stub
return null;
}
#Override
public Rectangle2D getBounds2D() {
// TODO Auto-generated method stub
return null;
}
#Override
public PathIterator getPathIterator(AffineTransform at) {
// TODO Auto-generated method stub
return null;
}
#Override
public PathIterator getPathIterator(AffineTransform at, double flatness) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean intersects(Rectangle2D r) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean intersects(double x, double y, double w, double h) {
// TODO Auto-generated method stub
return false;
}
}
Class CellState
public enum CellState {
STARTCELL,ENDCELL,EMPTYCELL,BLOCKEDCELL;
}
I can't give a chapter and verse answer, not without your MCVE, but I can give you a large suggestion. Note that selecting empty and and blocked cells is logically a very different thing from selecting starting and ending cells, and so your code should do these things in very different ways. What I would do, is in the mouse listener, check which button is pressed. If the left button (the standard button), toggle the cells blocked / empty state (but only if it's not already a start or end cell). If the right mouse button is pressed (or alt-mouse if there is no mouse button), then display a pop-up menu to allow the user to select the cell as the start or end cell. The code for selecting start or end would be separate from the empty/block toggle code, would first iterate through the model, clearing the former start or end cell, and then setting it.
If you want a better more complete solution, again, please post your valid Minimal, Complete, and Verifiable example code here with your question (not in a link).
Luck.
I am trying to implement a click and drag method, for which I need mousePressed and mouseReleased events. I will also be using mouseClicked events, so I implemented MouseMotionListener and MouseListener.
However, when I go to write mousePressed, mouseReleased, mouseEntered, mouseExited methods I get the following error:
method mousePressed(MouseEvent) is already defined in class BoingPanel
Here is the entire class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
public class BoingPanel extends JPanel implements MouseMotionListener, MouseListener {
private int width;
private int height;
private int updateRate=40;
ArrayList<Ball> balls;
ArrayList<Line> lines;
private Container box;
private boolean drag = false;
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public BoingPanel()
{
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
lines.add(new Line(0, height, width, height));
gameStart();
}
public BoingPanel(int x, int y)
{
width=x;
height=y;
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
box = new Container(width, height);
gameStart();
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public void gameStart() {
// Run the game logic in its own thread.
Thread gameThread = new Thread() {
public void run() {
while (true) {
// Execute one time-step for the game
update();
// Refresh the display
repaint();
// Delay and give other thread a chance
try {
Thread.sleep(1000 /updateRate);
} catch (InterruptedException ex) {}
}
}
};
gameThread.start(); // Invoke GaemThread.run()
}
private void update()
{
for(Ball a:balls) //calls balls updated position
{
a.update(box);
}
}
public void paintComponent(Graphics g)
{
box.paint(g);
for(Ball a:balls) //calls balls updated position
{
a.paint(g);
}
for(Line b:lines) //draws lines
{
b.paint(g);
}
}
public void actionPerformed(ActionEvent e)
{
update(); //changes ball position
repaint(); //refreshes image
}
}
What is causing this error? Thanks!
I would suggest this, just below your variable declarations and before you constructor, isn't helping...
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
You've basically implemented these methods twice. Just before and after the constructor.
Simply remove on of these groups of declarations...
please remove public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { } and then try
Basically I have two classes, an Infantry class which is used to create units in a game, and a Map class which is used to paint everything (i.e. units, building, etc.) to the screen. I have a MouseListener in my Infantry class that takes the coordinates of the mouse upon click, sets the x and y variables of an image to those then repaints the image on the screen. When I directly make an Infantry object in my JFrame class this works fine, but I can't see the Map class being painted before hand. When I make the object within the Map class itself (which is my main objective), the MouseListener doesn't work, as in it won't register a click or any of the methods (I tried a console printout to test this). Right now I'm a little lost on why this won't work and any help would be much appreciated.
Infantry class:
public class Infantry extends JLabel{
private Image img;
private int bx;
private int by;
private MouseListener move = new Move();
public Infantry(String file, int Bx, int By){
img = new ImageIcon(file).getImage();
bx = Bx;
by = By;
setOpaque(false);
addMouseListener(move);
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawImage(img, bx, by, null);
}
private class Move implements MouseListener{
#Override
public void mouseClicked(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
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
bx = e.getX();
by = e.getY();
repaint();
}
}
}
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.
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);
}
}