Make JInternalFrame behave like a modal dialog
843804Feb 16 2005 — edited Feb 17 2005Hi everyone,
after searching the web for many hours for a solution to make JInternalFrames act like modal dialogs and trying lots of different aproaches I finally created this (IMHO simple) solution.
Since many out there seem to have similar problems and are searching for a solution I would like to contribute this piece of code which demonstrates how to make a JIF "modal". If you have close and/or minimize and maximize buttons on the JIF you will have to add some handler to avoid their selection. This isn't included in the sample.
The sample opens two JIFs. The first one cannot be moved or selected. The second one always stays on top. I find this solution is much simpler (and works more reliable) than the one working with a glass pane being added to the JFrame. This solution doesn't need JOptionPane either.
The sample is kept very simple and it is definitely a quick hack but maybe it helps the one or the other. :-)
Enough of talking...here's the quick piece of code:
import javax.swing.*;
import javax.swing.event.*;
import java.beans.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame implements VetoableChangeListener
{
public Test()
{
super("Test");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JDesktopPane desktopPane = new JDesktopPane();
getContentPane().add(desktopPane);
// Overwrite some methods to disable movement of frames.
final JInternalFrame jif1 = new JInternalFrame("Frame 1")
{
public void setLocation(int x, int y)
{
}
public void setLocation(Point p)
{
}
public void setBounds(Rectangle r)
{
}
};
JInternalFrame jif2 = new JInternalFrame("Frame 2");
desktopPane.add(jif1);
desktopPane.add(jif2);
jif1.setSize(400, 300);
jif1.setLocation(50, 50);
jif1.setVisible(true);
jif1.getContentPane().add(new JTextArea("Textbereich"));
jif2.setSize(400, 300);
jif2.setLocation(100, 100);
jif2.setVisible(true);
setVisible(true);
// Set a glass pane on the JIF to avoid events to get to the frame.
JPanel gp = new JPanel();
gp.setSize(400, 300);
gp.setOpaque(true);
gp.setVisible(true);
gp.setBackground(java.awt.Color.RED);
jif1.setGlassPane(gp);
// Add a veto change listener to avoid the selection of the first frame.
jif1.addVetoableChangeListener(this);
}
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException
{
if(evt.getPropertyName().equals(JInternalFrame.IS_SELECTED_PROPERTY))
{
System.err.println("SELECTED");
throw new PropertyVetoException("Selected", null);
}
}
public static void main(String arguments[])
{
Test test = new Test();
}
}