user2932450
user2932450

Reputation: 71

How to draw a rectangle within a JPanel

I am attempting to draw a Rectangle within a JPanel that is within a JFrame. I am wanting to use the paintComponents(Graphics g) method and override it but for some reason the rectangle is not appearing within the JPanel as I would hope. Any help would be appreciated.

public class RectangleFrame extends JFrame implements ActionListener {
    JPanel buttonPanel;
    JButton saveImage;
    JButton clearImage;
    JCheckBox intersections;
    JCheckBox union;
    JPanel drawingArea;



public RectangleFrame()
{
    super();
    setTitle("Rectangles");
    setSize(600,600);
    setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonPanel = new JPanel();
    buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    this.add(buttonPanel, BorderLayout.SOUTH);

    intersections = new JCheckBox("Draw Intersections");
    buttonPanel.add(intersections);

    union = new JCheckBox("Draw Union");
    buttonPanel.add(union);

    saveImage = new JButton("Save Image");
    saveImage.setMargin(new Insets(0,0,0,0));
    buttonPanel.add(saveImage);

    clearImage = new JButton("Clear Image");
    clearImage.setMargin(new Insets(0,0,0,0));
    buttonPanel.add(clearImage);

    drawingArea = new JPanel();
    drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
    this.add(drawingArea, BorderLayout.CENTER); 
}
}

      class RectanglePanel extends JPanel
{
public RectanglePanel()
{
    super();
}



@Override
public void paintComponent(Graphics g) 
{
    super.paintComponent(g);

    g.setColor(Color.BLUE);
    g.fillRect(25,25,100,30);       
}


}

Here is my main method that is in a separate class:

    public class SwingRectangle
{

/**
 * @param args
 */
public static void main(String[] args) 
{
    // TODO Auto-generated method stub
    RectangleFrame frame = new RectangleFrame();
    RectanglePanel panel = new RectanglePanel();
    frame.setVisible(true);

}

}

Upvotes: 0

Views: 217

Answers (1)

Reimeus
Reimeus

Reputation: 159754

You didnt add the RectanglePanel to your frame.

drawingArea = new JPanel();

should be

drawingArea = new RectanglePanel();

Other points:

  • You still need to override paintComponent rather than paintComponents as suggested by @David so +1 to him
  • The panel created in SwingRectangle is unused

Upvotes: 4

Related Questions