更改图像我单击

时间:2013-03-03 02:55:00

标签: java swing awt mouselistener

我有这个可运行的代码,在运行时无法正常工作。

当您在编辑器框架内单击时,它应该将您单击的图像更改为其他图像。

图像的更改发生在setImage()

int array images只存储012

getImage()用于paintComponent中的图像绘制,读取int array images并根据特定点的图像值绘制每个图像。

package mapMaker;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class MapMakerWindow implements ActionListener, KeyListener {

//Create all the different objects (I like to organize them by what they are and what they do)
JFrame mainFrame = new JFrame("Dungeon Crawler Map Maker");

PaintPanel editorFrame = new PaintPanel("Editor", true, true, true, true);
JInternalFrame sliderFrame = new JInternalFrame("Scaler");
JInternalFrame blankFrame = new JInternalFrame("DO NOT USE");//this is used so that the other JIFs show correctly, for some reason the last one added to the mainFrame doesn't work properly

JPanel mainEP = new JPanel();
JPanel sliderPanel = new JPanel();

JMenuBar jBar = new JMenuBar();
JMenu toolsMenu = new JMenu("Tools");
JMenu fileMenu = new JMenu("File");
JMenuItem toggleBrushesFrame = new JMenuItem("Show Brushes Menu");
JMenuItem toggleToolsFrame = new JMenuItem("Show Tools Menu");
JMenuItem toggleEditorFrame = new JMenuItem("Show Editor Menu");

boolean showToolsFrame;
boolean showBrushesFrame;

static JSlider slider = new JSlider(0, 60, 10);

ChangeListener sizeAction = new ChangeListener() {
    public void stateChanged (ChangeEvent event) {
        PaintPanel.scale = slider.getValue();
        editorFrame.repaint();
        System.out.println("Changing: " + slider.getValue() + " Scale: " + PaintPanel.scale);
    }
};

public static void main(String args[]) {
    new MapMakerWindow();
}

public MapMakerWindow() {

    slider.setVisible(true);
    sliderPanel.add(slider);
    sliderFrame.add(sliderPanel);
    sliderFrame.addKeyListener(this);
    mainFrame.add(editorFrame);
    mainFrame.add(sliderFrame);
    mainFrame.add(blankFrame);
    mainFrame.addKeyListener(this);

    jBar.add(fileMenu);
    jBar.add(toolsMenu);
    toolsMenu.add(toggleToolsFrame);
    toolsMenu.add(toggleBrushesFrame);
    toolsMenu.add(toggleEditorFrame);
    toggleToolsFrame.addActionListener(this);
    toggleBrushesFrame.addActionListener(this);
    toggleEditorFrame.addActionListener(this);

    editorFrame.setSize(700, 450);
    sliderFrame.setSize(200, 80);
    //sliderFrame.setSize(1000, 100);
    mainFrame.setSize(750, 600);

    editorFrame.setLocation(15, 15);
    editorFrame.setVisible(true);

    slider.addChangeListener(sizeAction);

    sliderFrame.setLocation(editorFrame.getWidth() - sliderFrame.getWidth() + editorFrame.getX(), editorFrame.getY() + editorFrame.getHeight() + 5);
    sliderFrame.setVisible(true);

    mainFrame.setJMenuBar(jBar);
    mainFrame.setLocationRelativeTo(null); //puts the window in the middle of your screen
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e) { //all the clicking for the JMenuBar and it's items

}

@Override
public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_ESCAPE) {
        System.exit(0);
    } else if (keyCode == KeyEvent.VK_A && e.isControlDown()) {//opens all the JIF's for ease of use for now
        editorFrame.setLocation(15, 15);
        editorFrame.setVisible(true);
        System.out.println("PRESSED");
    } else if (keyCode == KeyEvent.VK_F) {
        System.out.println(slider.getValue());
    }
}

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyReleased(KeyEvent e) {
}

}

