繁体   English   中英

如何将MouseListener添加到GridLayout中的每个单独的元素?

[英]How to add a MouseListener to each individual element in a GridLayout?

我有一些代码创建一个彩色按钮网格,我想将鼠标侦听器附加到该网格上。 理想情况下,我希望程序每次鼠标进入这些按钮中的任何一个时都打印一行(例如,“已输入按钮!”)。

但是,我当前的代码仅在输入网格本身时才打印此消息。

我的代码在这里:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.net.URL;

public class ColorGrid implements MouseListener {

/*
    Frame holds the panel
    Panel holds the grid framework and the toolbar
*/
JFrame frame = new JFrame();
JLabel[][] grid;
JToolBar toolbar = new JToolBar("Test");
ButtonGroup bgroup = new ButtonGroup();
JPanel panel = new JPanel();

// Example strings for default button implementations - not needed
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";

// holds strings that point to URL of button elements
String[] buttonPics = {"images/circle_blue.png", "images/circle_green.png", "images/circle_orange.png", "images/circle_red.png", "images/circle_yellow.png"};
Random rand = new Random();

/*
    CONSTRUCTOR

    Add buttons to the toolbar
    Set layouts for the frame and panel
    Populate grid with icons (representing buttons)

*/
public ColorGrid(int width, int length) {

    addButtons(bgroup, toolbar);

    frame.setLayout(new BorderLayout());
    panel.setLayout(new GridLayout(width, length));

    grid = new JLabel[width][length];

    panel.addMouseListener(this);

    for(int y=0; y<length; y++){

        for(int x=0; x<width; x++){

            int randomColor = rand.nextInt(5);
            ImageIcon icon = createImageIcon(buttonPics[randomColor]);

            grid[x][y] = new JLabel(icon);
            panel.add(grid[x][y]);

        }
    }

    frame.add(toolbar, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true); 

}

/*
    Finds URL for button images and returns it
*/
ImageIcon createImageIcon(String path) {

    URL imgURL = ColorGrid.class.getResource(path);

    if (imgURL != null) 
        return new ImageIcon(imgURL);
    else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }

}

/*
    Adds buttons to the ButtonGroup and then add to Toolbar
*/
void addButtons(ButtonGroup bgroup, JToolBar toolbar) {
    JToggleButton button = null;

    //first button
    button = makeNavigationButton("circle_blue", PREVIOUS, "Back to previous something-or-other", "Previous");
    bgroup.add(button);
    toolbar.add(button);

    //second button
    button = makeNavigationButton("circle_Green", UP, "Up to something-or-other", "Up");
    bgroup.add(button);
    toolbar.add(button);

    //third button
    button = makeNavigationButton("circle_orange", NEXT, "Forward to something-or-other", "Next");
    bgroup.add(button);
    toolbar.add(button);

    button = makeNavigationButton("circle_red", NEXT, "Forward to something-or-other", "Next");
    bgroup.add(button);
    toolbar.add(button);

    button = makeNavigationButton("circle_yellow", NEXT, "Forward to something-or-other", "Next");
    bgroup.add(button);
    toolbar.add(button);

}

/*
    Called by the addButtons() method.

    Handles main button creation logic - finds the image and sets the command to the default string commands
*/
JToggleButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {
    //Look for the image.
    String imgLocation = "images/"
                         + imageName
                         + ".png";
    URL imageURL = ColorGrid.class.getResource(imgLocation);

    //Create and initialize the button.
    JToggleButton button = new JToggleButton();
    button.setActionCommand(actionCommand);
    button.setToolTipText(toolTipText);

    if (imageURL != null) {                      //image found
        button.setIcon(new ImageIcon(imageURL, altText));
    } else {                                     //no image found
        button.setText(altText);
        System.err.println("Resource not found: "
                           + imgLocation);
    }

    return button;
}

public void mouseEntered(MouseEvent e) {

    JPanel panel = (JPanel) getComponentAt(e.getPoint());

    if (panel != null) {
        System.out.println("Button entered!");
    }
}

public void mousePressed(MouseEvent e) {
    System.out.println("Mouse pressed!");
}

public void mouseReleased(MouseEvent e) {
    System.out.println("Mouse released!");
}

public void mouseExited(MouseEvent e) {
    System.out.println("Mouse exited!");
}

public void mouseClicked(MouseEvent e) {
    System.out.println("Mouse clicked!");
}


public static void main(String[] args) {
    new ColorGrid(4,4);//makes new ButtonGrid with 2 parameters
}

}

我怎样才能解决这个问题?

我不确定您的意思是“按钮”,因为添加到GridLayout的唯一内容就是JLabel s。

但基本上,您需要为每个组件分别注册一个MouseListener ,例如...

for(int y=0; y<length; y++){

    for(int x=0; x<width; x++){

        int randomColor = rand.nextInt(5);
        ImageIcon icon = createImageIcon(buttonPics[randomColor]);

        grid[x][y] = new JLabel(icon);
        grid[x][y].addMouseListener(this);
        panel.add(grid[x][y]);

    }
}

您还应该删除panel.addMouseListener(this); 致电,因为这可能只会混淆问题...

如果要测试鼠标是否输入了按钮,请将ChangeListener添加到按钮的ButtonModel并测试isRollover()

你做得好

panel.addMouseListener(this);

尝试将其更改为

button.addMouseListener(this); 

addButtons方法中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM