Modal JDialog messing parent layout
Hello!
Why does a modal JDialog mess up the parent frame layout? Actually only one panel inside it and a few components but still. When setVisible(true) is called on the dialog, the parent layout gets screwed. And when the dialog is closed it stays screwed until something makes the panel/frame re-validate itself (like resize or call to validate()). Any ideas what might be causing this?
The dialog is modal and the frame is set as the parent for the dialog.
Thanks,
-teka
Well it's possible that I am. The code is a bit complex with lots of classes etc. (and not made by me originally). Didn't find any AWT components when I browsed through the code but maybe I missed something. Does mixing AWT and Swing cause layout problems like that?
-teka
Similar Messages
-
Hello everyone!
I have a problem regarding customized modal JDialog in an application I am working on. The problem goes like this, first I open the JDialog from my application which is supposedly the parent of this JDialog, when I switch to any application from the OS (making my application hidden or brought to the background) and then going back to my application the JDialog is no longer shown making my application lock up and not accept any input at all --- making it impossible to close unless killed explicitly from the task manager.
What have I done wrong? And what should I do to get around it?@param owner the non-null <code>Dialog</code> from which the dialog is displayed
* @param title the <code>String</code> to display in the dialog's
* title bar
* @param modal true for a modal dialog, false for one that allows
* other windows to be active at the same time
JDialog(Dialog owner, String title, boolean modal)pass true if you want to make dialog as model -
Can't start Thread from modal JDialog.
Hi,
this is a part of my code. I can't start the scanThread from the object WaitingDl. But if i close the modal JDialog (WaitingDl) the scanThread starts, please help:
Thread scanThread = new Thread() {
public void run() {
// do something ....
WaitingDl waitFrame = new WaitingDl("Waiting process", parent, scanThread, "Please wait ...");
class WaitingDl extends JDialog {
public WaitingDl(String title, JFrame parent, Thread thread, String waitingText) {
// a modal Dialog
super(parent,true);
// This command doesn't work!
scanThread.start();
Thanks!Hi,
As suggestion :
I think your JDialog is modal and visible by default, so
when you invoke the contructor :
WaitingDL d=new ......
you enter to "modal state" so the Event thread is blocked and this append when you invoke super at
contructor level.
If you set your dialog not visible you can do :
WaitingDL d=new .........
// at this moment the contructor is invoked but the event thread is not blocked so your thread is started
d.setVisible(true);
// at this point the dialog is visible you enter at a modal state but your thread is running
Hope this help
Bye -
Restrict Movement of JDialog in Parent Component
I have created a non-modal JDialog. I would like to restrict the movement of the JDialog so that it cannot be moved outside the bounds of its parent component. Help is appreciated!
lissa7613You could use a JDesktopPane with JInternalFrames, this is their default behaviour. Read this section from the Swing tutorial on "How to Use Internal Frames":
http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html
Otherwise, you would have to add a ComponentListener to the JDialog. Whenever the JDialog is moved, you would check its location and if it is outside the bounds of the parent frame then you would reset its location. Here is a tutorial on "Using a Component Listener":
http://java.sun.com/docs/books/tutorial/uiswing/events/componentlistener.html -
Problems with 'background' JFrame focus when adding a modal JDialog
Hi all,
I'm trying to add a modal JDialog to my JFrame (to be used for data entry), although I'm having issues with the JFrame 'focus'. Basically, at the moment my program launches the JFrame and JDialog (on program load) fine. But then - if I switch to another program (say, my browser) and then I try switching back to my program, it only shows the JDialog and the main JFrame is nowhere to be seen.
In many ways the functionality I'm looking for is that of Notepad: when you open the Find/Replace box (albeit it isn't modal), you can switch to another program, and then when you switch back to Notepad both the main frame and 'JDialog'-esque box is still showing.
I've been trying to get this to work for a couple of hours but can't seem to. The closest I have got is to add a WindowFocusListener to my JDialog and I hide it via setVisible(false) once windowLostFocus() is fired (then my plan was to implement a similar functionality in my JFrame class - albeit with windowGainedFocus - to show the JDialog again, i.e. once the user switches back to the program). Unfortunately this doesn't seem to work; I can't seem to get any window or window focus listeners to actually fire any methods, in fact?
I hope that kind of makes sense lol. In short I'm looking for Notepad CTRL+R esque functionality, albeit with a modal box. As for a 'short' code listing:
Main.java
// Not all of these required for the code excerpt of course.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
import javax.swing.plaf.basic.BasicSplitPaneUI;
public class Main extends JFrame implements ActionListener, WindowFocusListener, WindowListener, FocusListener {
static JFrame frame;
private static int programWidth;
private static int programHeight;
private static int minimumProgramWidth = 700;
private static int minimumProgramHeight = 550;
public static SetupProject setupProjectDialog;
public Main() {
// Setup the overall GUI of the program
private static void createSetupProjectDialog() {
// Now open the 'Setup Your Project' dialog box
// !!! Naturally this wouldn't auto-open on load if the user has already created a project
setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );
// Okay, for this we want it to be (say) 70% of the progamWidth/height, OR *slightly* (-25px) smaller than the minimum size of 700/550
// Change (base on programWidth/Height) then setLocation
int currProgramWidth = getProgramWidth();
int currProgramHeight = getProgramHeight();
int possibleWidth = (int) (currProgramWidth * 0.7);
int possibleHeight = (int) (currProgramHeight * 0.7);
// Set the size and location of the JDialog as needed
if( (possibleWidth > (minimumProgramWidth-25)) && (possibleHeight > (minimumProgramHeight-25)) ) {
setupProjectDialog.setPreferredSize( new Dimension(possibleWidth,possibleHeight) );
setupProjectDialog.setLocation( ((currProgramWidth/2)-(possibleWidth/2)), ((currProgramHeight/2)-(possibleHeight/2)) );
else {
setupProjectDialog.setPreferredSize( new Dimension( (minimumProgramWidth-25), (minimumProgramHeight-25)) );
setupProjectDialog.setLocation( ((currProgramWidth/2)-((minimumProgramWidth-25)/2)), ((currProgramHeight/2)-((minimumProgramHeight-25)/2)) );
setupProjectDialog.setResizable(false);
setupProjectDialog.toFront();
setupProjectDialog.pack();
setupProjectDialog.setVisible(true);
public static void main ( String[] args ) {
Main frame = new Main();
frame.pack();
frame.setVisible(true);
createSetupProjectDialog();
// None of these get fired when the Jframe is switched to. I also tried a ComponentListener, but had no joy there either.
public void windowGainedFocus(WindowEvent e) {
System.out.println("Gained");
setupProjectDialog.setVisible(true);
public void windowLostFocus(WindowEvent e) {
System.out.println("GainedLost");
public void windowOpened(WindowEvent e) {
System.out.println("YAY1!");
public void windowClosing(WindowEvent e) {
System.out.println("YAY2!");
public void windowClosed(WindowEvent e) {
System.out.println("YAY3!");
public void windowIconified(WindowEvent e) {
System.out.println("YAY4!");
public void windowDeiconified(WindowEvent e) {
System.out.println("YAY5!");
public void windowActivated(WindowEvent e) {
System.out.println("YAY6!");
public void windowDeactivated(WindowEvent e) {
System.out.println("YAY7!");
public void focusGained(FocusEvent e) {
System.out.println("YAY8!");
public void focusLost(FocusEvent e) {
System.out.println("YAY9!");
SetupProject.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SetupProject extends JDialog implements ActionListener {
public SetupProject( final JFrame frame, String title, boolean modal ) {
// Setup the JDialog
super( frame, title, modal );
setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
// Bad code. Is only temporary
add( new JLabel("This is a test.") );
// !!! TESTING
addWindowFocusListener( new WindowFocusListener() {
public void windowGainedFocus(WindowEvent e) {
// Naturally this now doesn't get called after the setVisible(false) call below
public void windowLostFocus(WindowEvent e) {
System.out.println("Lost");
setVisible(false); // Doing this sort of thing since frame.someMethod() always fires a null pointer exception?!
}Any help would be very much greatly appreciated.
Thanks!
TristanHi,
Many thanks for the reply. Isn't that what I'm doing with the super() call though?
As in, in Main.java I'm doing:
setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );Then the constructor in SetupProject is:
public SetupProject( final JFrame frame, String title, boolean modal ) {
// Setup the JDialog
super( frame, title, modal );
And isn't the super call (since the class extends JDialog) essentially like doing new JDialog(frame,title,modal)?
If not, that would make sense due to the null pointer exception errors I've been getting. Although I did think I'd done it right hence am confused as to the right way to handle this,if so.
Thanks,
Tristan
Edited by: 802573 on 20-Oct-2010 08:27 -
Modal JDialog needs disposing TWICE!
I have a simple JDialog that is modal over another JDialog. It has a cancel button whose action event simply calls dispose().
However, on first invocation of cancel, the dispose() does not actually remove the dialog; it is only on a second click that dispose() actually does kill the dialog. I notice also that the first dispose() does not cause WindowClosed() to be called. I have verified that definitely only one instance of the dialog is being referenced (hashcode on each dispose is the same).
The problem immediately goes away if I make the dialog non-modal, but I want it modal!!
Any suggestions? Seems like a bug to me...(j2sdk1.4.1_01)By calling setVisible(false) the modal JDialog disappears and while it's invisible it's not modal (awt Dialogs do that, too). I was not able to reproduce your problem, but this piece of code may solve it:
setVisible(false);
dispose(); -
Change a modal JDialog to non-modal JDialog
I created a modal JDialog initially, for some result i need change it to a non-modal JDialog, is there any set modal command can do it??
Nope.
The reason is because of program flow:
System.out.println("first line");
JDialog dialog = new JDialog(modal);
dialog.setVisible(true); // blocks this flow if and only if modal is true
System.out.println("second line");
Try putting a button in the dialog which prints out "button pressed".
If you press the button each time before closing the dialog you will get:
when modal is true:
first line
button presed
second line
when modal is false:
first line
second line
button prese -
JButton on XP non-modal Jdialog doen't work.
I recently upgraded from 1.3 to 1.4 while upgrading my OS from NT 4.0 to XP.
In a stand-alone application I have non-modal JDialog's that are launched as threads so that I can have multiple instances of them running simultaneously. There are JButton's on the JDialog's which no longer respond to any mouse events even though I can execute them via the keyboard using the tab and enter keys. They work just fine under 1.3 or if I make them modal.
Any thoughts?Hello,
Issue is-
There are JButton's on the JDialog's which no longer respond to any mouse events even though I can execute them via the keyboard using the tab and enter keys. They work just fine if I make them modal.
Plz suggest -
Hi All,
I want a non modal JDialog which is used to show the message to the user that it is searching for the records, when a search is performed and records are retrieved from the database. When the search is going on user might hit cancel on the JDialog to cancel the search. My problem is, the cancel button on the Search dialog is not catching the event and user is not able to select the cancel option on the dialog.
Here is my code :
class SearchWindow extends JDialog {
private JPanel btnPanel;
private JLabel lblSearch;
private JButton btnCancel;
* Constructor
public SearchWindow() {
super((Frame)null, false);
setTitle("Searching Shipment Legs");
cancelled = false;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
close();
Container contentPane = getContentPane();
contentPane.setLayout(null);
addButtons();
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setSize(new Dimension(300, 100));
setSize(300,100);
setLocation((screenSize.width-700)/2,(screenSize.height-450)/2);
private void addButtons() {
btnPanel = new JPanel();
btnPanel.setLayout(new BorderLayout());
lblSearch = new JLabel("Searching..........");
btnCancel = new JButton("Cancel");
btnPanel.setBackground(Color.lightGray);
lblSearch.setBackground(Color.lightGray);
btnCancel.setBackground(Color.lightGray);
btnPanel.add(lblSearch, BorderLayout.CENTER);
btnPanel.add(btnCancel, BorderLayout.SOUTH);
btnCancel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
System.out.println("cancel");
cancelled = true;
close();
btnPanel.setBounds(0,0,200,50);
this.getContentPane().add(btnPanel);
lblSearch.setVisible(true);
btnCancel.setVisible(true);
this.getContentPane().validate();
public void close() {
this.setVisible(false);
this.dispose();
public void show() {
super.show();
paintComponents(getGraphics());
this.setModal(false);
Any help is greatly appreciated.
Thanks,
BhaskarHi Haroldsmith
I am calling this search window in one of my programs where on button click it will fetch the records from the database. When this process is on, search dialog is shown up. Ths dialog is shown correctly and its getting closed as soon as the search is completed. But the probelm is its not allowing me to click on cancel button.
Bhaskar -
Issues opening pdf in a modal jdialog
Hi guys,
I've a strange issue, I can't solve it.
I'm newbie of java swing and this is a very difficult issue.
I've a jdialog modal. In this jDialog I've a button, clicking on it a pdf is generated with itext.
I observed that:
-if I try to generate pdf from a frame, pdf is shown over the frame.
-if I try to generate pdf from a jdialog swing(that's case I need) pdf is shown below jdialog...so I can't see pdf without closing jdialog and it's not good.
How can I proceed in the second case?
Thankshi,
thanks for your reply...I try to addo more detail.
I have a modal jdialog.
In it I have a button, clicking on it is called a method to create a pdf with itext.
Here a snippet of code
try {
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
create(document);
document.close();
String[] command = new String[3];
command [0] = "cmd.exe";
command [1] = "/C";
command [2] = "\"" + FILE+ "\"";
Runtime.getRuntime().exec(command );
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Si è verificato il seguente errore: "+e.getMessage(), "Errore stampa pdf", JOptionPane.ERROR);
return;
}Following this way pdf is opened but it's shown under the modal jdialog that called it.
So for watching it I need to close modal jdialog.
How can I run pdf to make it OVER a modal jdialog?
Thanks,
Regards -
Fillable PDF Form messes up layout and structure in Adobe Readers 7 or 8
Hi Team,
I have designed a Fillable PDF Form in Live Cycle Designer 8.2.1, the form works perfectly well in Adobe Reader versions 9.0 or greater,
but messes up layout and structure in Adobe Readers 7 or 8 or older versions.., more over users are having problems, saving data.
I have Acrobat Professional with Adobe Reader Extensions, but still having issues, could any one please help,
Thanks,
Younge..You should post this in the LiveCycle Designer forum if you havne't already.
-
Stopping execution without modal Jdialog
Hi there,
I am writing a gui that needs to wait for a button click. I used to use a modal JDialog for this, which worked fine, but I have recently changed the GUI to a wizard style, and I would like to simply redraw a Card every time, rather than having a popup Dialog.
Basically the program will show info, but this info will change whenever the button is pressed.
How would I go about this without using a modal JDialog?, In other words, how can I make the program wait until button press? I am very confused about wait() and notify(), its not as simple as I thought, maybe someone can enlighten me.
Thanks for any helpWow ok, I really screwed up on this one. Let me start again, For anyone still reading:
The program I am writing presents the User with a choice to which they must reply with using a button press. This is easily done using a JDialog that is Modal as the program waits until the JDialog is disposed.
My question is whether it is possible to achieve this effect without using a JDialog. I am doing it without a JDialog because I do not wish to have any pop ups, rather just a constantly refreshing JPanel.
To sum up: How do I achieve the modal effect of a JDialog using other Components?
I am unable to post any code right now, if anyone needs to see some I will gladly post it tommorow.
Thanks again! -
Execute code after show() in a Modal JDialog
Is there any way of executing a piece of code after a Modal JDialog's show() method ? I tried to run the code using SwingUtilities.invokeLater to no use. Any ideas ?
Thanks !Thanks Jamie !
Adding a new thread wasn't required. I found the solution in some forum. The main issue was to get focus to a textfield in JDialog along with displaying a JPopupMenu against it. I could get the focus in but the popup wasn't showing. In brief this is what solved it.
Assuming JTextField is testField. I add this listener to the textField just before calling JDialog.show().
<code>
private FocusListener fListen = new FocusListener()
public void focusGained(FocusEvent e)
// showPop() logic
public void focusLost(FocusEvent e)
testField.removeFocusListener(fListen);
testField.requestFocus();
</code> -
Freezed modal jdialog in japplet
I have made an applet program whose method javascript calls. And the method of the applet shows modal JDialog. But, after showing modal JDialog, the applet is locked.
In Windows XP + JRE 6.2 + Firefox 2.0, it is locked just after showing modal JDialog.
But in Windowx XP + JRE 5,4,3 + Firefox 2.0/IE, it is OK(working well) And, in Other OSes and Other browser, it is OK
You can test this and watch java source in the below link.
http://whoispso.cafe24.com/freezed_dialog_in_ff/FreezedJDialogInFFInJRE6InWindows.html
http://whoispso.cafe24.com/freezed_dialog_in_ff/FreezedJDialogInFFInJRE6InWindows.java
import java.awt.Frame;
import javax.swing.JApplet;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class FreezedJDialogInFFInJRE6InWindows extends JApplet {
private Frame rootFrame;
public void init() {
rootFrame = JOptionPane.getFrameForComponent(this);
showJDialog("it is called from init()");
public String showJDialogFromJS() {
String msg = "it is called from showJDialogFromJS()";
showJDialog(msg);
return msg;
private void showJDialog(String msg) {
JDialog dialog = new JDialog(rootFrame, msg, true);
dialog.setSize(300, 300);
dialog.setResizable(false);
dialog.setVisible(true);
{code}
{code:javascript}
<HTML>
<HEAD>
<SCRIPT language = "javascript">
function install() {
var applet_tag = '<APPLET ID = "dialog_test"' +
'CODE = "FreezedJDialogInIEInJRE5InWindows.class"' +
'WIDTH = "0"' +
'HEIGHT = "0">';
document.getElementById("applet_space").innerHTML = applet_tag;
function showJDialog() {
if(!is_installed()) {
alert("not installed!");
return;
var returnValue;
try {
returnValue = document.dialog_test.showJDialogFromJS();
} catch (err) {
alert(err);
alert("return value is " + returnValue);
function is_installed() {
if(document.dialog_test == null) {
return false;
} else {
return true;
</SCRIPT>
</HEAD>
<BODY>
<DIV id = "applet_space"></DIV>
<SCRIPT>
install();
</SCRIPT>
<INPUT TYPE="button" NAME="button" VALUE="showJDialog()" onClick=javascript:showJDialog()>
</BODY>
</HTML>
{code}Try placing it on the awt thread, for example:
private void showJDialog(String msg) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new JDialog(rootFrame, msg, true);
dialog.setSize(300, 300);
dialog.setResizable(false);
dialog.setVisible(true);
{code} -
How to invoke OK button in Modal JDialog
Hi,
I have two buttons in a Modal JDialog box OK, Save. The functionalities are written in actionPerformed(). But when I click the OK or Save button, the function is not getting invoked.
JDialog jd = new JDialog();
jd.setModal(true);
jd.show;
Please give me a solution.
Thanks in Advance....Actually, I didn't use Swing for some years now.
Hava a look at the API doc. Seems like you can pass a Component instead of a String for the message. Maybe you could use a ScrollPane or something like that.
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JOptionPane.html
What doc says about message arg:
A descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant. However, the type of this parameter is actually Object. Its interpretation depends on its type:
Object[]
An array of objects is interpreted as a series of messages (one per object) arranged in a vertical stack. The interpretation is recursive -- each object in the array is interpreted according to its type.
Component
The Component is displayed in the dialog.
Icon
The Icon is wrapped in a JLabel and displayed in the dialog.
others
The object is converted to a String by calling its toString method. The result is wrapped in a JLabel and displayed.
Maybe you are looking for
-
Creating Sales Order with reference to Quotation from different Sales Area
Hi, I would like to inform you that our customer (GE ENERGY OC) from Europe have a requirement where they want to create sales orders with reference to quotation that is from different sales area. Standard SAP functionality doesn't allow this feature
-
My Camera Is Recording Color Bands Can Someone Help???
I use a samsung sc-hmx20c HD camera to record my ps3 video game footage For some reason when i record there are red and blue lines of color either up and down or in circular directions.I use a tripod and turn all the lights off in the room. The camer
-
I've backed up my iphone on a mac but now want to use it on a PC
i now want to transfer songs onto it onto my PC instead of my mac. i've got some paid apps. thanks.
-
My husband got new cell phone and we want to find his iPhone from my computer
In my household I have a Mac 27inch, and my iphone 4. My husband just got an iphone 4s and does not have his own pc or mac to sync with. He will get one in a few months. In the meantime how can he sync contacts, Find His Iphone? sync photos until
-
Search Help for KUNNR, depending on a certain BUKRS
Hy gurus, I have the following selection-screen PARAMETERS : p_bukrs LIKE bsid-bukrs OBLIGATORY. SELECT-OPTIONS: s_kunnr FOR bsid-kunnr. I'd like to make the search help of KUNNR dependable on the input of p_bukrs. I don't want to create any se