有几个选项。
使用在JPanel
一个MouseListener
直接一个简单而肮脏的方式将是直接添加MouseListener
到您推翻了paintComponent
方法JPanel
,并实现了一个mouseClicked
方法,检查该区域图像存在的位置已被点击。
一个例子是沿着线的东西:
class ImageShowingPanel extends JPanel {
// The image to display
private Image img;
// The MouseListener that handles the click, etc.
private MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Do what should be done when the image is clicked.
// You'll need to implement some checks to see that the region where
// the click occurred is within the bounds of the `img`
}
}
// Instantiate the panel and perform initialization
ImageShowingPanel() {
addMouseListener(listener);
img = ... // Load the image.
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
注释:ActionListener
不能添加到JPanel
,作为JPanel
本身不借给自己的作品被认为是“行动”。
创建JComponent
显示图像,并添加MouseListener
一个更好的办法是使JComponent
一个新的子类,其唯一目的是要显示的图像。 JComponent
应根据图像的大小自行调整,以便点击任何部分的JComponent
都可以被视为图像上的点击。再次,在JComponent
中创建一个MouseListener
以捕获点击。
class ImageShowingComponent extends JComponent {
// The image to display
private Image img;
// The MouseListener that handles the click, etc.
private MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Do what should be done when the image is clicked.
}
}
// Instantiate the panel and perform initialization
ImageShowingComponent() {
addMouseListener(listener);
img = ... // Load the image.
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
// This method override will tell the LayoutManager how large this component
// should be. We'll want to make this component the same size as the `img`.
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
}
1)对于绘制图像,只需要一个“JComponent”。 2)对于'JComponent'或'JPanel',重写'paintComponent(Graphics)'而不是'paint(Graphics)'3)不要尝试在paint方法中加载图像。将它加载到'init()'或构造过程中并将其作为类级属性存储。 4)'Toolkit'图像加载方法需要一个'MediaTracker'。使用'ImageIO.read(文件)'来保证图像被加载。 5)在'drawImage()'方法中为'this'交换'null'。 – 2011-04-30 06:13:16