我正在尝试在 Swing 中实现俄罗斯方块,因为我试图绘制与每个矩形相邻的矩形,但第二个矩形不与第一个矩形相邻。
此外,如果 getPreferredSize() 返回小于 50,50 的值,则屏幕上不会显示任何内容。这段代码有什么问题以及如何绘制相邻的矩形。
public class Tetris extends JFrame
{
public Tetris(String string)
{
super(string);
}
public static void main(String[] args)
{
Tetris tetris = new Tetris("Tetris");
tetris.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
tetris.getContentPane().add(mainPanel);
tetris.setVisible(true);
tetris.setLocationRelativeTo(null);
tetris.pack();
tetris.setSize(500, 500);
tetris.setResizable(false);
tetris.paintBoard(mainPanel);
}
public void paintBoard(JPanel mainPanel)
{
Piece p1 = new Piece(10,10,50,50,Color.GREEN);
Piece p2 = new Piece(60,10,50,50,Color.RED);
mainPanel.add(p1);
mainPanel.add(p2);
}
}
public class Piece extends JComponent
{
private int X = 0;
private int Y = 0;
private int H = 0;
private int W = 0;
private Color c;
public Piece(int X, int Y, int W, int H, Color c)
{
this.X = X;
this.Y = Y;
this.W = W;
this.H = H;
this.c = c;
}
@Override
public void paintComponent(Graphics g)
{
g.setColor(c);
g.drawRect(X, Y, W, H);
g.fillRect(X, Y, W, H);
System.out.println("g.drawRect("+X+", "+Y+", "+W+", "+H+")");
}
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}