【发布时间】:2022-01-17 09:06:03
【问题描述】:
对于我正在学习和使用 Java Swing 的当前项目。我希望我的程序创建圆角矩形,我目前正在使用 Graphics。
我创建了一个JFrame 和一个菜单。两者都工作正常。当我单击菜单项“创建球体”时,您可以从ColorChooser 中选择一种颜色,定义名称、宽度、高度、x 和 y 位置。调用该方法后,我得到了我的 RoundedRectangle
当我想创建另一个时,它也可以,但是第一个消失了
调整框架大小后,第一个再次出现,但第二个正在消失。
代码:
JFrame:
public void createWindow() {
/** Frame */
this.setTitle("Diagram");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(700,500);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
我的对话框框架调用了createSphere 方法,在这里我创建了一个新的Sphere(即RoundedRectangle)并将其添加到我的框架中:
public void createSphere(String name, int width, int height, int x, int y, Color color) {
this.add(new Sphere(name, width, height, x, y, color));
this.validate();
}
球类:
public class Sphere extends JPanel {
private String name;
private int width;
private int height;
private int xPos;
private int yPos;
private Color color;
public Sphere(String name, int width, int height, int xPos, int yPos, Color color) {
this.name = name;
this.width = width;
this.height = height;
this.xPos = xPos;
this.yPos = yPos;
this.color = color;
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.drawRoundRect(this.xPos,this.yPos,this.width,this.height, 15, 15);
g.setColor(this.color);
g.fillRoundRect(this.xPos,this.yPos,this.width,this.height, 15, 15);
}
我希望我的程序创建几个 Sphere 对象。稍后,Sphere 对象也将包含几个较小的带有文本的Spheres。
【问题讨论】:
-
使
Sphere成为一个普通的Java getter/setter 类。创建一个扩展JPanel的DrawingPanel类。创建一个DrawingModel类作为一个普通的Java getter/setter 类,其中包含java.util.LIst的Sphere对象。编写DrawingPanel类以在paintComponent方法中绘制List的Sphere实例。 -
在绘制图形之前面板会被清除,因此您只能看到最后绘制的图形。请参阅Custom Painting Approaches,了解进行增量绘制的两种常用方法,看看哪种方法最能满足您的要求。
标签: java swing graphics2d