For example, if the user clicks in the top-left element, program could print out, on the console, "Mouse" clicked in element 0,0". So far this is what I have done. the program compiles but most of the results given are incorrect which does not match with the number of rows and columns.
------------------------------------------------------------------------------------------------------------------------------------import java.awt.*; import java.awt.geom.*; import javax.swing.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; class GridPanel extends JPanel implements MouseListener { int numCols; int numRows; public void mouseReleased(MouseEvent event) { System.out.println("Mouse button is released"); } public void mousePressed(MouseEvent event) { System.out.println("Mouse button is pressed"); System.out.println("Mouse button is released"); } public void mouseClicked(MouseEvent event) { System.out.println("Mouse is clicked"); int x = event.getX(); int y = event.getY(); System.out.println("the x position is " + x); System.out.println("the y position is " + y); int numCols=5; int numRows=7; int ClickColIndex=numCols-1; int ClickRowIndex=numRows-1; int width = getWidth(); int height = getHeight(); System.out.println("width of pane= " + width); System.out.println("height of pane= " + height); ClickColIndex = (numCols * x)/(width); ClickRowIndex= (numRows * y)/(height); System.out.println ("Mouse clicked in element "+ClickRowIndex + ","+ ClickColIndex); } public void mouseEntered(MouseEvent event) { System.out.println("Mouse cursor entered the screen"); } public void mouseExited(MouseEvent event) { System.out.println("Mouse cursor exited the screen"); } public GridPanel(int nc, int nr) { addMouseListener(this); numCols = nc; numRows = nr; } Rectangle getRect(int thisCol, int thisRow) { if(thisCol <0 || thisRow < 0) return null; if(thisCol>=numCols || thisRow>=numRows) return null; int w = getWidth()/numCols; int h = getHeight()/numRows; int x = thisCol*w; int y = thisRow*h; Rectangle myRect = new Rectangle(x,y,w,h); return myRect; } public void paint(Graphics g) { g.setColor(Color.gray); g.fillRect(0,0,getWidth(), getHeight()); g.setColor(Color.black); Graphics2D g2 = (Graphics2D)g; for (int i = 0;i<numCols;i++) { for(int j = 0;j<numRows;j++) { Rectangle r = getRect(i,j); g2.draw(r); } } } public static void main(String[] args) { W2MouseEvents w = new W2MouseEvents(); w.setVisible(true); } }
import java.awt.*; import java.awt.geom.*; import javax.swing.*; public class W2MouseEvents extends JFrame { GridPanel myGridPanel; public static void main(String[] args) { W2MouseEvents w = new W2MouseEvents(); w.setVisible(true); } public W2MouseEvents() { setTitle("Workshop 2 (Mouse Events): starting code"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,220); setLocation(300,300); myGridPanel = new GridPanel(7, 5); add(myGridPanel); } }