gpt4 book ai didi

java - 在内部框架中绘制多个形状(Jpanels)

转载 作者:行者123 更新时间:2023-12-02 06:43:03 24 4
gpt4 key购买 nike

我正在用 Java 实现一个演示绘画应用程序。我现在可以绘制单个形状。当我再次尝试绘制时,先前的形状消失了,并且出现了新的形状。我使用 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();
}




}

最佳答案

在 Swing 中绘制是破坏性的,也就是说,每次调用 paintComponent 时,您都需要从头开始重新绘制整个组件状态。

最好的解决方案是生成 Shape 或绘制命令的 List,您每次都可以根据您的要求调用/绘制/填充这些命令paintComponent 被调用

参见Incremental graphics in Swing了解更多细节和想法

关于java - 在内部框架中绘制多个形状(Jpanels),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com