我正在用 Java 实现一个演示绘画应用程序。我现在可以绘制一个形状。当我再次尝试绘制时,之前的形状消失了,出现了一个新的形状。我将 JPanel 嵌入到带有 BorderLayut.CENTER 的内部框架上。
请帮助我如何在这个内部框架中绘制多个形状。
public class InternalFrame extends JInternalFrame{
public InternalFrame(String string, boolean b, boolean c, boolean d,
boolean e) {
super(string,b,c,d);
MyShape myShape2 = new MyRectangle();
add(myShape2, BorderLayout.NORTH);
MyShape myShape1 = new MyCircle();
add(myShape1, BorderLayout.SOUTH);
}
}
public class MyRectangle extends MyShape {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int temp = 0;
System.out.println("rect");
// draw circle
g.setColor(Color.RED);
g.fillRect(startX, startY, endX - startX, endY - startY);
g.setColor(Color.GREEN);
g.drawRect(startX, startY, endX - startX, endY - startY);
}
}
public abstract class MyShape extends JPanel {
protected int startX;
protected int startY;
protected int endX;
protected int endY;
MyShape(){
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
// To initialisise the starting and ending point
setStart(0,0);
setEnd(0,0);
// To set starting point
setStart(event.getX(), event.getY());
}
// handle mouse release event
public void mouseReleased(MouseEvent event) {
setEnd(event.getX(),event.getY());
}
});
}
public void setStart(int x, int y) {
startX = x;
startY = y;
repaint();
}
public void setEnd(int x, int y){
endX = x;
endY = y;
repaint();
}
}