SHARE
TWEET

Simple Java Paint program

GameNationRDF Mar 26th, 2016 185 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. public class SimplePaint
  6. {
  7.   public static void main(String[] args)
  8.   {
  9.     JFrame frame = new JFrame("Simple Paint");
  10.     frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  11.    
  12.     Panel panel = new Panel();
  13.     frame.add(panel);
  14.    
  15.     frame.pack();
  16.     frame.setVisible(true);
  17.   }
  18.  
  19.   public static class Panel extends JPanel implements MouseListener, MouseMotionListener
  20.   {
  21.     private int prevX, prevY;
  22.     private Graphics g;
  23.    
  24.     public Panel()
  25.     {
  26.       setBackground(Color.WHITE);
  27.       setPreferredSize( new Dimension(600, 600) );
  28.      
  29.       addMouseListener(this);
  30.       addMouseMotionListener(this);
  31.     }
  32.    
  33.     public void paintComponent(Graphics g)
  34.     {
  35.       super.paintComponent(g);
  36.     }
  37.    
  38.     private void setUpDrawingGraphics()
  39.     {
  40.       g = getGraphics();
  41.     }
  42.    
  43.     // MOUSE STUFF **********************
  44.     public void mousePressed(MouseEvent e)
  45.     {
  46.       int x = e.getX();
  47.       int y = e.getY();
  48.      
  49.       prevX = x;
  50.       prevY = y;
  51.      
  52.       setUpDrawingGraphics();
  53.     }
  54.    
  55.     public void mouseDragged(MouseEvent e)
  56.     {
  57.       int x = e.getX();
  58.       int y = e.getY();
  59.      
  60.       g.drawLine(prevX, prevY, x, y);
  61.      
  62.       prevX = x;
  63.       prevY = y;
  64.     }
  65.    
  66.     public void mouseReleased(MouseEvent e){  }
  67.     public void mouseEntered( MouseEvent e){ }
  68.     public void mouseExited(  MouseEvent e){ }
  69.     public void mouseClicked( MouseEvent e){ }
  70.     public void mouseMoved(   MouseEvent e){ }
  71.   }
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top