How to draw something on a label which is on a panel?

Im new to deal with Java2D. I was trying to draw something on a jlabel, and put the label on a panel.

But I does not work. When I put the label on a JFrame, it works well.

I cant understand what is the trick.

Can someone explain this trick for me?

Thanks a lot.

Following is the code i wrote.

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

publicclass testextends JLabel{

publicvoid paint(Graphics g){

Graphics2D g2 = (Graphics2D)g;

g2.drawOval(100, 100, 100, 100);

}

publicstaticvoid main(String[] args){

JFrame f =new JFrame();

f.setSize(400,400);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel =new JPanel();

test t =new test();

panel.add(t);

//f.add(panel); // Does not work.

f.add(t);// Works well

f.setVisible(true);

}

}

[1793 byte] By [scott_kima] at [2007-10-3 11:29:50]
# 1

I cant understand what is the trick.

No trick, just some of the subtlety of layout managers in Java.

The default layout manager for JFrame is BorderLayout. When you add a component to the center section of a BorderLayout it is expanded in size to fill the available space. The JLabel is displayed at this size when added to the frames content pane without constraints: default center section. When you add the JLabel to the JPanel, it is shown at its preferred size by the JPanels default FlowLayout. Since you have not set any text, icon or preferredSize the JLabel has no idea what size it should be and the JPanel gets something like (0,0) or (10,10) when it asks the JLabel for its size. The JPanel expands to fill the center section space and shows the JLabel at its (the JLabels) requested size (likely (0,0)). You can read about the details in the class api for the BorderLayout and FlowLayout classes and also in the Swing tutorial section on layout managers.

To get the JLabel to show up in the JPanel you can either call setPreferredSize in/on it or override the getPreferredSize method in the class and return the desired Dimension. Or set the JPanels layout to BorderLayout and add the label to its center section.

crwooda at 2007-7-15 13:56:20 > top of Java-index,Security,Cryptography...