This should do the job. It's not the best option, nor the one with the best performance, but it works.
// The main class which makes the frame and adds the necessary stuff
class Mainclass {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CPanel panel = new CPanel();
// I like colours
panel.setBackground(new Color(255,255,255,255));
frame.add(panel);
frame.addMouseListener(new Mouse(panel));
frame.setVisible(true);
}
}
// The MouseListener which checks if the mouse is clicked
class Mouse implements MouseListener {
CPanel panel;
public Mouse(CPanel panel) {
this.panel=panel;
}
@Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
boolean inside=false;
ArrayList<Integer> Ys = panel.coordinates.get(x);
if(Ys != null) {
if(panel.coordinates.get(x).contains(y)) {
inside=true;
}
}
if(inside) {
System.out.println("You clicked in the triangle");
} else {
System.out.println("You clicked out of the triangle");
}
}
@Override public void mousePressed (MouseEvent e) {}
@Override public void mouseReleased (MouseEvent e) {}
@Override public void mouseEntered (MouseEvent e) {}
@Override public void mouseExited (MouseEvent e) {}
}
// The panel
class CPanel extends JPanel {
public int minX=100;
public int maxX=200;
public int minY=100;
public int maxY=200;
// All the pixels in the triangle
HashMap<Integer, ArrayList<Integer>> coordinates = new HashMap<Integer, ArrayList<Integer>>();
public void paintComponent(Graphics G) {
super.paintComponent(G);
/** For that one downvoter: I made it G2D, even though it makes no difference **/
Graphics2D g = (Graphics2D) G;
// Drawing a centered triangle
int xCen=(int)Math.round((minX+maxX)/2.0);
// I like colours
g.setColor(new Color(0,0,255,128));
for(int y=0; y<=maxY-minY; y++) {
int x0=xCen-y;
int x1=xCen+y;
int y0=y+minY;
for(int x=x0; x<=x1; x++) {
// Adding all pixels in this row to 'coordinates'
ArrayList<Integer> Ys = coordinates.get(x);
if(Ys==null) {
coordinates.put(x, new ArrayList<Integer>());
Ys = coordinates.get(x);
}
Ys.add(y0);
coordinates.put(x, Ys);
}
// Draw the row
g.drawLine(x0,y0,x1,y0);
}
// Output the coordinates for debugging purposes
System.out.println(coordinates);
}
}
Again, if you want something with better performance, don't use this.