How do I get a shape to display in a JPanel?

Hi

I've created a rectangle class and can add (and view) it in a JFrame. If I put it in a JPanel and add the JPanel, I can't see it. The code is below.

import javax.swing.JFrame;

import javax.swing.JPanel;

publicclass rectTest

{

publicstaticvoid main(String[] args)

{

//create frame

JFrame frame =new JFrame();

frame.setSize(1000, 900);

//create panel

JPanel inset =new JPanel();

inset.setSize(250, 250);

//create rectangle and add to JPanel

RC rec =new RC();

inset.add(rec);

inset.setVisible(true);

//add JPanel to JFrame

frame.add(inset);

frame.setVisible(true);

}

}

[1339 byte] By [Aalstaira] at [2007-11-27 6:49:43]
# 1
What is the code of RC class plz send it so i can give u better suggestion
BMPRASADa at 2007-7-12 18:23:31 > top of Java-index,Java Essentials,New To Java...
# 2

Hi

RC is as undernoted.

package testCode;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

public class RC extends JComponent

{

public void paintComponent(Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

Rectangle box = new Rectangle(50, 100, 200, 300);

g2.draw(box);

}

}

Thanks for your prompt reply!

Aalstaira at 2007-7-12 18:23:31 > top of Java-index,Java Essentials,New To Java...
# 3
The JFrame probably considers the JPanel to be empty and so shrinks it's size to the point of invisibility. Set a minimum size, perhaps. Also, try calling the super classes paintComponent method from yours, to make sure you're not missing anything important there.
RedUnderTheBeda at 2007-7-12 18:23:31 > top of Java-index,Java Essentials,New To Java...
# 4

RedUnderTheBed is right. Use the setPreferredSize() method to force it to be displayed at the size you wish. You also want to add the shape to the frame's contentPane, not the frame itself:

import java.awt.*;

import javax.swing.*;

class RC extends JComponent {

public void paintComponent(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

Rectangle box = new Rectangle(50, 100, 200, 300);

g2.draw(box);

}

}

public class rectTest

{

public static void main(String[] args)

{

JFrame frame = new JFrame();

frame.setSize(1000, 900);

JPanel inset = new JPanel();

inset.setSize(750, 750);

RC rec = new RC();

inset.add(rec);

rec.setPreferredSize( new Dimension(750,750) );

inset.setVisible(true);

frame.getContentPane().add(inset);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

kevjavaa at 2007-7-12 18:23:31 > top of Java-index,Java Essentials,New To Java...
# 5
try some absolute positioning:yourJpanel.setLayout(null);rec.setSize(x, y);rec.setLocation(a, b);
boblettoj99a at 2007-7-12 18:23:31 > top of Java-index,Java Essentials,New To Java...