Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 更改我单击的图像_Java_Swing_Awt_Mouselistener - Fatal编程技术网

Java 更改我单击的图像

Java 更改我单击的图像,java,swing,awt,mouselistener,Java,Swing,Awt,Mouselistener,我有一个可运行的代码,当运行时它不能正常工作 当您在编辑器框架内单击时,应该将您单击的图像更改为其他图像 图像的更改发生在setImage()中 int数组图像仅存储0、1或2 在绘制paintComponent中的图像时使用的getImage(),读取int数组图像,并根据特定点的图像值绘制每个图像 package mapMaker; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEv

我有一个可运行的代码,当运行时它不能正常工作

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

图像的更改发生在
setImage()

int数组图像
仅存储
0
1
2

在绘制
paintComponent
中的图像时使用的
getImage()
,读取
int数组图像
,并根据特定点的图像值绘制每个图像

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();
    }
}
}
包映射器;
导入java.awt.Graphics;
导入java.awt.Image;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.KeyEvent;
导入java.awt.event.KeyListener;
导入java.awt.event.MouseEvent;
导入java.awt.event.MouseListener;
导入java.awt.event.MouseMotionListener;
导入java.awt.event.mouseweelEvent;
导入java.awt.event.MouseWheelListener;
导入java.awt.image.buffereImage;
导入java.io.File;
导入javax.imageio.imageio;
导入javax.swing.*;
导入javax.swing.event.ChangeEvent;
导入javax.swing.event.ChangeListener;
公共类MapMakerWindow实现ActionListener、KeyListener{
//创建所有不同的对象(我喜欢根据它们是什么和它们做什么来组织它们)
JFrame mainFrame=新的JFrame(“地下城爬虫地图生成器”);
PaintPanel editorFrame=新的PaintPanel(“编辑器”,真,真,真,真);
JInternalFrame滑块框架=新的JInternalFrame(“定标器”);
JInternalFrame blankFrame=new JInternalFrame(“请勿使用”);//使用此选项可以正确显示其他JIF,但由于某些原因,添加到大型机的最后一个JIF无法正常工作
JPanel mainEP=新的JPanel();
JPanel sliderPanel=新的JPanel();
JMenuBar jBar=新JMenuBar();
JMenu toolsMenu=新JMenu(“工具”);
JMenu fileMenu=新JMenu(“文件”);
JMenuItem toggleBrushesFrame=新JMenuItem(“显示笔刷菜单”);
JMenuItem toggleToolsFrame=新的JMenuItem(“显示工具菜单”);
JMenuItem toggleEditorFrame=新的JMenuItem(“显示编辑器菜单”);
布尔显示工具框架;
布尔显示框架;
静态JSlider滑块=新JSlider(0,60,10);
ChangeListener sizeAction=新的ChangeListener(){
公共无效状态已更改(ChangeEvent事件){
PaintPanel.scale=slider.getValue();
editorFrame.repaint();
System.out.println(“更改:“+slider.getValue()+”比例:“+PaintPanel.Scale”);
}
};
公共静态void main(字符串参数[]){
新MapMakerWindow();
}
公共mapperwindow(){
slider.setVisible(true);
sliderPanel.add(滑块);
添加(sliderPanel);
sliderFrame.addKeyListener(此);
mainFrame.add(editorFrame);
mainFrame.add(sliderFrame);
大型机。添加(空白帧);
mainFrame.addKeyListener(this);
jBar.add(文件菜单);
jBar.add(工具菜单);
添加(切换ToolsFrame);
toolsMenu.add(切换笔刷框架);
toolsMenu.add(切换编辑器框架);
toggleToolsFrame.addActionListener(此);
toggleBrushesFrame.addActionListener(此);
toggleEditorFrame.addActionListener(此);
editorFrame.setSize(700450);
滑块框架设置尺寸(200,80);
//滑块框架设置尺寸(1000100);
大型机。设置大小(750600);
editorFrame.setLocation(15,15);
editorFrame.setVisible(true);
slider.addChangeListener(sizeAction);
设置位置(editorFrame.getWidth()-sliderFrame.getWidth()+editorFrame.getX(),editorFrame.getY()+editorFrame.getHeight()+5);
sliderFrame.setVisible(true);
mainFrame.setJMenuBar(jBar);
主机设置位置相对(NULL);/ /将窗口置于屏幕中间。
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@凌驾
public void actionPerformed(ActionEvent e){//JMenuBar及其项的所有单击
}
@凌驾
按下公共无效键(按键事件e){
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_ESCAPE){
系统出口(0);
}else if(keyCode==KeyEvent.VK_A&&e.isControlDown()){//打开所有JIF以便现在使用
editorFrame.setLocation(15,15);
editorFrame.setVisible(true);
系统输出打印项次(“按下”);
}else if(keyCode==KeyEvent.VK\u F){
System.out.println(slider.getValue());
}
}
@凌驾
public void keyTyped(KeyEvent e){
}
@凌驾
公共无效密钥已释放(密钥事件e){
}
}
类PaintPanel扩展JInternalFrame实现MouseListener、MouseMotionListener、MouseWheelListener{
静态int sliderValue=MapMakerWindow.slider.getValue();
int[]gridSize={100100};
int[]images=newint[gridSize[0]*gridSize[1]];
静态整数比例=滑动值;
int xOffset=0;
int-yOffset=0;
int xPressed=0;
int yPressed=0;
int dragXOff=0;
int-dragYOff=0;
int color=2;
/*只需在你的comp上选择任意3张图片,大小不重要*/
File blank=新文件(“/Users/Calvin/Dropbox/src/mapMaker/blank.png”);
文件地面=新文件(“/Users/Calvin/Dropbox/src/mapMaker/ground.png”);
文件grass=新文件(“/Users/Calvin/Dropbox/src/mapMaker/grass.png”);
缓冲图像空白;
图像消隐;
缓冲图像背景img;
图像背景尺寸;
缓冲图像;
图像缩放DIMG;
JPanel mainPanel=newjpanel(){
@凌驾
公共组件(图形g){
试一试{
blankImg=图像读取(空白);
blankResizedImg=ImageIO.read(空白);
地面img=图像读取(地面);
groundResizedImg=图像IO.read(接地);
grassImg=图像读取(grass);
grassResizedImg=图像IO.read(草);
}捕获(例外e){
系统输出打印ln(e);
}
blankResizedImg=blankImg.getScaledInstance(scale,scale,Image.scale\u FAST);
groundResizedImg=groundImg.getScaledInstance(scale,scale,Image.scale\u FAST);
格拉斯雷斯迪姆
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;
   }

}