我对Java编程很陌生。我开发了一个java应用程序,它在窗口框架上绘制形状(圆圈、线条、三角形等)。我定义了一个抽象类Shapes.java,以包含用于形状的框架:
public abstract class Shapes {
public abstract void draw(Graphics g);
}然后,定义了一些类,如圆、线、三角和矩形,这些类是从Shapes.java类扩展而来的。
public class Circle extends Shapes{
private int x;
private int y;
private int radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw(Graphics g) {
g.drawOval(x-radius,y-radius,radius * 2, radius *2);
}}在我的Picture.java类中,我确定一个JFrame并在其上添加形状:
public class Picture extends JFrame {
private static final long serialVersionUID = 1L;
private int width;
private int height;
private boolean isClear = false;
private ArrayList<Shapes> listShape = new ArrayList<Shapes>();
private class ShapesPanel extends JPanel{
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
return;
else
for (Shapes s : listShape)
s.draw(g);
}
public void add(Shapes s){
listShape.add(s);
}
public Picture(int width, int height, String title) throws HeadlessException {
ShapesPanel mypanel = new ShapesPanel();
add(mypanel);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.width = width;
this.height = height;
this.setTitle(title);
}
public void draw(){
setLocationRelativeTo(null);
setSize(width, height);
setVisible(true);
repaint();
}
void clear(){//clear the componets in the JPanel
this.setIsClear(true);
this.validate();
this.repaint();
}
private void setIsClear(boolean b) {
// TODO Auto-generated method stub
this.isClear = b;
}
}但是,当我在主类中调用clear()方法时,程序不能再次重新绘制新的形状。我怎么才能治好虫子?谢谢。
public class MyPic {
public static void main(String[] args){
Picture pic = new Picture(420, 300, "shape demo");
Circle c1 = new Circle(320,80,80);
Rectangle r1 = new Rectangle(100,100,100,100);
Triangle t1 = new Triangle(100,100,200,100,150,50);
Line l1 = new Line(0,205,400,50);
pic.add(c1);
pic.add(r1);
pic.add(t1);
pic.add(l1);
pic.clear();
pic.draw();
pic.add(l1);//add l1 again
}
}发布于 2020-05-27 08:26:40
好的,通过调用clear(),您将变量isClear设置为true。然后在你的paintComponent里你会说:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
return;这意味着‘如果isClear是真的,不要画任何东西’(事实上,您只需在clear()中将其设置为true )。所以,难怪。
无论如何,我认为在clear方法中,您可能希望执行listShape.clear()而不是设置布尔值。
https://stackoverflow.com/questions/62035870
复制相似问题