Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Resize JDialog to fit dialog title

843807Aug 30 2010 — edited Aug 30 2010
Hello members

I've been trying to resize a JDialog to have the same width as the dialog title (which is longer than the information in the dialog panels).
The code below does not work, how can I change it to get the dialog resized?
import javax.swing.*;*
*import java.awt.*;
import java.awt.event.*;

public class DialogTitleTest {

	public DialogTitleTest() {
		JDialog dialog = new JDialog();
		dialog.setLayout(new BorderLayout());
		dialog.setSize(new Dimension(300, 300));
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.add(new JLabel("Hello"), BorderLayout.CENTER);
		String title = "This is a very very very very long title";
		dialog.setTitle(title);

		dialog.pack();
		dialog.setVisible(true);

		JLabel titleLabel = new JLabel(title);
		Dimension dialogPrefSize = dialog.getPreferredSize();
		System.out.println("Dialog pref width "  +dialogPrefSize.getWidth()+  " title pref width " + titleLabel.getPreferredSize().getWidth());
    dialog.setPreferredSize(new Dimension(
        (int) titleLabel.getPreferredSize().getWidth(),
        (int) dialogPrefSize.getHeight()));
    dialog.validate();
    dialog.repaint();
	}


  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    	public void run() {
    	  DialogTitleTest p = new DialogTitleTest();
    	}
    });
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 27 2010
Added on Aug 30 2010
2 comments
1,135 views