Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The overall problem is a Swing Layout issue. Your mainPanel JPanel has a default layout, FlowLayout, that attempts to arrange each thing (Piece) that you add to it. Each Piece's paintComponent will only control painting itself, not on the overall mainPanel. So your Pieces are not being painted relative to the overall mainPanel.</p> <p>Something Like:</p> <pre><code>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; 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(); mainPanel.setLayout(new BorderLayout()); tetris.getContentPane().setLayout(new BorderLayout()); tetris.getContentPane().add(mainPanel, BorderLayout.CENTER); tetris.setLocationRelativeTo(null); tetris.pack(); tetris.setSize(500, 500); tetris.setResizable(false); tetris.setVisible(true); 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); Board board = new Board(); board.addPiece(p1); board.addPiece(p2); mainPanel.add(board, BorderLayout.CENTER); } private class Board extends JComponent { private List&lt;Piece&gt; pieces = new ArrayList&lt;Piece&gt;(); public void addPiece(Piece piece) { pieces.add(piece); } @Override public void paintComponent(Graphics g) { for(Piece piece : pieces) { g.setColor(piece.c); g.drawRect(piece.X, piece.Y, piece.W, piece.H); g.fillRect(piece.X, piece.Y, piece.W, piece.H); } } } private class Piece { 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; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload