Edgar Smith
Edgar Smith

Reputation: 183

Adding Graphics to JPanel

I'm trying to add a graphic onto a JPanel. I have working code for creating a rectangle and putting it onto a frame. Now for some reason when I try to add it onto a JPanel, I don't see anything. I'm not sure if I've done something wrong or the process for adding graphics to a JFrame doesn't work for adding to a JPanel.

This is the code that DOESN'T work:

Panel

import java.awt.Component;
import java.awt.Container;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.FlowLayout;

public class Window2 extends JFrame {
    public Window2() {
        Container panel = this.getContentPane();
        panel.setLayout(new FlowLayout());
        panel.setSize(1000,1000);

        ExampleComponent2 dc = new ExampleComponent2();
        panel.add(dc);

        setSize(800,600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);       
    }

    public static void main(String[] args){
        Window window = new Window();
    }   
}

DrawingComponent class

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Rectangle;

public class ExampleComponent2 extends JComponent {
    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;

        Rectangle rect1 = new Rectangle(20,20,40,40);
        g2.draw(rect1);
    }
}

And this is the code that DOES work:

Main Class

import javax.swing.JFrame;
import java.awt.Rectangle;

public class Main{
    public static void main(String[] args){
        JFrame window = new JFrame();
        window.setSize(650,500);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);

        ExampleComponent dc = new ExampleComponent();
        window.add(dc);
    }   
}

Upvotes: 0

Views: 327

Answers (2)

matt
matt

Reputation: 12346

ExampleComponent2 dc = new ExampleComponent2();
dc.setPreferredSize(new Dimension(100, 100));
panel.add(dc);

Then it shows up for me.

Upvotes: 1

Wulf
Wulf

Reputation: 712

The problem is your Layout. Try the Borderlayout and after that read some API.

panel.setLayout(new BorderLayout());

Upvotes: 0

Related Questions