Jframe的contentPane默认使用BorderLayout。当您向其添加一个Square时,默认情况下会添加BorderLayout.CENTER并覆盖以前添加的所有Square。您将需要阅读所有可用于Swing
GUI的布局管理器。
例如,从这里开始:在容器中布置组件
话虽如此,我会做不同的事情。我将只创建一个JPanel并使其能够绘制多个正方形。例如这样的事情:
import java.awt.Dimension;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Rectangle;import java.util.ArrayList;import java.util.List;import javax.swing.*;public class Gameframe extends Jframe { public Gameframe() { super("Game frame"); setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); Squares squares = new Squares(); getContentPane().add(squares); for (int i = 0; i < 15; i++) { squares.addSquare(i * 10, i * 10, 100, 100); } pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new Gameframe(); }}class Squares extends JPanel { private static final int PREF_W = 500; private static final int PREF_H = PREF_W; private List<Rectangle> squares = new ArrayList<Rectangle>(); public void addSquare(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); squares.add(rect); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; for (Rectangle rect : squares) { g2.draw(rect); } }}


