NickMeinholdTheCanvas v0.3


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // added code to select an item from the canvas, currently just prints the item's image path
  2. // just to show it works. The properties toolbar needs to change accordingly
  3.  
  4. package project;
  5.  
  6. import java.awt.*;
  7. import javax.imageio.ImageIO;
  8. import javax.swing.*;
  9.  
  10. import java.awt.event.*;
  11. import java.io.File;
  12. import java.util.ArrayList;
  13. import java.util.Iterator;
  14.  
  15. public class TheCanvas extends JPanel implements MouseListener, MouseMotionListener {
  16.  
  17. private int X, Y;
  18. private Image image;
  19. static public ArrayList<Item> canvas_items = new ArrayList<Item>();
  20.  
  21. public TheCanvas() {
  22. addMouseMotionListener(this);
  23. addMouseListener(this);
  24. setVisible(true);
  25. }
  26. public void mouseMoved(MouseEvent event) {
  27. X = (int) event.getPoint().getX();
  28. Y = (int) event.getPoint().getY();
  29. repaint();
  30. }
  31. public void mouseDragged(MouseEvent event) {
  32. mouseMoved(event);
  33. }
  34. public void mousePressed(MouseEvent event) {
  35.  
  36. }
  37.  
  38. public void mouseReleased(MouseEvent event) {
  39.  
  40. }
  41.  
  42. public void mouseEntered(MouseEvent event) {
  43.  
  44. }
  45.  
  46. public void mouseExited(MouseEvent event) {
  47.  
  48. }
  49.  
  50. public void mouseClicked(MouseEvent event) {
  51. System.out.println(X+","+Y);
  52. if(MapMaker.current_item != null) {
  53. Item placed_item = new Item(MapMaker.current_item);
  54. placed_item.setPos(X, Y);
  55. canvas_items.add(placed_item);
  56. MapMaker.current_item = null;
  57. repaint();
  58. }
  59. else {
  60. for (int i = canvas_items.size()-1; i >= 0; i--) {
  61. Item item = (Item) canvas_items.get(i) ;
  62. if(item.picked(X, Y)) {
  63. System.out.println(item.getImgpath());
  64. break;
  65. }
  66.  
  67. }
  68. }
  69.  
  70. }
  71. public void update(Graphics graphics) {
  72. paint(graphics);
  73. }
  74. public void paint(Graphics g) {
  75. // Dynamically calculate size information
  76. Dimension size = getSize();
  77. // diameter
  78. //int d = Math.min(size.width, size.height);
  79. //int x = (size.width - d)/2;
  80. //int y = (size.height - d)/2;
  81. g.setColor(Color.white);
  82. g.fillRect(0, 0, size.width, size.height);
  83. for (Iterator<Item> it = canvas_items.iterator (); it.hasNext (); ) {
  84. Item item = it.next ();
  85. g.drawImage(item.getImg(), item.getPos().x, item.getPos().y, null);
  86. }
  87. if(MapMaker.current_item != null)
  88. g.drawImage(MapMaker.current_item.getImg(), X, Y, null);
  89. }
  90.  
  91. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.