This is my current RectangleComponent class and I add it to a panel in my main JFrame but it never appears. I thought it wasn't drawing so I decided to call the paintComponent method in the Rectangle's constructor, and after sorting through 4-5 nullPointerExceptions, nothing has changed. I've read multiple guides on how to draw rectangles and I have seen multiple code examples, but I can never get the panels to work with more than one JComponent. If you could, please take a brief look at my code and see if you can devise a solution. Thank you for your time. Also listed is the Frame I call the rectangle constructor in.
public class GameFrame extends JFrame
{
private SpellBarComponent bar;
private JPanel mainPanel = new JPanel();
private JPanel buttonPanel = new JPanel();
private JPanel healthPanel = new JPanel();
Color green = new Color(29, 180, 29);
Color red = new Color(255, 0, 0);
private RectangleComponent life;
private RectangleComponent death;
private JFrame frame = new JFrame();
public GameFrame(char x)
{
frame.setSize(1024, 768);
frame.setTitle("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
FlowLayout layout = new FlowLayout();
createPanels(x);
healthPanel.setLayout(layout);
buttonPanel.setLayout(layout);
mainPanel.setLayout(layout);
frame.getContentPane().add(mainPanel);
frame.pack();
repaint();
}
public RectangleComponent getLife()
{
return life;
}
private void createHealth()
{
life = new RectangleComponent(green, healthPanel);
death = new RectangleComponent(red, healthPanel);
}
private void createPanels(char x)
{
add(healthPanel);
pack();
createBar(x);
createHealth();
mainPanel.add(buttonPanel);
mainPanel.add(healthPanel);
healthPanel.add(death);
healthPanel.add(life);
buttonPanel.add(bar.getSpell1());
buttonPanel.add(bar.getSpell2());
buttonPanel.add(bar.getSpell3());
add(mainPanel);
}
private void createBar(char x)
{
bar = new SpellBarComponent(x, mainPanel);
}
}
public class RectangleComponent extends JComponent
{
Color color;
int width;
int height = 18;
RoundRectangle2D roundedRectangle;
private JPanel panel;
public RectangleComponent(Color color, JPanel panel)
{
this.panel = panel;
this.color = color;
paintComponent(panel.getGraphics());
}
public void paintComponent(Graphics g)
{
Graphics2D graphics2 = (Graphics2D) g;
width = 125;
roundedRectangle = new RoundRectangle2D.Float(10, 10, width, height, 10, 10);
graphics2.setPaint(color);
graphics2.fill(roundedRectangle);
graphics2.draw(roundedRectangle);
}
public void subtractLife(int amount)
{
width -= amount;
roundedRectangle.setRoundRect(10, 10, width, height, 10, 10);
repaint();
}
}
No need to pass JPanel
to the constructor of RectangleComponent
just to get Graphics
, and no need to manually call paintComponent
. See Painting in AWT and Swing. Check out this example that demonstrates a custom component that paints a rectangle.