Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. import javax.swing.JFrame;
  2. import javax.swing.JPanel;
  3. import javax.swing.Timer;
  4. import java.awt.Container;
  5. import java.awt.Graphics;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8.  
  9. class myPanel extends JPanel implements ActionListener {
  10. int x = 0, y = 0;
  11. int dx = 1, dy = 1, d = 10;
  12. Timer pTimer;
  13. final int width, hight;
  14.  
  15. public myPanel(int w, int h) {
  16. width = w;
  17. hight = h;
  18. pTimer = new Timer(200, this);
  19. }
  20.  
  21. public void start() {
  22. pTimer.start();
  23. }
  24.  
  25. @Override
  26. public void paintComponent(Graphics g) {
  27. super.paintComponent(g);
  28. g.drawRect(0, 0, width, hight);
  29. g.drawArc(x , y , 100, 100, 0, 360);
  30. g.drawArc(x + 15, y+ 15, 70, 70, 0, -180);
  31. g.drawArc(x + 35, y + 35, 10, 10, 0, 360);
  32. g.drawArc(x + 60, y + 35, 10, 10, 0, 360);
  33. }
  34.  
  35. @Override
  36. public void actionPerformed(ActionEvent e) {
  37. x += d * dx;
  38. y += d * dy;
  39.  
  40. if (x < 0) {
  41. x += d;
  42. dx *= -1;
  43. } else if (x > width - 100) {
  44. x -= d;
  45. dx *= -1;
  46. }
  47. if (y < 0) {
  48. y += d;
  49. dy *= -1;
  50. } else if (y > hight - 100) {
  51. y -= d;
  52. dy *= -1;
  53. }
  54. repaint();
  55. }
  56. }
  57.  
  58. class MovingSmiley extends JFrame {
  59. public static void main(String[] args) {
  60. JFrame f = new JFrame();
  61. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  62. f.setSize(300, 200);
  63. f.setTitle("Moving Smiley");
  64. f.setResizable(false);
  65. Container contentPane = f.getContentPane();
  66. myPanel p = new myPanel(300, 150);
  67. contentPane.add(p);
  68. p.start();
  69.  
  70. f.setVisible(true);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement