我有以下疑问:是否可以使用鼠标侦听器使“鼠标左键单击事件”超出组件的限制?或者我应该用另一种方法试试这个?
我的问题如下。我正在创建一个适合我的项目的 WYSIWYG 面板。此面板与显示根据用户选择加载的图像的另一个面板是同级的。例如,我需要获取此图像的背景颜色。当点击任何颜色时,这将改变 WYSIWYG 面板的 bgcolor。我正在使用Robot
该类来获取像素的颜色,但这仅在图像和颜色选择器位于同一面板中时才有效,但它们不会。
更新:这段代码就是我的意思。大型机有两个独立的 JFrame。我需要通过单击 MouseColorPane 来获取 ImageLoader 上图像的 rgb 颜色。在这种情况下,Robot 只能获取 JLabel 的黑色边框。
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class WhatsMyColor {
public static void main(String[] args) throws IOException {
new WhatsMyColor();
}
public WhatsMyColor() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
final MouseColorPane mcp = new MouseColorPane();
frame.add(mcp,BorderLayout.CENTER);
ImageLoader il = new ImageLoader();
frame.add(il,BorderLayout.NORTH);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception exp) {
exp.printStackTrace();
}
}
});
}
public class ImageLoader extends JPanel {
ImageLoader(){
BufferedImage img = null;
try {img = ImageIO.read(new File("src/monkey-icon128.png"));} catch (IOException e1) {e1.printStackTrace();}
add(new JLabel (new ImageIcon (img)));
BufferedImage img2 = null;
try {img2 = ImageIO.read(new File("src/monkey-icon128.png"));} catch (IOException e1) {e1.printStackTrace();}
add(new JLabel (new ImageIcon (img2)));
}
}
public class MouseColorPane extends JPanel {
private Robot robot;
private JLabel color;
public MouseColorPane() throws AWTException {
setLayout(new GridBagLayout());
color = new JLabel();
color.setBorder(BorderFactory.createLineBorder(Color.black));
color.setPreferredSize(new Dimension(100,100));
color.setFocusable(false);
color.setOpaque(true);
color.setFocusTraversalPolicyProvider(false);
color.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
PointerInfo pi;
pi = MouseInfo.getPointerInfo();
updateColor(pi.getLocation());
}
});
add(color);
robot = new Robot();
setVisible(true);
}
protected void updateColor(Point p) {
Color pixelColor = robot.getPixelColor(p.x, p.y);
color.setBackground(pixelColor);
}
}
}