Paint a rect on Jpanel with paintcomponent doesn't work - java

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.

Related

Multiple images one by one JPanel

I am trying to load images to JPanel from a directory (which contains only images) one by one. I want to crop the image one by one using mouse events. I wrote program for loading one image by giving it's path to JPanael and then cropping it using mouse. But i don't know how to extend program for multiple images one by one and saving the cropped ones in a different directory. I tried swing timer also but i could not figure how to use it. Can any please help me?
Here is my code for single image.
public class MainActivity extends JFrame implements MouseListener,MouseMotionListener{
int drag_status=0,c1,c2,c3,c4;
static String[] pathArray = new String[1000];
public static void main(String args[]) {
new MainActivity().start();
String s = "G:\\my pic";
File f = new File(s);
String str;
System.out.println(true);
//just to put all the pictures in list
File[] fa = f.listFiles();
for (int i=0; i< fa.length; i++) {
String path = fa[i].toString();
str = path.replace("\\", "\\\\");
pathArray [i] = str;
System.out.println(pathArray[2]); //gives all the paths in ImagePanel path format
}
}
public void start() {
ImageJPanel imageJPanel=new ImageJPanel(pathArray[1]);
add(imageJPanel);
setSize(200,200);
setVisible(true);
addMouseListener(this);
addMouseMotionListener( this );
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void mouseMoved(MouseEvent e) {
// 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
repaint();
c1=arg0.getX();
c2=arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
if(drag_status==1) {
c3=arg0.getX();
c4=arg0.getY();
try {
draggedScreen();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public void draggedScreen()throws Exception {
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,width,height));
File save_path=new File("C:\\Users\\apurvgandhwani\\Desktop\\cropped");
ImageIO.write(img, "JPG", save_path);
System.out.println("Saved to folder");
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
drag_status=1;
c3=arg0.getX();
c4=arg0.getY();
}
public void paint(Graphics g) {
super.paint(g);
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
if(width<0) width = width * -1;
g.drawRect(c1, c2, width, height); }
}
And ImageJPanel class
public class ImageJPanel extends JPanel{
private static final long serialVersionUID = 1L;
private Image image;
int x = 0;
public ImageJPanel(String image){
this(new ImageIcon(image).getImage());
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x += 110;
if (x >= 1000) {
x = 1000;
((Timer)e.getSource()).stop();
}
repaint();
}
});
timer.start();
}
public ImageJPanel(Image image){
this.image = image;
Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g){
g.drawImage(image, 0, 0, null);
}
}

Drawing on JPanel with paint(Graphics gr)

I tried to draw a simple rectangle on a JPanel wich is on a JFrame, but it didn't work. Can someone please give me some advices? Would be happy if someone could... I really tried hard, but I couldn figure out how to do this. This code is part of my "Snake" -program. All the rest works, in excep of this. Here is my Code:
package initialising_Package;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Initialising extends JPanel implements WindowListener,
ItemListener, ChangeListener, Runnable {
/**
* #param args
*/
private String name;
private JFrame frame;
private boolean fall = false;
private JSlider slider;
private JLabel lbl1, lbl2, lbl3, lbl4;
private JComboBox box1, box2, box3;
private String[] positionsx, positionsy, laenge;
private JPanel pnl1, pnl2, pnl3, pnlpnl;
private JButton btn;
private int beginningLenght, posX, posY;
private boolean start = false;
public Initialising() {
initStartFrame("Initialising");
}
public void initStartFrame(String name) {
frame = new JFrame(name);
frame.setLocation(300, 300);
frame.setSize(500, 350);
frame.setUndecorated(false);
frame.getContentPane().setLayout(new GridLayout(5, 1));
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(this);
// GUI
slider = new JSlider(1, 100, 50);
slider.addChangeListener(this);
slider.setPaintTicks(false);
slider.setPaintTrack(true);
positionsx = new String[50];
positionsy = new String[50];
for (int i = 0, j = 0; i < 50; i++, j = j + 10) {
positionsx[i] = new String("" + j);
positionsy[i] = new String("" + j);
}
laenge = new String[45];
for (int i = 0; i < 45; i++) {
laenge[i] = "" + (i + 1);
}
box1 = new JComboBox(positionsx);
box1.addItemListener(this);
box2 = new JComboBox(positionsy);
box2.addItemListener(this);
box3 = new JComboBox(laenge);
box3.addItemListener(this);
lbl1 = new JLabel("Geschwindigkeit: ");
lbl2 = new JLabel("Startlaenge: ");
lbl3 = new JLabel("Position: ");
pnlpnl = new JPanel();
pnlpnl.setPreferredSize(new Dimension(95, 490));
pnlpnl.setBackground(Color.BLACK);
pnl1 = new JPanel();
pnl1.setLayout(new GridLayout(1, 2));
pnl2 = new JPanel();
pnl2.setLayout(new GridLayout(1, 2));
pnl3 = new JPanel();
pnl3.setLayout(new GridLayout(1, 3));
btn = new JButton("Snake!");
btn.setPreferredSize(new Dimension(80, 490));
pnl1.add(lbl1);
pnl1.add(slider);
pnl2.add(lbl2);
pnl2.add(box3);
pnl3.add(lbl3);
pnl3.add(box1);
pnl3.add(box2);
frame.add(pnlpnl);
frame.add(pnl1);
frame.add(pnl2);
frame.add(pnl3);
frame.add(btn);
// GUI
frame.validate();
frame.repaint();
}
public int getSpeed() {
return slider.getValue();
}
public int getBeginningLenght() {
return beginningLenght;
}
public int getPosX() {
return posX;
}
public int getPosY() {
return posY;
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
int z = JOptionPane.showConfirmDialog(frame,
"Willst du wirklich benden?", "Warnung", 0);
if (z == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Initialising init = new Initialising();
new Thread(init).start();
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(box1)) {
posX = Integer.parseInt((String) box1.getSelectedItem());
System.out.println("PosX: " + posX);
} else if (e.getSource().equals(box2)) {
posY = Integer.parseInt((String) box2.getSelectedItem());
System.out.println("PosY: " + posY);
} else if (e.getSource().equals(box3)) {
beginningLenght = Integer.parseInt((String) box3.getSelectedItem());
System.out.println("Beginning Lenght: " + beginningLenght);
System.out.println("H: " + pnlpnl.getHeight() + " B: "
+ pnlpnl.getWidth());
}
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(slider)) {
System.out.println("Speed: " + slider.getValue());
}
}
#Override
public void paintComponent(Graphics gr) {
super.paint(gr);
gr.setColor(Color.CYAN);
gr.fillRect(0, 0, 200, 200);
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
System.out.println("It works!!");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!start) {
}
repaint();
validate();
}
}
}
Remove the paintComponent from the JFrame. That did also call super.paint i.o. super.paintComponent.
pnlpnl = new JPanel() {
#Override
public void paintComponent(Graphics gr) {
super.paintComponent(gr);
gr.setColor(Color.CYAN);
gr.fillRect(0, 0, 200, 200);
}
};
In this paintComponent you can use the JFrame's fields.
As initStartFrame is called in the constructor it should not be overridable (the child class's version then would be called, without the child class being entirely initialized).
//Sometimes: public final void initStartFrame(String name) {
private void initStartFrame(String name) {
Start the frame as such:
// GUI
frame.validate();
//frame.repaint();
frame.pack();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});

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.

How do i use KeyListener in java?

How do I use KeyListener on this code to move up and down? Ii know how to use KeyListener but I don't know where it put it on this code.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ControlPanel extends JPanel implements Runnable,ActionListener,KeyListener,MouseListener{
private MainPanel main;
private final static int maxWidth = 800, maxHeight = 600; //width & height of JPanel
private boolean running; //keeps track of state of the program
private Thread thread;
private Graphics2D graphics;
private Image image; //used for double buffering
private BufferedImage bgImage;
private String s = "";
Font f = new Font("Times New Roman",Font.PLAIN,50);
Timer t = new Timer(2000,this);
private int typed = 0;
private int x = 50,y = 500;
public ControlPanel(MainPanel main) {
this.setDoubleBuffered(false); //we'll use our own double buffering method
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(maxWidth, maxHeight));
this.setFocusable(true);
this.requestFocus();
this.main = main;
addKeyListener(this);
addMouseListener(this);
t.start();
}
public static void main(String[] args) {
new MainPanel();
}
public void addNotify() {
super.addNotify();
startGame();
}
public void stopGame() {
running = false;
}
//Creates a thread and starts it
public void startGame() {
if (thread == null || !running) {
thread = new Thread(this);
}
thread.start(); //calls run()
}
public void run() {
running = true;
init();
while (running) {
createImage(); //creates image for double buffering
///////////////USE THESE 2 METHODS////////////////////
update(); //use this to change coordinates, update values, etc
draw(); //use this to draw to the screen
//////////////////////////////////////////////////////
drawImage(); //draws on the JPanel
}
System.exit(0);
}
//Use this to create or initialize any variables or objects you have
public void init() {
}
public void initGame(){
}
//Use this to update anything you need to update
public void update() {
}
//Use this to draw anything you need to draw
public void draw() {
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 450, 300,100);
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 320, 300,100);
graphics.setColor(Color.GREEN);
graphics.setFont(f);
graphics.drawString(s, x, y);
typed = 0;
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("HANGMAN", 270,75);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("PLAY", 330, 390);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("QUIT", 330, 520);
graphics.setColor(Color.red);
graphics.drawRect(248, 318, 304,104);
}
//creates an image for double buffering
public void createImage() {
if (image == null) {
image = createImage(maxWidth, maxHeight);
if (image == null) {
System.out.println("Cannot create buffer");
return;
}
else
graphics = (Graphics2D)image.getGraphics(); //get graphics object from Image
}
if (bgImage == null) {
graphics.setColor(Color.black);
graphics.fillRect(0, 0, maxWidth, maxHeight);
//System.out.println("No background image");
}
else {
//draws a background image on the Image
graphics.drawImage(bgImage, 0, 0, null);
}
}
//outputs everything to the JPanel
public void drawImage() {
Graphics g;
try {
g = this.getGraphics(); //a new image is created for each frame, this gets the graphics for that image so we can draw on it
if (g != null && image != null) {
g.drawImage(image, 0, 0, null);
g.dispose(); //not associated with swing, so we have to free memory ourselves (not done by the JVM)
}
image = null;
}catch(Exception e) {System.out.println("Graphics objects error");}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
typed = 1;
s+=Character.toString(e.getKeyChar());
s+=" ";
System.out.println(s);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
#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
}
}
KeyListener isn‘t designated for listening of keyboard events for Swing JComponents, use KeyBindings instead, output to the Swing GUI should be from Swing Action
You have added key listener by calling this      
addKeyListener(this);

freehand drawline using mouse events

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

Categories

Resources