Java 不能绘制矩形
我只是想做一个简单的游戏,但是为了让游戏正常运行,我需要能够画一个矩形。我添加了绘画方法,并告诉它画一个矩形,但它不起作用。有人能修改我的代码或者告诉我为什么没有画矩形吗Java 不能绘制矩形,java,swing,graphics,jpanel,rectangles,Java,Swing,Graphics,Jpanel,Rectangles,我只是想做一个简单的游戏,但是为了让游戏正常运行,我需要能够画一个矩形。我添加了绘画方法,并告诉它画一个矩形,但它不起作用。有人能修改我的代码或者告诉我为什么没有画矩形吗 import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JButton; import javax.swing
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();
}
}
您从未实际将面板添加到JFrame
。替换:
f.add(p);
与
显然,这将取代BorderLayout.CENTER
位置中的JPanel
p
,因此您需要确定它现在的位置。如图所示,您可以将其添加到北方
此外,您还应该重写
paintComponent
,而不是paint
,同时记住调用super.paintComponent(g)
请参阅:矩形应该是什么颜色?@syb0rg只有在他们创建它时(即通过
Graphics\create
),否则这将阻止在它上绘制任何东西。您说的是f。添加(这个)我为“这个”写什么为什么要在喷漆上使用paintComponent?paintComponent
使用双缓冲提供了更好的喷漆性能,因此应始终在喷漆中使用Swing@Reimus我对这个很陌生,我应该把Jpanel p和Borderlayout.center放在哪里?
f.add(p, BorderLayout.NORTH);
f.add(this);