0

I am trying to just make a simple game, but for the game to work I need to be able to draw a rectangle. I added the paint method and told it to draw a rectangle and it didnt work. can someone please fix my code or tell me why a rectangle isn't being drawn?

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();
}

}
4

1 回答 1

2

You never actually add the panel to your JFrame. Replace:

f.add(p);

with

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

Obviously, this will displace the JPanel p in the BorderLayout.CENTER position, so you need to decide where this be now located. You could add it up NORTH as shown.


Also you should override paintComponent rather than paint, while remembering to call super.paintComponent(g).

See: Custom Painting

于 2013-04-01T23:49:19.710 回答