【问题标题】:Cant Draw Rectangle不能画矩形
【发布时间】:2013-04-01 23:44:36
【问题描述】:

我正在尝试制作一个简单的游戏,但要让游戏正常运行,我需要能够绘制一个矩形。我添加了paint方法并告诉它绘制一个矩形,但它不起作用。有人可以修复我的代码或告诉我为什么没有绘制矩形吗?

import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;



public class Graphic extends JPanel{

JFrame f = new JFrame("lol");
JPanel p = new JPanel(new GridBagLayout());

public Graphic(){

        f.setVisible(true);
        f.setSize(1600,900);
        //above decides if the frame is visible and the size of it
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //above makes the Jpanel which is in the frame
        JButton b1 = new JButton("Play");
        JButton b2 = new JButton("Stop");
        //above makes a button


        GridBagConstraints c = new GridBagConstraints();

        c.insets = new Insets(10,10,10,10);
        c.gridx = 0;
        c.gridy = 1;

        p.add(b1,c);
        //c.gridx = 0;
        //c.gridy = 2;
        p.add(b2);

        f.add(p);
}
public void paint(Graphics g){
    g.drawRect(100,100,100,100);
}


public static void main(String args[]) {
    Graphic G = new Graphic();
}

}

【问题讨论】:

  • 矩形应该是什么颜色的?

标签: java swing graphics jpanel rectangles


【解决方案1】:

您实际上从未将面板添加到您的JFrame。替换:

f.add(p);

f.add(p, BorderLayout.NORTH);
f.add(this);

显然,这将取代BorderLayout.CENTER 位置中的JPanel p,因此您需要确定它现在的位置。你可以把它加起来NORTH,如图所示。


您还应该覆盖paintComponent 而不是paint,同时记住调用super.paintComponent(g)

见:Custom Painting

【讨论】:

  • @syb0rg 仅当他们创建它(即通过Graphics#create),否则这将阻止任何东西被绘制到它
  • 你说 f.add(this) 我为“this”写什么
  • 为什么要在paint上使用paintComponent?
  • paintComponent 使用双缓冲提供更好的绘制性能,因此应始终在 Swing 中使用
  • @Reimus 我对此很陌生,我应该把 Jpanel p 和 Borderlayout.center 放在哪里?
猜你喜欢
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 2011-10-09
  • 2017-03-21
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多