I'm trying to create a program that will draw an equilateral triangle with an oval at the center point when the mouse is pressed, and while the mouse is being dragged, the triangle will redraw itself so that the triangle remains equilateral regardless of where the mouse is (the mouse acts as one of the corners of the triangle). I have the following code so far.
public class EquilateralRubberBand extends JFrame {
/**
*
*/
public EquilateralRubberBand() {
super("Equilateral Triangle Rubber Band");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.white);
setContentPane(new DrawTrianglePanel());
setSize(400, 400); // you can change this size but don't make it HUGE!
setVisible(true);
}
/**
*
*/
private class DrawTrianglePanel extends JPanel implements MouseListener,
MouseMotionListener {
final float dash[] = { 5.0f };
final BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 3.0f, dash, 0.0f);
final BasicStroke solid = new BasicStroke(1.0f);
Graphics2D g2;
/**
*/
public DrawTrianglePanel() {
addMouseListener(this);
addMouseMotionListener(this);
}
/**
*
* @param g the graphics context with which we paint into.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
public void mousePressed(MouseEvent e) {
Point pressPoint = e.getPoint();
g2.setColor(Color.RED);
g2.fillOval(pressPoint.x, pressPoint.y, 100, 100);
g2.setColor(Color.BLUE);
g2.drawRect(pressPoint.x, pressPoint.y, 100, 100);
g2.drawString(("Dragging: " + pressPoint.x + ", " + pressPoint.y),
50, 25);
repaint();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
}
/**
*
*/
public static void main(String[] args) {
new EquilateralRubberBand();
}
};
Obviously this is nowhere near complete, but I just wanted to be able to test what I had done initially to make sure I was on the right track. So I wrote the code to draw the oval and the corner that the mouse will drag, as well as a string that tracks the coordinates of the mouse. However, when I open the panel and press the mouse to do this initial stuff, nothing happens. I'm sure I've added the mouse listeners correctly, and the frame opens up when I try to run the program. I tried a simple setBackground() in the mouseEntered() portion to make sure I had added the listeners and frame components correctly. It works, so the issue must be with the code I've written in the mousePressed method. I'm not sure where I've gone wrong though. Any help would be appreciated.