Reputation: 4359
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.event.*;
import java.awt.geom.*;
import java.util.*;
public class test extends JFrame implements ActionListener, MouseListener {
private Vector<String> vlist = new Vector<String> ();
private int mouseX, mouseY;
Canvas c = new Canvas();
public test () {
setSize(400,400);
addMouseListener(this);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test frame = new test();
//frame.setBackground(Color.yellow);
frame.setVisible(true);
}
});
}
public void actionPerformed(ActionEvent ae) {
}
@Override
public void paint(Graphics g) {
Shape circle = new Ellipse2D.Float(100f, 100f, 100f, 100f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
}
public void move() {
}
public void drawCircle(int x, int y) {
}
public void mouseClicked(MouseEvent e) {
repaint();
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
this.mouseX=e.getX();
this.mouseY=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
i want to write a testing program to learn the graphic programming in java. To run the above code, the circle is automatically drawn. Why the paint() method is auto executed? I the circle to be created when i clicked the mouse.
Upvotes: 0
Views: 1799
Reputation: 12706
Add an attribute to the class.
boolean draw;
Surround the code in the paint(...)
with
if (draw) {
// existing code
}
This will make the program draws only when draw
is true. Initially, it is false so it won't draw anything. The value attribute draw
will be true when the mouse is clicked.
public void mouseClicked(MouseEvent e) {
draw = true;
repaint();
}
Upvotes: 1
Reputation: 285403
The Swing paint manager calls the paint method when the JFrame is rendered. For more details on the inner workings of this, please see Painting in AWT and Swing.
To improve your program, you'll want to
Upvotes: 1
Reputation: 324118
You should NOT be overriding the paint() method of the JFrame to do custom painting.
You should override the paintComponent() method of a JPanel or JComponent and add that component to the JFrame.
Check out the Swing tutoria on Custom Painting for the basics.
Check out Painting in AWT and Swing for detailed information.
Upvotes: 0