使用在我上面的问题中找到的代码示例,我创建了几个带有不规则边缘的按钮,它们互锁,并且使用空布局来正确定位按钮。我遇到的问题是,尽管未在缓冲图像中的透明像素上检测到鼠标点击,但按钮仍采用矩形形状。这意味着稍后添加到面板的按钮会阻塞与其相邻的按钮部分。
我的问题是:有没有办法强制鼠标事件沿着 JButtons 的整个物理排列传播,直到它出现不透明像素,或者是否需要另一种解决方案?我看过涉及 Shape 的解决方案,但它们似乎非常昂贵,这就是为什么我想知道另一种方式。
我不太喜欢使用 JButtons,如果解决方案需要我离开它们,但我想找到一个便宜的解决方案,如果存在的话。
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class JButtonExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyButton button1 = null, button2 = null;
try {
button1 = new MyButton(ImageIO.read(new URL("https://dl.dropbox.com/s/dxbao8q0xeuzhgz/button1.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
button1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
MyButton mb = ((MyButton) me.getSource());
if (!isAlpha(mb.getIconImage(), me.getX(), me.getY()))
JOptionPane.showMessageDialog(frame, "You clicked button 1");
}
private boolean isAlpha(BufferedImage bufImg, int posX, int posY) {
int alpha = (bufImg.getRGB(posX, posY) >> 24) & 0xFF;
return alpha == 0 ? true : false;
}
});
button1.setBounds(10, 10, 72, 77);
try {
button2 = new MyButton(ImageIO.read(new URL("https://dl.dropbox.com/s/v16kyha0ojx1gza/button2.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
button2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
MyButton mb = ((MyButton) me.getSource());
if (!isAlpha(mb.getIconImage(), me.getX(), me.getY()))
JOptionPane.showMessageDialog(frame, "You clicked button 2");
}
private boolean isAlpha(BufferedImage bufImg, int posX, int posY) {
int alpha = (bufImg.getRGB(posX, posY) >> 24) & 0xFF;
return alpha == 0 ? true : false;
}
});
button2.setBounds(65, 0, 122, 69);
frame.getContentPane().setLayout(null);
frame.add(button1);
frame.add(button2);
frame.setSize(210, 130);
frame.setVisible(true);
}
});
}
}
class MyButton extends JButton {
BufferedImage icon;
MyButton(BufferedImage bi) {
this.icon = ((BufferedImage) bi);
setContentAreaFilled(false);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(icon.getWidth(), icon.getHeight());
}
public BufferedImage getIconImage() {
return icon;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(icon, 0, 0, null);
g.dispose();
}
}