Reputation: 23
in my class draw Shape i want to send parameter to method paint like
g.drawRect (a, b, 200, 200);
how can i implement my code
class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.drawRect (10, 10, 200, 200);
}
}
public class drawShape {
public drawShape(){
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
Upvotes: 0
Views: 1894
Reputation: 1032
The method paint
is called from EDT every time the component needs to be repainted. And parameters of drawing should be considered as the properties of the MyCanvas
.
For example:
class MyCanvas extends JComponent {
int a,b;
public void setProps(int a, int b) {
this.a=a; this.b=b;
repaint();//mark this component to be repainted
}
public void paint(Graphics g) {
super.paint(g);
g.drawRect (a, b, 200, 200);
}
static public void main(String args[]){
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
MyCanvas canvas=new MyCanvas();
canvas.setProps(20,40);
window.getContentPane().add(canvas);
window.setVisible(true);
}
}
Upvotes: 3