虽然已经提供的答案可能会导致出现矩形,但这种方法并非最佳。此示例旨在显示一种更好的方法。阅读代码中的注释以获取详细信息。
请注意,应该在EDT上启动Swing / AWT GUI。这留给读者练习。
import java.awt.*;import javax.swing.*;public class Painting { public static void main(String[] args) { Jframe jf = new Jframe("JUST DRAW A RECTANGLE"); jf.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); // null layouts cause more problems than they solve. DO NOT USE! //jf.setLayout(null); jf.setLocationRelativeTo(null); //jf.setSize(600, 600); //jf.setVisible(true); // as mentioned, this should be last Mainting maint = new Mainting(); jf.add(maint); jf.pack(); // makes the GUI the size it NEEDS to be jf.setVisible(true); }}class Mainting extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.drawRect(10, 10, 200, 200); System.out.println("paintComponent called"); //g.setColor(Color.red); } @Override public Dimension getPreferredSize() { // Provide hints to the layout manager! return new Dimension(220, 220); }}


