有幾個選項。
使用在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