class PaintPanel extends JInternalFrame implements MouseListener, MouseMotionListener, MouseWheelListener {

static int sliderValue = MapMakerWindow.slider.getValue();
int[] gridSize = {100, 100};
int[] images = new int[gridSize[0] * gridSize[1]];
static int scale = sliderValue;
int xOffset = 0;
int yOffset = 0;
int xPressed = 0;
int yPressed = 0;
int dragXOff = 0;
int dragYOff = 0;
int color = 2;
/*Just pick any 3 images on your comp, it doesn't matter what the sizes are*/
File blank = new File("/Users/Calvin/Dropbox/src/mapMaker/blank.png");
File ground = new File("/Users/Calvin/Dropbox/src/mapMaker/ground.png");
File grass = new File("/Users/Calvin/Dropbox/src/mapMaker/grass.png");

BufferedImage blankImg;
Image blankResizedImg;
BufferedImage groundImg;
Image groundResizedImg;
BufferedImage grassImg;
Image grassResizedImg;

JPanel mainPanel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        try{
            blankImg = ImageIO.read(blank);
            blankResizedImg = ImageIO.read(blank);
            groundImg = ImageIO.read(ground);
            groundResizedImg = ImageIO.read(ground);
            grassImg = ImageIO.read(grass);
            grassResizedImg = ImageIO.read(grass);
        }catch(Exception e){
            System.out.println(e);
        }
        blankResizedImg = blankImg.getScaledInstance(scale, scale, Image.SCALE_FAST);
        groundResizedImg = groundImg.getScaledInstance(scale, scale, Image.SCALE_FAST);
        grassResizedImg = grassImg.getScaledInstance(scale, scale, Image.SCALE_FAST);

        super.paintComponent(g);
        for (int x = 0; x < gridSize[0] * scale; x += blankResizedImg.getWidth(this)){
            for (int y = 0; y < gridSize[1] * scale; y += blankResizedImg.getHeight(this)) {
                g.drawImage(getImage((x * 100 + y)/scale), x + xOffset + dragXOff, y + yOffset + dragYOff, groundResizedImg.getWidth(this), groundResizedImg.getHeight(this), this);
                //g.drawString((x * 100 + y)/scale + "", x + xOffset + dragXOff, y + yOffset + dragYOff);
            }
        }
        fixGrid();
    }
};

public Image getImage(int i){
    Image newImage = null;
        if(images[i] == 0){
            newImage = blankResizedImg;
        }else if(images[i] == 1){
            newImage = groundResizedImg;
        }else if(images[i] == 2){
            newImage = grassResizedImg;
        }
    return newImage;
}

public void writeImages() {
    for(int x = 0; x < images.length; x++) {
        if(color == 0){
            images[x] = 0;
        }else if(color == 1){
            images[x] = 1;
        }else if(color == 2){
            images[x] = 2;
        }
    }
}

public void setImage(int x, int y){
    images[(y * 100 + x)/scale] = 1;
    repaint();
}

public void fixGrid() {
    if (scale * gridSize[0] < getWidth()) {
        scale = (int) Math.ceil((double) getWidth() / (double) gridSize[0]);
    } else if (scale * gridSize[1] < getHeight()) {
        scale = (int) Math.ceil((double) getHeight() / (double) gridSize[1]);
    }
    if (xOffset < 0 && gridSize[0] * scale < getWidth()) {
        xOffset = 0;
    }
    if (gridSize[0] * scale + xOffset < getWidth()) {
        xOffset = getWidth() - gridSize[0] * scale;
    } 
    if (gridSize[1] * scale + yOffset < getHeight()) {
        yOffset = getHeight() - gridSize[1] * scale;
    }
    if(xOffset > 0){
        xOffset = 0;
    }
    if(yOffset > 0){
        yOffset = 0;
    }
    MapMakerWindow.slider.setValue(scale);
    repaint();
}

public PaintPanel(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) {
    this.setTitle(title);
    if (resizable == true) {
        setResizable(true);
    }
    if (closable == true) {
        setClosable(true);
    }
    if (maximizable == true) {
        setMaximizable(true);
    }
    if (iconifiable == true) {
        setIconifiable(true);
    }
    addMouseListener(this);
    addMouseMotionListener(this);
    addMouseWheelListener(this);
    writeImages();
    add(mainPanel);
}

@Override
public void mouseWheelMoved(MouseWheelEvent e) {
        int xChange = 1;
        int yChange = 1;
        int notches = e.getWheelRotation();
        scale -= notches;
        xChange *= (int) (e.getX() / scale);
        yChange *= (int) (e.getY() / scale);
        xOffset -= xChange;
        yOffset -= yChange;
        fixGrid();
}

