Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. import java.awt.*;
  2. import javax.swing.*;
  3.  
  4. import java.awt.event.*;
  5. import java.awt.FlowLayout;
  6. import javax.swing.JFrame;
  7. import javax.swing.JLabel;
  8. import javax.swing.JPanel;
  9.  
  10. public class Main extends JPanel {
  11. private static final int DEFAULT_WIDTH = 800;
  12. private static final int DEFAULT_HEIGHT = 800;
  13. private static final Color BACK_COLOR = Color.WHITE;
  14. private Color curColor = Color.BLACK;
  15.  
  16. private int x1, y1, x2, y2;
  17. private Graphics g;
  18.  
  19.  
  20. public static void main(String[] args) {
  21. JFrame frame = new JFrame("Paint program simple");
  22. frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  23.  
  24. JPanel panel = new Main();
  25. frame.add(panel);
  26.  
  27. frame.pack();
  28. frame.setVisible(true);
  29. }
  30.  
  31.  
  32. private Main() {
  33. setBackground(BACK_COLOR);
  34. setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
  35.  
  36. MyMouseHandler handler = new MyMouseHandler();
  37.  
  38. this.addMouseListener(handler);
  39. this.addMouseMotionListener(handler);
  40. this.setFocusable(true);
  41. this.addKeyListener(new KeyAdapter() {
  42. @Override
  43. public void keyPressed(KeyEvent e) {
  44. // TODO Auto-generated method stub
  45. int key = e.getKeyCode();
  46. switch (key) {
  47. case KeyEvent.VK_Y:
  48. curColor = Color.YELLOW;
  49. break;
  50. case KeyEvent.VK_R:
  51. curColor = Color.RED;
  52. break;
  53. case KeyEvent.VK_G:
  54. curColor = Color.GREEN;
  55. break;
  56. case KeyEvent.VK_O:
  57. curColor = Color.ORANGE;
  58. break;
  59. case KeyEvent.VK_B:
  60. curColor = Color.BLACK;
  61. break;
  62. }
  63. }
  64. });
  65. }
  66.  
  67. private class MyMouseHandler extends MouseAdapter {
  68. public void mousePressed(MouseEvent e) {
  69. x1 = e.getX();
  70. y1 = e.getY();
  71.  
  72. g = getGraphics();
  73.  
  74. x2 = x1;
  75. y2 = y1;
  76. }
  77.  
  78. public void mouseDragged(MouseEvent e) {
  79. x1 = e.getX();
  80. y1 = e.getY();
  81.  
  82. g.setColor(curColor);
  83. g.drawLine(x1, y1, x2, y2);
  84.  
  85. x2 = x1;
  86. y2 = y1;
  87. }
  88. }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement