我正在用Java实现一个demo paint应用程序。我现在能够绘制一个形状。当我再次尝试画画时,早期的形状消失了,一个新的形状出现了。 我使用BorderLayut.CENTER在内部框架上嵌入JPanel。
请帮我看看如何在这个内部框架中绘制多个形状。
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();
}
}
答案 0 :(得分:1)
Swing中的绘画是破坏性的,也就是说,每次调用paintComponent
时,都需要从头开始重绘整个组件状态。
最佳解决方案是生成List
Shape
个或绘制命令,您可以根据自己的要求调用/绘制/填充,每次
paintComponent
被称为
有关更多详情和想法,请参阅Incremental graphics in Swing
答案 1 :(得分:1)