Posted By

tonyjiang02 on 07/07/18


Tagged

java


Versions (?)

CIS35B project 0


 / Published in: Java
 

U

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.ArrayList;
  4. import java.util.Random;
  5.  
  6. import javax.swing.*;
  7.  
  8. public class Lab0 {
  9. public static JFrame fr;
  10. public static void main(String[] args) {
  11. SwingUtilities.invokeLater(new Runnable() {
  12. public void run() {
  13. fr = new MouseFrame();
  14. fr.setVisible(true);
  15. }
  16. });
  17. }
  18. }
  19. class MouseFrame extends JFrame {
  20. public static final int SCREEN_WIDTH = 900;
  21. public static final int SCREEN_HEIGHT = 700;
  22. public MouseFrame() {
  23. setTitle("Follow Mouse");
  24. setSize(SCREEN_WIDTH,SCREEN_HEIGHT);
  25. setDefaultCloseOperation(EXIT_ON_CLOSE);
  26. setResizable(false);
  27. Container contentPane = getContentPane();
  28. contentPane.add(new MousePanel());
  29. }
  30. }
  31. class MousePanel extends JPanel {
  32. private MousePanel panel = this;
  33. private int currentX;
  34. private int currentY;
  35. private int prevX;
  36. private int prevY;
  37. private boolean firstClick = true;
  38. public MousePanel() {
  39. setLayout(null);
  40. addMouseListener(new MouseTracker());
  41. }
  42. private class MouseTracker extends MouseAdapter {
  43. public void mousePressed(MouseEvent event) {
  44. currentX=event.getX();
  45. currentY=event.getY();
  46. panel.add(new Square(currentX-10,currentY-10,30,30));
  47. if(!firstClick) {
  48. panel.add(new MouseLine(prevX,prevY,currentX,currentY));
  49. }else {
  50. firstClick=false;
  51. }
  52. prevX = currentX;
  53. prevY = currentY;
  54. panel.revalidate();
  55. panel.repaint();
  56. }
  57. }
  58. }
  59. class Square extends JComponent {
  60. public Square(int x, int y, int w, int h) {
  61. setBounds(x,y,w,h);
  62. }
  63. @Override
  64. public void paintComponent(Graphics g) {
  65. super.paintComponent(g);
  66. g.drawRect(0, 0, 20, 20);
  67. }
  68. // public Dimension getPreferredSize() {
  69. // return new Dimension(30, 30);
  70. // }
  71. }
  72. class MouseLine extends JComponent {
  73. int xstart;
  74. int ystart;
  75. int xend;
  76. int yend;
  77. public MouseLine(int xs, int ys, int xe, int ye) {
  78. xstart = xs;
  79. ystart = ys;
  80. xend = xe;
  81. yend = ye;
  82. setBounds(0,0,MouseFrame.SCREEN_WIDTH,MouseFrame.SCREEN_HEIGHT);
  83. }
  84. @Override
  85. public void paintComponent(Graphics g) {
  86. super.paintComponent(g);
  87. g.drawLine(xstart,ystart,xend,yend);
  88. }
  89. // public Dimension getPreferredDimension() {
  90. // return new Dimension(Math.abs(xstart-xend),Math.abs(ystart-yend));
  91. // }
  92. }

Report this snippet  

You need to login to post a comment.