为什么paintComponent一一绘制所有形状?

时间:2019-04-26 17:36:43

标签: java swing sockets graphics

我正在使用套接字编程在Java gui上工作。我正在使用来自服务器的数据在客户端绘制图形。 首先,我将传入的数据推入数组中,然后尝试绘制它。我的问题是我想绘制列表中的所有形状,但是绘制后每个元素都会丢失。我想绘制所有我不想一一看到的形状。     我的代码在客户端;

  public void starteGame(String received) {

    Info.shapes = new ArrayList<Shape>();

    String[] mParsed = received.split(" ");
    int width = Integer.parseInt(mParsed[2]);
    int height = Integer.parseInt(mParsed[1]);
    int x1 = Integer.parseInt(mParsed[3]);
    int y1 = Integer.parseInt(mParsed[4]);
    int x2 = Integer.parseInt(mParsed[5]);
    int y2 = Integer.parseInt(mParsed[6]);
    int randomShape = Integer.parseInt(mParsed[7]);
    Color firstColor = new Color(Integer.parseInt(mParsed[8]), true);
    Color secondColor = new Color(Integer.parseInt(mParsed[9]), true);
    boolean cyclic = Boolean.parseBoolean(mParsed[10]);

    Shape shapeEx = new Shape(randomShape, x1, y1, x2, y2, firstColor, 
secondColor, cyclic);

    Info.shapes.add(shapeEx);

    showShapes(width, height);


}

public void showShapes(int height, int width) {

    JFrame frame = new JFrame();


        PanelDraw panel = new PanelDraw(width, height );

        frame.add(panel);

        frame.setSize(width, height);
        frame.setBackground(Color.RED);
        frame.setUndecorated(true);
        frame.setLocation(0, 400);
        frame.setVisible(true);


}

另一个功能是;

public class PanelDraw extends JPanel  {

private MyShape myShape;
int width;
int height;
// constructor, creates a panel with random shapes
public PanelDraw(int width, int height) {
    this.width = width;
    this.height = height;

    setBackground( Color.BLACK );   
} // end DrawPanel constructor

// end method

// for each shape array, draw the individual shapes
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    boolean filled = true;

    for (Shape shape : Info.shapes) {

        switch (shape.Type) {
            case 1:

                myShape = new MyPolygon(shape.X1, shape.Y1, shape.X2, shape.Y2, shape.FirstColor, filled);
                break;
            case 2:
                myShape = new MyRectangle(shape.X1, shape.Y1, shape.X2, shape.Y2, shape.FirstColor, filled);
                break;
            case 3:
                myShape = new MyOval(shape.X1, shape.Y1, shape.X2, shape.Y2, shape.FirstColor, filled);
                break;
        }

        Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D
        g2d.setPaint(new GradientPaint(shape.X1, shape.Y1, shape.FirstColor, shape.X2, shape.Y2,
                shape.SecondColor, shape.cyclic));
        myShape.draw(g2d);


    }


} // end method paintComponent

}

你能帮我吗?

0 个答案:

没有答案