Advertisement
Guest User

Untitled

a guest
May 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. package ergastirio16;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Graphics;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.MouseEvent;
  8. import java.awt.event.MouseMotionListener;
  9. import java.awt.image.BufferedImage;
  10. import java.io.File;
  11. import java.io.IOException;
  12. import javax.imageio.ImageIO;
  13. import javax.swing.JFrame;
  14. import javax.swing.JPanel;
  15. import javax.swing.Timer;
  16.  
  17. /**
  18. *
  19. * @author aifragkou
  20. */
  21. public class Game extends JFrame implements ActionListener , MouseMotionListener{
  22. private MyPanel panel;
  23. private Timer timer;
  24. public Game(){
  25. this.setBounds(0,0,800,600);
  26. this.setTitle("Hello unicorn");
  27. this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  28. this.panel = new MyPanel(this);
  29. this.add(this.panel);
  30. this.setVisible(true);
  31. this.timer = new Timer(33,this);
  32. this.timer.start();
  33. this.addMouseMotionListener(this);
  34. }
  35.  
  36. @Override
  37. public void actionPerformed(ActionEvent e) {
  38. // this.panel.setUnicornX(this.panel.getUnicornX()+1);
  39. this.repaint();
  40. }
  41.  
  42. @Override
  43. public void mouseDragged(MouseEvent e) {
  44.  
  45. }
  46.  
  47. @Override
  48. public void mouseMoved(MouseEvent e) {
  49. this.panel.setUnicornX(e.getX());
  50. this.panel.setUnicornY(e.getY());
  51.  
  52. }
  53. private class MyPanel extends JPanel{
  54.  
  55. private Game gameInstance;
  56. private BufferedImage image;
  57. private int unicornX,unicornY;
  58.  
  59. public int getUnicornX() {
  60. return unicornX;
  61. }
  62.  
  63. public void setUnicornX(int unicornX) {
  64. this.unicornX = unicornX;
  65. }
  66.  
  67. public int getUnicornY() {
  68. return unicornY;
  69. }
  70.  
  71. public void setUnicornY(int unicornY) {
  72. this.unicornY = unicornY;
  73. }
  74.  
  75. public MyPanel(Game game){
  76. this.gameInstance = game;
  77. try {
  78. this.image = (BufferedImage)ImageIO.read(new File("C:\\Users\\aifragkou\\Downloads\\unicorn1.jpg"));
  79. } catch (IOException ex) {
  80. }
  81. }
  82.  
  83. @Override
  84. public void paint(Graphics g){
  85. if(Math.random()>0.5){
  86. g.setColor(Color.BLACK);
  87. }else{
  88. g.setColor(Color.GREEN);
  89. }
  90. g.fillRect(0,0, this.gameInstance.getWidth(),this.gameInstance.getHeight());
  91. g.drawImage(image,this.getUnicornX(),this.getUnicornY(),this);
  92. g.setColor(Color.GREEN);
  93. g.drawString("Hello world", 50, 50);
  94.  
  95. }
  96. }
  97.  
  98.  
  99. public static void main(String[] args){
  100. Game g = new Game();
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement