无法绘制矩形

时间:2013-04-01 23:44:37

标签: java swing graphics jpanel rectangles

我正在尝试制作一个简单的游戏,但为了让游戏工作,我需要能够绘制一个矩形。我添加了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();
}

}

1 个答案:

答案 0 :(得分:2)

您永远不会面板添加到JFrame。替换:

f.add(p);

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

显然,这会取代JPanel p位置中的BorderLayout.CENTER paintComponent,因此您需要确定此位置的位置。您可以将其添加到 NORTH ,如图所示。


此外,您应该覆盖paint而不是super.paintComponent(g),同时记住要调用{{1}}。

请参阅:Custom Painting