Java 在JPanel中添加鼠标单击图像

Java 在JPanel中添加鼠标单击图像,java,swing,graphics,paintcomponent,Java,Swing,Graphics,Paintcomponent,我第一次和Swing一起工作,遇到了一些问题。我有一个JFrame,它被分成四个JPanel。JFrame上有一个鼠标听筒,它的动作如下 单击时,如果单击位于左侧栏内,则确定正在选择13个图标中的哪一个。如果单击位于右侧的“游戏窗格”内&已选择图标,请将其放置在单击的位置 这是在这里完成的 @Override public void mouseClicked(MouseEvent event) { // TODO Auto-generated method stub xPos =

我第一次和Swing一起工作,遇到了一些问题。我有一个JFrame,它被分成四个JPanel。JFrame上有一个鼠标听筒,它的动作如下

单击时,如果单击位于左侧栏内,则确定正在选择13个图标中的哪一个。如果单击位于右侧的“游戏窗格”内&已选择图标,请将其放置在单击的位置

这是在这里完成的

@Override
public void mouseClicked(MouseEvent event) {
    // TODO Auto-generated method stub
    xPos = event.getX();
    yPos = event.getY()-25;
    //If click is inside tool bar
    if(xPos<=75){
        if(yPos>-1 && yPos<48)
            //First tool image
              image = new ImageIcon(getClass().getResource(_image path_)).getImage();
        else if(yPos>=48 && yPos<96)
            //Second tool image
              image = new ImageIcon(getClass().getResource(_image path_)).getImage();
        else if(yPos>=96 && yPos<144)
            //Third tool image
              image = new ImageIcon(getClass().getResource(_image path_)).getImage();
        else if(yPos>=144 && yPos<192)
            //Fourth tool image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=192 && yPos<240)
            //Fifth tool image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=240 && yPos<288)
            //Sixth tool image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=288 && yPos<336)
            //Seventh tool image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=336 && yPos<384)
            //First NPC image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=384 && yPos<432)
            //second NPC image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=432 && yPos<480)
            //Third NPC image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=480 && yPos<528)
            //First Decoration image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=528 && yPos<576)
            //Second Decoration image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
        else if(yPos>=576 && yPos<=625)
            //Third Decoration image
              image = new ImageIcon(getClass().getResource(imagepath)).getImage();
    }
    //If click is within Game Pane
    else if (xPos>75 && yPos<625){
        //A tool has been selected
        if(image!=null){
            placedTool = this.image;
            this.image = null;
            placeable = true;
        }
    }
    //An image and location on the game pane has been selected
    if(placeable && this.image==null){
        ImageInfo newImg = new ImageInfo(xPos, yPos, image);
        gamePane.additions.add(newImg);
        gamePane.repaint();
        System.out.println("IMAGE PLACED @ " + xPos + ", " + yPos);
        placeable = false;
    }

    System.out.println("CLICK: (" + xPos + "," + yPos +")");
}
其中加法的定义如下

列表添加=新的ArrayList()

ImageInfo类只包含一个图像,一个x坐标和一个y坐标

public class ImageInfo {
private int x;
private int y;
private Image image;

public int getX() {
    return x;
}

public int getY() {
    return y;
}

public Image getImage() {
    return image;
}

public ImageInfo(int x, int y, Image image) {
    super();
    this.x = x;
    this.y = y;
    this.image = image;
}

}
固定的:

谢谢你,mKorbel。通过定义mouseClicked方法之外的所有图像

Image tool1 = new ImageIcon(getClass().getResource(toolBar.TOOL1)).getImage();
Image tool2 = new ImageIcon(getClass().getResource(toolBar.TOOL2)).getImage();
Image tool3 = new ImageIcon(getClass().getResource(toolBar.TOOL3)).getImage();
Image tool4 = new ImageIcon(getClass().getResource(toolBar.TOOL4)).getImage();
Image tool5 = new ImageIcon(getClass().getResource(toolBar.TOOL5)).getImage();
Image tool6 = new ImageIcon(getClass().getResource(toolBar.TOOL6)).getImage();
Image tool7 = new ImageIcon(getClass().getResource(toolBar.TOOL7)).getImage();
Image npc1 = new ImageIcon(getClass().getResource(toolBar.NPC1)).getImage();
Image npc2 = new ImageIcon(getClass().getResource(toolBar.NPC2)).getImage();
Image npc3 = new ImageIcon(getClass().getResource(toolBar.NPC3)).getImage();
Image decor1 = new ImageIcon(getClass().getResource(toolBar.DECOR1)).getImage();
Image decor2 = new ImageIcon(getClass().getResource(toolBar.DECOR2)).getImage();
Image decor3 = new ImageIcon(getClass().getResource(toolBar.DECOR3)).getImage();
执行mouseClicked函数,如

@Override
public void mouseClicked(MouseEvent event) {
    // TODO Auto-generated method stub
    xPos = event.getX();
    yPos = event.getY()-25;
    //If click is inside tool bar
    if(xPos<=75){
        if(yPos>-1 && yPos<48)
            //First tool image
              image = tool1;
        else if(yPos>=48 && yPos<96)
            //Second tool image
              image = tool2;
        else if(yPos>=96 && yPos<144)
            //Third tool image
              image = tool3;
        else if(yPos>=144 && yPos<192)
            //Fourth tool image
              image = tool4;
        else if(yPos>=192 && yPos<240)
            //Fifth tool image
              image = tool5;
        else if(yPos>=240 && yPos<288)
            //Sixth tool image
              image = tool6;
        else if(yPos>=288 && yPos<336)
            //Seventh tool image
              image = tool7;
        else if(yPos>=336 && yPos<384)
            //First NPC image
              image = npc1;
        else if(yPos>=384 && yPos<432)
            //second NPC image
              image = npc2;
        else if(yPos>=432 && yPos<480)
            //Third NPC image
              image = npc3;
        else if(yPos>=480 && yPos<528)
            //First Yard Decoration image
              image = decor1;
        else if(yPos>=528 && yPos<576)
            //Second Yard Decoration image
              image = decor2;
        else if(yPos>=576 && yPos<=625)
            //Third Yard Decoration image
              image = decor3;
    }
    //If click is within Game Pane
    else if (xPos>75 && yPos<625){
        //A tool has been selected
        if(image!=null){
            placedTool = this.image;
            this.image = null;
            placeable = true;
        }
    }

    if(placeable && this.image==null){
        GamePiece newImg = new GamePiece(placedTool, xPos, yPos);
        gamePane.additions.add(newImg);
        gamePane.repaint();
        System.out.println("IMAGE PLACED @ " + xPos + ", " + yPos);
        placeable = false;
    }

    System.out.println("CLICK: (" + xPos + "," + yPos +")");
}
@覆盖
公共void mouseClicked(MouseEvent事件){
//TODO自动生成的方法存根
xPos=event.getX();
yPos=event.getY()-25;
//如果单击位于工具栏内
如果(xPos-1&&yPos=48&&yPos=96&&yPos=144&&yPos=192&&yPos=240&&yPos=288&&yPos=336&&yPos=384&&yPos=432&&yPos=480&&yPos=528&&yPos=576&&yPos=75&&yPos这看起来可疑:

if(placeable && this.image==null){
您没有在方法中声明
image
,因此它与
this.image
相同,因此只有当
image==null
时,才会运行添加代码。您的意思可能是:

if (placeable && this.image != null) {
(我不知道可放置的
的目的,所以我保留了原样)

只有一个注释

  • 发布一个简短的可运行、可编译的

  • 为什么有
    yPos=event.getY()-25;
    what逻辑表示-25处的
    整数

  • 将所有
    ImageIcons
    存储在局部变量中,将那些
    ImageIcons
    存储在任何数组或
    List
    中(如果存在固定逻辑而不是get坐标),然后加载
    image=new ImageIcon(getClass().getResource(
    paintComponent
    中绘制,在运行时不提供任何
    文件IO


    • 创建由
      GridLayout
      铺设的
      JLabel
      网格,将
      MouseListener
      添加到每个
      JLabel
      s,更改
      JLabel.setIcon(myImageIcon)
      中的
      鼠标事件,我缺少的其余逻辑没有SSCCE
    比如说

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    
    public class ChessBoard extends JFrame {
    
        private JFrame frame = new JFrame();
        private JPanel panel = new JPanel();
        private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
        private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
        private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
        private Icon questnIcon = UIManager.getIcon("OptionPane.questionIcon");
        private JButton button = new JButton("Reset my board");
    
        public ChessBoard() {
            panel.setLayout(new GridLayout(8, 8, 0, 0));
            for (int i = 0; i < 64; i++) {
                final JLabel label = new JLabel();
                label.setIcon(errorIcon);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == MouseEvent.BUTTON3) {
                            label.setIcon(infoIcon);
                        } else {
                            label.setIcon(warnIcon);
                        }
                    }
    
                    @Override
                    public void mouseEntered(MouseEvent me) {
                        label.setIcon(questnIcon);
                    }
                });
                panel.add(label);
            }
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (Component c : panel.getComponents()) {
                        if (c instanceof JLabel) {
                            JLabel label = (JLabel) c;
                            label.setIcon(errorIcon);
                        }
                    }
                }
            });
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(panel);
            frame.add(button, BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new ChessBoard();
                }
            });
        }
    }
    
    导入java.awt.BorderLayout;
    导入java.awt.Component;
    导入java.awt.GridLayout;
    导入java.awt.event.ActionEvent;
    导入java.awt.event.ActionListener;
    导入java.awt.event.MouseAdapter;
    导入java.awt.event.MouseEvent;
    导入javax.swing.Icon;
    导入javax.swing.JButton;
    导入javax.swing.JFrame;
    导入javax.swing.JLabel;
    导入javax.swing.JPanel;
    导入javax.swing.UIManager;
    公共类棋盘扩展JFrame{
    私有JFrame=新JFrame();
    private JPanel panel=new JPanel();
    私有图标errorIcon=UIManager.getIcon(“OptionPane.errorIcon”);
    私有图标infoIcon=UIManager.getIcon(“OptionPane.informationIcon”);
    私有图标warnIcon=UIManager.getIcon(“OptionPane.warningIcon”);
    私有图标questnIcon=UIManager.getIcon(“OptionPane.questionIcon”);
    私有JButton按钮=新JButton(“重置我的板”);
    公共棋盘(){
    panel.setLayout(新的GridLayout(8,8,0,0));
    对于(int i=0;i<64;i++){
    最终JLabel标签=新的JLabel();
    label.setIcon(错误图标);
    label.addMouseListener(新的MouseAdapter(){
    @凌驾
    公共无效mouseClicked(MouseEvent e){
    如果(例如getButton()==MouseEvent.BUTTON3){
    label.setIcon(信息图标);
    }否则{
    label.setIcon(警告图标);
    }
    }
    @凌驾
    公共无效mouseenterned(MouseEvent me){
    标签.设置图标(questnIcon);
    }
    });
    面板。添加(标签);
    }
    addActionListener(新建ActionListener()){
    @凌驾
    已执行的公共无效操作(操作事件e){
    对于(组件c:panel.getComponents()){
    if(JLabel的c实例){
    JLabel标签=(JLabel)c;
    label.setIcon(错误图标);
    }
    }
    }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    框架。添加(面板);
    框架。添加(按钮,边框布局。南);
    frame.pack();
    frame.setVisible(true);
    }
    公共静态void main(字符串[]args){
    invokeLater(new Runnable()){
    @凌驾
    公开募捐{
    新棋盘();
    }
    });
    }
    }
    
    多亏@MadProgrammer提供了这段代码,他帮了我(这意味着他做了一切)

    您可以查看他在此处发布的确切答案:

    我不认为image==null真的是必要的,因为image被设置为null,而placeable被设置为true。我这样做只是出于预防。很抱歉,这有点让人困惑。但主要的问题是,我不能用添加的图像在背景图像上重新绘制。@user2307421我的意思是,代码导致图像永远不会被删除添加到
    gamePane.additions
    ,因为这是执行添加的块上的条件。我正在处理SSCE。但是为了回答第二点,我不确定为什么,但对于MouseListener,所有Y值都偏移了25。当我单击窗口最顶端的点时,它给出了25而不是0,所以我只是减去了这个偏移t、 可能重复的
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    
    public class ChessBoard extends JFrame {
    
        private JFrame frame = new JFrame();
        private JPanel panel = new JPanel();
        private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
        private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
        private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
        private Icon questnIcon = UIManager.getIcon("OptionPane.questionIcon");
        private JButton button = new JButton("Reset my board");
    
        public ChessBoard() {
            panel.setLayout(new GridLayout(8, 8, 0, 0));
            for (int i = 0; i < 64; i++) {
                final JLabel label = new JLabel();
                label.setIcon(errorIcon);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == MouseEvent.BUTTON3) {
                            label.setIcon(infoIcon);
                        } else {
                            label.setIcon(warnIcon);
                        }
                    }
    
                    @Override
                    public void mouseEntered(MouseEvent me) {
                        label.setIcon(questnIcon);
                    }
                });
                panel.add(label);
            }
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (Component c : panel.getComponents()) {
                        if (c instanceof JLabel) {
                            JLabel label = (JLabel) c;
                            label.setIcon(errorIcon);
                        }
                    }
                }
            });
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(panel);
            frame.add(button, BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new ChessBoard();
                }
            });
        }
    }
    
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.sound.sampled.*;
    import javax.swing.*;
    
    
    import  sun.audio.*;
    
    public class SHR {
    
        public static void main(String[] args) {
            new SHR();
        }
    
        public SHR() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("To Battle");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new ToBattle());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class ToBattle extends JPanel {
    
            private BufferedImage image;
            private Point drawPoint;
    
            public ToBattle() {
                try {
                    image = ImageIO.read(getClass().getResource("SilverHandRecruit.png"));
                    addMouseListener(new MouseAdapter() {
    
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            drawPoint = new Point(e.getPoint());
    
                            repaint();
                        }
    
                    });
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                if (drawPoint != null) {
                    g2d.drawImage(image, drawPoint.x - 100, drawPoint.y - 100, this);
                }
                g2d.dispose();
            }
    
        }
    
    }