In Java, is it possible to get the Width and Height of the JFrame without the title and other borders?
frame.getWidth() and frame.getHeight()1 seems to return the width including the border.
Thanks.
frame.getContentPane().getSize();
frame.pack();
System.out.println("frame width : "+getWidth());
System.out.println("frame height: "+getHeight());
System.out.println("content pane width : "+getContentPane().getWidth());
System.out.println("content pane height: "+getContentPane().getHeight());
System.out.println("width of left + right borders: "+(getWidth()-getContentPane ().getWidth()));
System.out.println("height of top + bottom borders: "+(getHeight()-getContentPane().getHeight()));
This works fine
frame.getContentPane().getSize();
But not if you haven't added content yet. In my case, I wanted to calculate the inner dimensions of the JFrame before adding content, so I could divide up the content accordingly. Here's what I came up with.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pack(); // Need this, otherwise insets() show as 0.
int scrW = (int)screenSize.getWidth();
int scrH = (int)screenSize.getHeight();
int innerW = scrW - getInsets().left - getInsets().right;
int innerH = scrH - getInsets().top - getInsets().bottom;
// Need to setSize(), otherwise pack() will collapse the empty JFrame
setSize(scrW, scrH);
Here is a code snippet which works on JFrame as well as AWT's Frame (which happens to be the super-type of JFrame):
public static Dimension getInnerSize(Frame frame) {
Dimension size = frame.getSize();
Insets insets = frame.getInsets();
if (insets != null) {
size.height -= insets.top + insets.bottom;
size.width -= insets.left + insets.right;
}
return size;
}
Beware: The insets are only valid once the frame has been shown.
Here is another code snippet to work around this problem:
private static Insets defaultInsets;
public static Insets getInsetsWithDefault(Frame frame) {
// insets only correct after pack() and setVisible(true) has been
// called, so we use some fallback strategies
Insets insets = frame.getInsets();
if (insets.top == 0) {
insets = defaultInsets;
if (insets == null) {
insets = new Insets(26, 3, 3, 3);
// usual values for windows as our last resort
// but only as long as we never saw any real insets
}
} else if (defaultInsets == null) {
defaultInsets = (Insets) insets.clone();
}
return insets;
}
This code needs to be called once with a visible Frame. After that it can correctly predict the insets even for invisible frames (due to caching of the defaultInsets), assuming they are always the same.
Of course this only works if all windows get the same window-decorations. But i am not aware of any case where they might differ from window to window.
This might be useful, too:
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
MyUtilClass.getInsetsWithDefault(frame); // init the defaultInsets
}
});
It will call the getInsetsWithDefault() method once the window is visible and initialize the correct defaultInsets.
Related
this.setLocationRelativeTo(null);
jFrame will show in the center of Screen. But i don't known how to set jFrame at the right of Screen.
You can do this yourself by calculating the position based on the size of the screen and the frame.
static void setLocationToTopRight(JFrame frame) {
GraphicsConfiguration config = frame.getGraphicsConfiguration();
Rectangle bounds = config.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
int x = bounds.x + bounds.width - insets.right - frame.getWidth();
int y = bounds.y + insets.top;
frame.setLocation(x, y);
}
The screen insets include places where a window is not expected to occupy, like task bars and the Mac menu bar. It's possible there is an OS where you can place something on the right side of the screen which would interfere with the window placement if you didn't subtract the insets. (I think Ubuntu can do that, actually, but I don't remember whether a window is placed on top of or behind the menu.)
Here's a simple MCVE demonstrating all four edges. Pressing one of the four buttons anchors the JFrame to that edge.
package mcve;
import javax.swing.*;
import java.awt.*;
public class WindowPlacement {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Window Placement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton top = new JButton("Top");
JButton left = new JButton("Left");
JButton bottom = new JButton("Bottom");
JButton right = new JButton("Right");
frame.add(top, BorderLayout.NORTH);
frame.add(left, BorderLayout.WEST);
frame.add(bottom, BorderLayout.SOUTH);
frame.add(right, BorderLayout.EAST);
top.addActionListener(e -> setLocationToTop(frame));
left.addActionListener(e -> setLocationToLeft(frame));
bottom.addActionListener(e -> setLocationToBottom(frame));
right.addActionListener(e -> setLocationToRight(frame));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
// Also see:
// https://docs.oracle.com/javase/9/docs/api/java/awt/GraphicsEnvironment.html#getMaximumWindowBounds--
static Rectangle getMaxWindowBounds(JFrame frame) {
GraphicsConfiguration config = frame.getGraphicsConfiguration();
Rectangle bounds = config.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= insets.left + insets.right;
bounds.height -= insets.top + insets.bottom;
return bounds;
}
static void setLocationToTop(JFrame frame) {
frame.setLocation(frame.getX(), getMaxWindowBounds(frame).y);
}
static void setLocationToLeft(JFrame frame) {
frame.setLocation(getMaxWindowBounds(frame).x, frame.getY());
}
static void setLocationToBottom(JFrame frame) {
Rectangle bounds = getMaxWindowBounds(frame);
frame.setLocation(frame.getX(), bounds.y + bounds.height - frame.getHeight());
}
static void setLocationToRight(JFrame frame) {
Rectangle bounds = getMaxWindowBounds(frame);
frame.setLocation(bounds.x + bounds.width - frame.getWidth(), frame.getY());
}
}
If the component is not null and is shown on the screen, then the window is located in such a way that the center of the window coincides with the center of the component.
In other words, you should try frame.setLocation() and then some values (x,y) and look what fits properly
Edit: value 0,0 will give rightcorner
so in ur case : this.setLocation(0,0);
At the moment I've got a 9x9 grid of text fields using a GridBayLayout. Because the grid makes each text field slighter longer than it is tall (even when I set a specific height for the text field), the grid is a rectangle, rather than a square.
How can I either make the entire grid a specific size, or each text field inside the grid a specific size?
EDIT: I need the 9 x 9 grid of text fields to be square, rather than rectangular.
The problem is with sizing hints, methods [get/set][Minimum/Maximum/Preferred]Size are telling the layout manager what size the component wants to be and layout managers sometimes ignore that and sometimes they don't. GridBagLayout respects that and your JTextFields are tellimg him that they want to be rectangular. How JTextFields figure out what size they want to be is all kinds of difficult so let's leave that out.
If you want to make sure that all your JTextFields are of the same size, you should override these methods. Subclass JTextField and make something like this:
final class SquareJTextField extends JTextField {
private static Dimension maxDimension = new Dimension(0, 0);
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
// take the larger value
int max = d.width > d.height ? d.width : d.height;
// compare it against our static dimension
// height je rovnaky ako width
if (max > maxDimension.width)
maxDimension = new Dimension(max, max);
// return copy so no one can change the private one
return new Dimension(maxDimension);
}
#Override
public Dimension getMinimumSize() {
Dimension d = super.getPreferredSize();
int max = d.width > d.height ? d.width : d.height;
if (max > maxDimension.width)
maxDimension = new Dimension(max, max);
return new Dimension(maxDimension);
}
#Override
public Dimension getMaximumSize() {
Dimension d = super.getPreferredSize();
int max = d.width > d.height ? d.width : d.height;
if (max > maxDimension.width)
maxDimension = new Dimension(max, max);
return new Dimension(maxDimension);
}
}
All objects of this class should be the same dimension and should be square.
Replace JtextFields in your grid with SquareJTextField
Using this class and this main method, I am trying to make it so that the window that is created when running the main class is the right size to hold all of the icons that are passed into it without having to resize the window, and without hardcoding a value into what I want the window size to be when I initialize it.
Right now when it runs, the window starts extremely tiny, and as I resize it the layout of all of the icons that are painted onto it are messed up.
I know how to determine the proper size it should be, but I am not sure how I I know using the coordinates ArrayList is how I would determine the size, but I am not sure how I would change the size of the window after it has already been initialized.
public class CompositeIcon implements Icon
{
ArrayList<Icon> iList;
static int width;
static int height;
ArrayList<Point> coordinates;
public CompositeIcon()
{
iList = new ArrayList<Icon>();
coordinates = new ArrayList<Point>();
}
public int getIconHeight()
{
return height;
}
public void addIcon(Icon icon, int x, int y)
{
iList.add(icon);
coordinates.add(new Point(x, y));
}
public int getIconWidth()
{
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
int i = 0;
for (Icon s : iList)
{
Point offset = coordinates.get(i++);
s.paintIcon(c, g, x + offset.x, y + offset.y);
}
}
This is the main to test it
public static void main (String args[]) {
JFrame frame = new JFrame();
Container panel = frame.getContentPane();
panel.setLayout(new BorderLayout());
CompositeIcon icon = new CompositeIcon();
try {
icon.addIcon(new ImageIcon(new URL("http://th02.deviantart.net/fs71/150/f/2013/103/2/7/java_dock_icon_by_excurse-d61mi0t.png")), 10, 10);
icon.addIcon(new ImageIcon(new URL("http://www.bravegnu.org/blog/icons/java.png")), 5, 370);
icon.addIcon(new ImageIcon(new URL("http://fc03.deviantart.net/fs20/f/2007/274/9/8/3D_Java_icon_by_BrightKnight.png")), 200, 200);
}
catch (MalformedURLException e) {
System.err.println("Apparently, somebody cannot type a URL");
}
panel.add(new JLabel(icon));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Basically, the width and height of the CompositeIcon should represent the combined width and height's of the icons you add (allowing for the x/y offsets)
Something like...
public void addIcon(Icon icon, int x, int y) {
iList.add(icon);
width = Math.max(width, x + icon.getIconWidth());
height = Math.max(height, y + icon.getIconHeight());
coordinates.add(new Point(x, y));
}
You will need to remove the static declearations for width and height as each instance of CompositeIcon should have it's own width and height
Your approach allows for random positioning of Icons, but it means you are responsible for knowing the size of each Icon and positioning them so the don't overlap one another.
For a more structured approach, you can check out Compound Icon. This class supports vertical, horizontal and stacked Icon alignment and does all the location/size calculations for you.
I have a custom layout where the principal behavior is to grow and shrink a child JTextArea when the JScrollPane it's in changes in width. The scroll pane has the horizontal scroll bar disabled and the text area is supposed to expand and contract so as to avoid needing a horizontal scroll bar. For a number of months, I worked around this using one of the standard layout managers, but now I need some different functionality.
What's happening is that when the user expands horizontally the scroll pane, the layout manager layoutContainer method is called. It resizes the text area and the text reflows properly. However, when you shrink the scroll pane, layoutContainer is not called and the text area stays fixed. I've put some printlns in the layoutContainer method to make it obvious when it's working and not.
The essential thing to note is that the problem happens when JTextArea.setColumns() is called. I can comment it out and the layoutContainer gets called during resizing (of course, then the text area doesn't get resized.) I've tried also using JTextArea.setSize(), with the same results.
Here's the code:
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#SuppressWarnings("serial")
class XTextArea extends JTextArea
{
XTextArea (String text)
{
super (text);
}
public int getColumnWidth()
{
return super.getColumnWidth();
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
class PackLeftLayout implements LayoutManager
{
Component viewPort;
Component flexWidthComponent;
int preferredWidth = 0;
int preferredHeight = 0;
//----------------------------------------------------------------------------
// viewPort - if null, compute width as sum of component's preferred width;
// otherwise width will be the viewPort's width.
// flexWidthComponent - if not null, this component width will be sized to right
// justify rightmost component.
public PackLeftLayout (Component viewPort, Component flexWidthComponent)
{
super ();
this.viewPort = viewPort;
this.flexWidthComponent = flexWidthComponent;
}
//----------------------------------------------------------------------------
public void addLayoutComponent(String name, Component comp)
{
}
//----------------------------------------------------------------------------
public void removeLayoutComponent(Component comp)
{
}
//----------------------------------------------------------------------------
// Calculates the preferred size dimensions for the specified container, given the
// components it contains.
// parent - the container to be laid out
// Components layed out left-to-right with no additional spacing.
public Dimension preferredLayoutSize (Container parent)
{
Insets insets = parent.getInsets();
int width = 0;
int height = 0; // will become max of all component's preferred height
// calculate sum of fixed width components - skip the flexwidth component
width = insets.left + insets.right;
for (int i = 0, limit = parent.getComponentCount(); i < limit; i++)
{
Component c = parent.getComponent(i);
if (c.isVisible())
{
if (c != flexWidthComponent)
{
Dimension size = c.getPreferredSize();
if (size.height > height)
height = size.height;
width += size.width;
}
}
}
// determine width of flex width component
if (flexWidthComponent != null)
{
int flexWidth = viewPort.getWidth() - width;
if (flexWidth < 1)
flexWidth = 1;
if (flexWidthComponent instanceof XTextArea)
{
// some trickery here to get the xtextarea to tell us its preferred height
// given a specific width.
int colWidth = ((XTextArea)flexWidthComponent).getColumnWidth();
// the following line causes the failure:
((XTextArea)flexWidthComponent).setColumns (flexWidth / colWidth);
Dimension taSize = flexWidthComponent.getPreferredSize();
width += taSize.width;
if (taSize.height > height)
height = taSize.height;
}
else
{
Dimension size = flexWidthComponent.getPreferredSize();
width += flexWidth;
if (size.height > height)
height = size.height;
}
}
preferredWidth = width; // already include insets
preferredHeight = height + insets.top + insets.bottom;
return new Dimension (preferredWidth, preferredHeight);
}
//----------------------------------------------------------------------------
// Calculates the minimum size dimensions for the specified container, given the
// components it contains.
// parent - the component to be laid out
public Dimension minimumLayoutSize(Container parent)
{
return new Dimension (10, 10); //???
}
static int k = 0;
//----------------------------------------------------------------------------
public void layoutContainer(Container parent)
{
System.out.println ("layout" + (k++));
Insets insets = parent.getInsets();
int left = insets.left;
if (preferredWidth == 0 || preferredHeight == 0)
preferredLayoutSize (parent);
for (int i = 0, limit = parent.getComponentCount(); i < limit; i++)
{
Component c = parent.getComponent(i);
Dimension size = c.getPreferredSize();
c.setBounds (left, insets.top, size.width, preferredHeight);
left += size.width;
}
// force another layout calc
preferredWidth = 0;
}
}
public class ResizablePane extends JFrame
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(
new Runnable() {public void run()
{
new ResizablePane();
}});
}
ResizablePane ()
{
super ("ResizableDemo");
// put a button and text area into a panel, then into a scroll pane
JButton button = new JButton ("button");
XTextArea text = new XTextArea (
"For three years I ran as fast as I could, trying to live and love and learn at " +
"double speed to make up for what Anne-Marie lost. Trying to anesthetize myself " +
"from what Id lost. When I decided to read a book a day and write about it, Id " +
"finally stopped running away.");
text.setLineWrap (true);
text.setWrapStyleWord (true);
JScrollPane scroll = new JScrollPane();
JPanel panel = new JPanel();
panel.setLayout (new PackLeftLayout(scroll.getViewport(), text));
panel.add (button);
panel.add (text);
scroll.setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setViewportView (panel);
getContentPane().add(scroll);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
JTextArea wont shrink inside JPanel
You need to set the minimum size of the text area:
textArea.SetMinimumSize(new Dimension(100,100));
ps. I'm Using GridLayout in my panel with just the one component.
This is old question, but i hope that it will be usefull to someone.
For me worked:
jScrollPane = new JScrollPane(textArea);
jScrollPane.setPreferredSize(jScrollPane.getPreferredSize());
I have a subclass of JLabel that forms a component of my GUI. I have implemented the ability to drag and drop the component from one container to another, but without any visual effects. I want to have this JLabel follow the cursor during the drag of the item from one container to another. I figured that I could just create a glass pane and draw it on there. However, even after I add the component to the glass pane, set the component visible, and set the glass pane visible, and set the glass pane as opaque, I still so not see the component. I know the component works because I can add it to the content pane and have it show up.
How do I add a component to the glass pane?
Finally figured how to get the simple example working. Thanks, #akf. I was able to adapt this solution to my original problem, allowing me to remove ~60 lines of Java2D code that manually rendered a representation of the JLabel.
package test;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MainFrame extends JFrame {
/**
* #param args
*/
public static void main(String[] args) {
MainFrame mf = new MainFrame();
mf.setSize(400, 400);
mf.setLocationRelativeTo(null);
mf.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
mf.setGlassPane(new JPanel());
JLabel l = new JLabel();
l.setText("Hello");
l.setBorder(new LineBorder(Color.BLACK, 1));
l.setBounds(10, 10, 50, 20);
l.setBackground(Color.RED);
l.setOpaque(true);
l.setPreferredSize(l.getSize());
//mf.add(l);
((JPanel)mf.getGlassPane()).add(l);
mf.getGlassPane().setVisible(true);
mf.setVisible(true);
}
}
The example code below shows how to drag a chess piece around a chess board. It uses JLayeredPane instead of a glass pane, but I'm sure the concepts would be the same. That is:
a) add the glass pane to the root pane
b) make the glass pane visible
c) add the component to the glass pane making sure the bounds are valid
d) use setLocation() to animate the dragging of the component
Edit: added code to fix SSCCE
JLabel l = new JLabel();
l.setText("Hello");
l.setBorder(new LineBorder(Color.BLACK, 1));
// l.setPreferredSize(l.getSize());
// l.setBounds(10, 10, 50, 20);
((JPanel)mf.getGlassPane()).add(l);
mf.setVisible(true);
mf.getGlassPane().setVisible(true);
When using layout managers you never use the setSize() or setBounds() methods. In your case you just set the preferred size to (0, 0) since this is the default size of all components.
It works when you add the label to the frame because the default layout manger for the content pane of the frame is a border layout, therefore the preferred size of the label is ignored and the label is made the size of the frame.
However, by default a JPanel uses a FlowLayout which does respect the preferred size of the component. Since the preferred size is 0, there is nothing to paint.
Also, the glass pane needs to made visible in order for it to be painted.
I suggest you read the Swing tutorial. There are section on how layout managers work and on how glass panes work and each section has working examples.
Edit: Example code added below:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
{
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
public ChessBoard()
{
Dimension boardSize = new Dimension(600, 600);
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize( boardSize );
layeredPane.addMouseListener( this );
layeredPane.addMouseMotionListener( this );
getContentPane().add(layeredPane);
// Add a chess board to the Layered Pane
chessBoard = new JPanel();
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
// Build the Chess Board squares
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
JPanel square = new JPanel( new BorderLayout() );
square.setBackground( (i + j) % 2 == 0 ? Color.red : Color.white );
chessBoard.add( square );
}
}
// Add a few pieces to the board
ImageIcon duke = new ImageIcon("dukewavered.gif"); // add an image here
JLabel piece = new JLabel( duke );
JPanel panel = (JPanel)chessBoard.getComponent( 0 );
panel.add( piece );
piece = new JLabel( duke );
panel = (JPanel)chessBoard.getComponent( 15 );
panel.add( piece );
}
/*
** Add the selected chess piece to the dragging layer so it can be moved
*/
public void mousePressed(MouseEvent e)
{
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel) return;
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
/*
** Move the chess piece around
*/
public void mouseDragged(MouseEvent me)
{
if (chessPiece == null) return;
// The drag location should be within the bounds of the chess board
int x = me.getX() + xAdjustment;
int xMax = layeredPane.getWidth() - chessPiece.getWidth();
x = Math.min(x, xMax);
x = Math.max(x, 0);
int y = me.getY() + yAdjustment;
int yMax = layeredPane.getHeight() - chessPiece.getHeight();
y = Math.min(y, yMax);
y = Math.max(y, 0);
chessPiece.setLocation(x, y);
}
/*
** Drop the chess piece back onto the chess board
*/
public void mouseReleased(MouseEvent e)
{
layeredPane.setCursor(null);
if (chessPiece == null) return;
// Make sure the chess piece is no longer painted on the layered pane
chessPiece.setVisible(false);
layeredPane.remove(chessPiece);
chessPiece.setVisible(true);
// The drop location should be within the bounds of the chess board
int xMax = layeredPane.getWidth() - chessPiece.getWidth();
int x = Math.min(e.getX(), xMax);
x = Math.max(x, 0);
int yMax = layeredPane.getHeight() - chessPiece.getHeight();
int y = Math.min(e.getY(), yMax);
y = Math.max(y, 0);
Component c = chessBoard.findComponentAt(x, y);
if (c instanceof JLabel)
{
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
parent.validate();
}
else
{
Container parent = (Container)c;
parent.add( chessPiece );
parent.validate();
}
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args)
{
JFrame frame = new ChessBoard();
frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
frame.setResizable( false );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
Although tangential to the question, the JLayeredPane example cited by #camickr admits the following adaptation, which highlights the effect of mouseReleased() over an existing component.
public ChessBoard() {
...
// Add a few pieces to the board
addPiece(3, 0, "♛");
addPiece(4, 0, "♚");
addPiece(3, 7, "♕");
addPiece(4, 7, "♔");
}
static Font font = new Font("Sans", Font.PLAIN, 72);
private void addPiece(int col, int row, String glyph) {
JLabel piece = new JLabel(glyph, JLabel.CENTER);
piece.setFont(font);
JPanel panel = (JPanel) chessBoard.getComponent(col + row * 8);
panel.add(piece);
}
Besides the pointers to the LayerPane examples already provided, the issue with your original code centers around the setting of the preferred size of your label. You set it before the JLabel has been sized, so your:
l.setPreferredSize(l.getSize());
is ineffectual. If, on the other hand, you make that call after you make your call to setBounds, you will see your desired results. With that in mind, reorder this:
l.setPreferredSize(l.getSize());
l.setBounds(10, 10, 50, 20);
to look like this:
l.setBounds(10, 10, 50, 20);
l.setPreferredSize(l.getSize());
Since I had been following Romain Guy's blogs on Swing for a long time. I have a link that you might be interested in. He released the source - which used a GlassPane for DnD effects.
http://jroller.com/gfx/entry/drag_and_drop_effects_the
I myself never did use a fizzy animation/effect on DnD, so can't comment any further :-|