Hi,
I added a Canvas in a JFrame. By clicking a JButton
within the JFrame I want to access a method within the Canvas-Class.
Is there someone who can tell me, why this does not work ?
Have a nice day, Guenter
------------my Code ------------------------
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyGrafik extends JFrame{
MyCanvas2 c1 = new MyCanvas2();
JButton btn1 = new JButton("ok");
ActionListener A1 = new ActionListener( ){
public void actionPerformed(ActionEvent evt){
doIt();
}
};
public void doIt(){
c1.zeichneGerade();
}
public MyGrafik(){
getContentPane().setLayout(null);
btn1.setBounds(300,10,50,30);
getContentPane().add(btn1);
c1.setBounds(200,100,300,200);
c1.setBackground(Color.yellow);
getContentPane().add(c1);
}
public static void main(String args[]){
JFrame MyGrafik = new MyGrafik();
MyGrafik.setSize(800,600);
MyGrafik.setVisible(true);
}
}
//------------class MyCanvas2 ---------
import java.awt.*;
public class MyCanvas2 extends Canvas{
public MyCanvas2(){
super();
}
public void zeichneGerade(){
Graphics g = getGraphics();
g.setColor(Color.red);
g.drawLine(10,10,60,60);
update(g);
}
}
Knute Johnson - 17 May 2006 18:46 GMT
> Hi,
>
[quoted text clipped - 56 lines]
>
> }
Guenter:
You've got a few problems going there Guenter. All drawing needs to be
done in the paint() or paintComponent() methods. Also you will have
problems mixing AWT and Swing components. If you are going to use a
JFrame use a JPanel. If you are using a Frame then you can use a Panel
or Canvas to draw on.
Here is a simple example of how to draw different things in the same
component and how to call methods on your objects.
import java.awt.*;
import java.awt.event.*;
public class test9 extends Frame {
public test9() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
final MyCanvas myc = new MyCanvas();
myc.setSize(100,100);
Button b = new Button("Draw");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
myc.set();
myc.repaint();
}
});
add(b,BorderLayout.WEST);
add(myc,BorderLayout.EAST);
pack();
setVisible(true);
}
class MyCanvas extends Canvas {
boolean isSet = false;
public MyCanvas() {
super();
}
public void set() {
isSet = true;
}
public void paint(Graphics g) {
if (isSet) {
g.setColor(Color.RED);
g.drawLine(0,getHeight()/2,getWidth(),getHeight()/2);
} else {
g.drawString("Not set yet!",10,getHeight()/2);
}
}
}
public static void main(String[] args) {
new test9();
}
}

Signature
Knute Johnson
email s/nospam/knute/
gzell@gmx.de - 17 May 2006 19:13 GMT
Hi Knute,
>....Here is a simple example of how to draw different things in the same
> component and how to call methods on your objects.
thank you for your quick and very informativly answer. Your input
was very helpful for me to do my next beginner steps...
Ciao, Guenter