Making a small little game for my computer science class but im struggling to figure out how to add graphics to a JPanel here's what I have so far
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class Map extends JComponent{
private JFrame frame;
private JPanel panel;
Map()
{
setPreferredSize(new Dimension(500,500));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(100,150, 100, 100);
}
public void makeMap()
{
frame = new JFrame();
panel = new JPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setTitle("MAP");
}
}
You're not adding the Map
component to the JPanel
that you've created.
Basically you lack the following lines in makeMap()
:
panel.setLayout(new BorderLayout());
panel.add(this);
Instead of setting the BorderLayout
of the panel
after its construction, you could also set it during construction, then it would look like this:
panel = new JPanel(new BorderLayout());
panel.add(this);