I am trying to implement Tetris in Swing, for that I am trying to draw rectangles adjacent to each, but the second rectangle is not coming adjacent to the first.
Also if getPreferredSize() returns anything less than 50,50 then nothing shows up in the screen. What is wrong in this code and how to paint adjacent rectangles.
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);
}
}