我想在Swing中实现俄罗斯方块,因为我试图绘制每个矩形相邻的矩形,但第二个矩形不会与第一个矩形相邻。如何在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);
}
}
无论什么问题,不使用LayoutManager是_解决方案 – kleopatra 2013-03-12 11:30:56