Java - Show multiple canvases in a container
I am new to Java. I want to show multiple Canvas objects in one container. I don't want to use Swing components. Here is my code:
//===============================================================================================|
package main;
//===============================================================================================|
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//===============================================================================================|
public class Main {
//-------------------------------------------------------------------------------------------+
public Main() {
// Create a window to draw into:
Frame window = new Frame();
window.addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
window.setSize(600,400);
window.setVisible(true);
//
// Create a container for the MyCanvas instances:
Container container = new Container();
container.setSize(600,400);
container.setVisible(true);
window.add(container);
//
// Create 2 MyCanvas instances and add them to the container:
// Only the first one is showing.
MyCanvas canvas1 = new MyCanvas(75, 75);
container.add(canvas1);
MyCanvas canvas2 = new MyCanvas(135, 300);
container.add(canvas2);
}
//-------------------------------------------------------------------------------------------+
public static void main(String[] args) {
Main app = new Main();
}
//===============================================================================================|
public class MyCanvas extends Canvas {
int x2;
int y2;
public MyCanvas (int x2, int y2) {
this.setSize(600,400);
this.x2 = x2;
this.y2 = y2;
}
public void paint (Graphics g) {
g.drawLine(0, 0, this.x2, this.y2);
}
}
//===============================================================================================|
}
//===============================================================================================|
The Mycanvas class simply draws a line from (0,0) to the traversed coordinate. It works fine for the first instance of MyCanvas. However, if I add more instances, only the first MyCanvas is displayed. Can anyone tell me why this is, and what to do about it?
Thank!
+3
source to share