@Override
public void mouseDragged(MouseEvent e) {
    if (SwingUtilities.isMiddleMouseButton(e)) {
        dragXOff = e.getX() - xPressed;
        dragYOff = e.getY() - yPressed;
        fixGrid();
    }
}

@Override
public void mouseMoved(MouseEvent e) {
}

@Override
public void mouseClicked(MouseEvent e) {
    setImage(e.getX(), e.getY());
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
    if (SwingUtilities.isMiddleMouseButton(e)) {
        xPressed = e.getX();
        yPressed = e.getY();
    }
}

@Override
public void mouseReleased(MouseEvent e) {
    if (SwingUtilities.isMiddleMouseButton(e)) {
        xOffset += dragXOff;
        yOffset += dragYOff;
        xPressed = 0;
        yPressed = 0;
        dragXOff = 0;
        dragYOff = 0;
        fixGrid();
    }
}
}

1 个答案:

答案 0 :(得分:2)

我自己,如果我想要一个网格来改变鼠标按下的图像,我会使用JLabel网格并简单地交换ImageIcons。例如:

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

import javax.swing.*;

@SuppressWarnings("serial")
public class GridExample extends JPanel {
   private Ground[][] groundMap = {
         { Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.WATER,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.WATER,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.DIRT,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT,
               Ground.DIRT, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.DIRT,
               Ground.WATER, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT,
               Ground.DIRT, Ground.WATER, Ground.WATER, Ground.WATER,
               Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.GRASS,
               Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.DIRT,
               Ground.DIRT, Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.GRASS,
               Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.DIRT,
               Ground.WATER, Ground.WATER, Ground.WATER },
         { Ground.GRASS, Ground.GRASS, Ground.GRASS, Ground.GRASS,
               Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.DIRT,
               Ground.DIRT, Ground.WATER, Ground.WATER }, };

   private JLabel[][] labelGrid = new JLabel[groundMap.length][groundMap[0].length];

   public GridExample() {
      setLayout(new GridLayout(groundMap.length, groundMap[0].length));
      for (int r = 0; r < labelGrid.length; r++) {
         for (int c = 0; c < labelGrid[r].length; c++) {
            labelGrid[r][c] = new JLabel();
            labelGrid[r][c].setIcon(groundMap[r][c].getIcon());
            add(labelGrid[r][c]);
         }
      }

      addMouseListener(new MyMouseListener());
   }

   private class MyMouseListener extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent mEvt) {
         Component comp = getComponentAt(mEvt.getPoint());
         for (int row = 0; row < labelGrid.length; row++) {
            for (int col = 0; col < labelGrid[row].length; col++) {
               if (labelGrid[row][col] == comp) {
                  Ground ground = groundMap[row][col];
                  int mapCode = ground.getValue();
                  mapCode++;
                  mapCode %= Ground.values().length;
                  groundMap[row][col] = Ground.values()[mapCode];
                  labelGrid[row][col].setIcon(groundMap[row][col].getIcon());
               }
            }
         }
      }
   }

   private static void createAndShowGui() {
      GridExample mainPanel = new GridExample();

      JFrame frame = new JFrame("GridExample");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum Ground {
   DIRT(0, new Color(205, 133, 63)), GRASS(1, new Color(0, 107, 60)), WATER(2,
         new Color(29, 172, 214));
   private int value;
   private Color color;
   private Icon icon;

   private Ground(int value, Color color) {
      this.value = value;
      this.color = color;

      icon = createIcon();
   }

   private Icon createIcon() {
      int width = 24;
      BufferedImage img = new BufferedImage(width, width,
            BufferedImage.TYPE_INT_ARGB);
      Graphics g = img.getGraphics();
      g.setColor(color);
      g.fillRect(0, 0, width, width);
      g.dispose();
      return new ImageIcon(img);
   }

   public int getValue() {
      return value;
   }

   public Color getColor() {
      return color;
   }

   public Icon getIcon() {
      return icon;
   }

   public static Ground getGround(int value) {
      for (Ground ground : Ground.values()) {
         if (ground.getValue() == value) {
            return ground;
         }
      }
      return null;
   }

}