Hello, I'm making a program where when the user clicks inside of the polygon it'll display a message saying they clicked inside of it and a different message for when they click out of it, I've done this using an if statement. I just found out about the contains method today and tried using it within the if statement, but I don't believe it is working because it seems to ignore the first condition completely and just go for the else part so it always comes with the message that they clicked outside of it even if they are clicking in. I might try to do something different but I would like to know why its not working, could please someone tell me?
Edit: Sorry I forgot to mention that the program is also supposed to print the co-ordinates of where they clicked in the message too
Here is my code:
import javax.swing.* ; import java.awt.* ; import java.awt.event.* ; public class KanjiInterface extends JFrame { JMenuBar menuBar ; JMenu menuSession ; JMenuItem subNewGame, subLoadGame ; MyComponent graphArea ; Color x = Color.blue ; //Boolean inPoly = false ; int xco[]={100,150,50} ; int yco[]={100,150,150} ; Polygon poly = new Polygon(xco,yco,3) ; KanjiInterface(){ //Creates the window super("Kanji Game") ; setLocation( new Point(100, 100) ) ; //this.getContentPane().setBackground( Color.white ) ; setSize( 600, 600 ) ; setResizable( true ) ; //Creates the Menu Bar along with sub-menus menuBar = new JMenuBar() ; menuSession = new JMenu("Session") ; subNewGame = new JMenuItem("New Session") ; subLoadGame = new JMenuItem("Load Session") ; menuBar.add(menuSession) ; menuSession.add( subNewGame ) ; menuSession.add( subLoadGame ) ; this.setJMenuBar(menuBar) ; //Create Panel for graphics graphArea = new MyComponent() ; graphArea.setBackground(Color.WHITE) ; add(graphArea, BorderLayout.CENTER) ; setVisible( true ) ; //Adding listener this.addMouseListener(new MouseCatcher ()) ; } class MyComponent extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g) ; g.setColor(x) ; //poly.addPoint(100,100) ; //poly.addPoint(150,150) ; //poly.addPoint(50,150) ; g.fillPolygon(poly) ; } } public class MouseCatcher extends MouseAdapter { public void mouseClicked(MouseEvent e) { int xpos = e.getX(); int ypos = e.getY(); if(poly.contains(xpos,ypos)){ System.out.println("You clicked on "+xpos+","+ypos) ; x = Color.red ; //inPoly = true ; } /* if(inPoly){ System.out.println("You clicked on "+xpos+","+ypos) ; x = Color.red ; } */ else{ System.out.println("You didn't click on "+xpos+","+ypos) ; } repaint() ; } } }
Note: My main is in a different class (using Eclipse).