向GUI添加多个形状

时间:2018-11-27 17:45:23

标签: java swing user-interface

我目前正在尝试创建一个破砖游戏,但是我遇到了一些问题。

我目前有一个抽象的类形状以及用于正方形和圆形的方法来绘制游戏形状。但是在我的主要方法中,当我尝试添加形状时,它仅输出一个形状,因此在本例中,对于我的代码,它仅显示圆而不是桨。我想知道是否有人可以帮助我解决这个问题?

主要

在这种情况下,我添加新方块的行不起作用。

import javax.swing.*;
import java.awt.*;

public class Main {

public static void main(String[] args) {
    FilledFrame frame = new FilledFrame();

    frame.setSize(700, 600);
    frame.setResizable( false );
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setTitle("CE203_RegNo_1603977");
    frame.setVisible( true );

}



static class FilledFrame extends JFrame{


    public FilledFrame(){


        // left border
        JPanel leftBorder   = new JPanel();
        leftBorder.setSize(4, 700);
        leftBorder.setBackground(Color.BLACK);
        add(leftBorder, BorderLayout.WEST);

        // top border
        JPanel topBorder    = new JPanel();
        topBorder.setSize(700, 4);
        topBorder.setBackground(Color.BLACK);
        add(topBorder, BorderLayout.NORTH);

        //right border
        JPanel rightBorder  = new JPanel();
        rightBorder.setSize(4, 700);
        rightBorder.setBackground(Color.BLACK);
        add(rightBorder, BorderLayout.EAST);

        /*
        JPanel cenBorder = new JPanel();
        cenBorder.setSize(696, 696);
        cenBorder.setBackground(Color.blue);
        add(cenBorder, BorderLayout.CENTER);
        */


        // create paddle

        Square paddle       = new Square(100, 8, 310, 550, Color.BLUE);
        add(paddle, BorderLayout.SOUTH);


        // create ball
        Circle ball        = new Circle(20, 20, 120, 350, Color.YELLOW);
        add(ball, BorderLayout.CENTER);
    }

}


}

形状

import javax.swing.*;
import java.awt.*;

public abstract class Shape extends JPanel {

public int posX;
public int posY;
public Color color;


public Shape(int posX, int posY, Color color){
    this.posX   = posX;
    this.posY   = posY;
    this.color  = color;


}

public abstract void paintComponent (Graphics g);

}

平方

import java.awt.*;

import java.awt.Color;

public class Square extends Shape {

protected int width;
protected int height;

public Square(int width, int height, int posX, int posY, Color color) {

    super(posX, posY, color);

    this.width  = width;
    this.height = height;

}


@Override
public void paintComponent (Graphics g) {
    g.setColor(color);
    g.fillRect(posX, posY, width, height);



}
}

圆圈

import java.awt.*;

public class Circle extends Shape {

protected int width;
protected int height;


public Circle(int width, int height, int posX, int posY, Color color) {
    super(posX, posY, color);

    this.width = width;
    this.height = height;


}

@Override
public void paintComponent(Graphics g) {

    g.setColor(color);
    g.fillOval(posX, posY, width, height);


}
}

0 个答案:

没有答案
相关问题