No image is displayed when I press the mouse. But the display on the command window shows that the mouse has been pressed and the coordinates where mouse was pressed.
Need help to display the image on mousePress event.
I tried to check if the display on the command window worked when mouse pressed. It did work. But when I tried to display the image, no image was displayed.
My java code appears below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class MouseListenerHandler extends Panel implements MouseListener {
BufferedImage[] image;
File input;
static int LastPressX, LastPressY ;
static JFrame frame;
Container pane;
static Panel panel;
Graphics g;
public void paint(Graphics g) {
g.drawImage(image[1],LastPressX, LastPressY,this);
}
MouseListenerHandler(){
try {
image = new BufferedImage[3];
input = new File("Z_DisplayedPic3.png");
image[1] = ImageIO.read(input);
}
catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
pane = frame.getContentPane();
pane.addMouseListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(375,450);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
int x = e.getClickCount();
System.out.println("You CLICKED the mouse " + x + " times.");
}
public void mouseEntered(MouseEvent e) {
pane.setBackground(Color.YELLOW);
}
public void mouseExited(MouseEvent e) {
pane.setBackground(Color.MAGENTA);
}
public void mousePressed(MouseEvent e) {
LastPressX = e.getX(); LastPressY = e.getY();
int a = e.getX();
int b = e.getY();
frame.repaint();
System.out.println("You have PRESSED the mouse at (" + a + "," + b + ")");
}
public void mouseReleased(MouseEvent e) {
int a = e.getX();
int b = e.getY();
System.out.println("You have RELEASED the mouse at (" + a + "," + b + ")");
}
public static void main(String args[]){
LastPressX = 0; LastPressY = 0;
frame = new JFrame();
new MouseListenerHandler();
}
}