2013-04-01 118 views
0

我想只做一个简单的游戏,但为了游戏的工作,我需要能够绘制一个矩形。我添加了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

矩形应该是什么颜色? –

回答

2

你从来没有真正添加面板您JFrame。替换:

f.add(p); 

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

显然,这将取代在BorderLayout.CENTER位置JPanelp,所以你需要决定这个被现在的位置。如图所示,您可以将其添加到NORTH。你


也应该重写paintComponent而非paint,一边回忆调用super.paintComponent(g)

参见:Custom Painting

+0

只要打败我吧! – Clark

+1

@ syb0rg只有他们创建它(即通过'Graphics#create'),否则这将防止任何东西被绘制到它 – MadProgrammer

+0

你说f.add(this)我为“this”写什么 – user2109242