How to Make a Jframe Modal in Swing Java

How to make a JFrame Modal in Swing java

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Edit: updated Modality API link & added tutorial link (nod to @spork for the bump).

How to make a modal JFrame?

How to make a modal JFrame?

Don't. Use a modal JDialog -- that's precisely what they're for. You understand of course that a JDialog can hold a complex GUI, as complex as any held by a JFrame.

We often run into posts like these by folks who use a GUI-builder such as NetBeans to help them create their GUI's, and since the second window's code was created by the builder to extend a JFrame, it's very hard for the programmer to go back and change it to a dialog. The way to fix this is to try to gear your Swing code creation towards creation of JPanels, not top-level windows such as JFrames. This way you could use the created JPanel in a JFrame if desired, a JDialog if desired, a JApplet, or even another JPanel, whatever works best for the situation. This will increase your code's flexibility tremendously.

How To Make A JFrame/JPanel Modal So No Input Will Continue Until The Window Is Closed Or Button Pushed?

You need to make the dialog visible before it will block...

JDialog dialog = new JDialog(theDog,"theTitle", Dialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible();

Windows in Swing are not visible by default

Have a look at How to Make Dialogs for more details

Modal Window on top of Modal Window in java swing?

Here is an MCVE of modality working as advertised.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class ModalOverModal {

private JComponent ui = null;

ModalOverModal() {
initUI();
}

public void initUI() {
if (ui!=null) return;

ui = new JPanel(new GridLayout());
ui.setBorder(new EmptyBorder(40,40,40,40));

final JButton b1 = new JButton("Open Modal Dialog");
b1.setMargin(new Insets(40, 200, 40, 200));
ui.add(b1);

final JButton b2 = new JButton("Open 2nd Modal Dialog");

ActionListener al1 = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(b1, b2);
}
};
b1.addActionListener(al1);

ActionListener al2 = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(b2, "Close Me!");
}
};
b2.addActionListener(al2);
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
ModalOverModal o = new ModalOverModal();

JFrame f = new JFrame("Modal over Modal");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

How can I make a JFrame modal like a JOptionPane?

Again, you can put any complex gui into a JOptionPane. The JOptionPane show method's second parameter takes an Object which can be any Swing component. For example:

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

import com.roots.map.MapPanel.ControlPanel;

public class ComplexDialog extends JPanel {
public static final String[] COMBO_LABELS = { "Nombre 1",
"Identificacion 1", "Fecha 1", "Empresa 1", "Nombre 2",
"Identificacion 2", "Fecha 2", "Empresa 2", "Nombre 3",
"Identificacion 3", "Fecha 3", "Empresa 3", "Nombre 4",
"Identificacion 4", "Fecha 4", "Empresa 4", "Nombre 5",
"Identificacion 5", "Fecha 5", "Empresa 5", "Nombre 6",
"Identificacion 6", "Fecha 6", "Empresa 6", "Nombre 7",
"Identificacion 7", "Fecha 7", "Empresa 7" };
public static final String[] COMBO_ITEMS = { "January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December" };
private JTextArea textarea = new JTextArea(15, 30);
private Map<String, JComboBox> comboMap = new HashMap<String, JComboBox>();

public ComplexDialog() {
textarea.setLineWrap(true);
textarea.setWrapStyleWord(true);
for (int i = 0; i < 100; i++) {
textarea.append("This is a really large text. ");
}

JPanel comboPanel = new JPanel(new GridBagLayout());
for (int i = 0; i < COMBO_LABELS.length; i++) {
addToComboPanel(comboPanel, COMBO_LABELS[i], i);
}

int eb = 5;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(textarea));
add(Box.createVerticalStrut(5));
JScrollPane comboPanelScroll = new JScrollPane(comboPanel);
add(comboPanelScroll);

comboPanelScroll.getViewport().setPreferredSize(
textarea.getPreferredSize());
}

private void addToComboPanel(JPanel comboPanel, String labelText, int index) {
GridBagConstraints gbc = new GridBagConstraints(0, index, 1, 1, 0.2, 1.0,
GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0,
0, 5), 0, 0);
comboPanel.add(new JLabel(labelText, SwingConstants.RIGHT), gbc);

gbc = new GridBagConstraints(1, index, 1, 1, 1.0, 1.0,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(
0, 0, 0, 0), 0, 0);
JComboBox combo = new JComboBox(COMBO_ITEMS);
comboMap.put(labelText, combo);
comboPanel.add(combo, gbc);

}

public String getComboChoice(String key) {
JComboBox combo = comboMap.get(key);
if (combo != null) {
return combo.getSelectedItem().toString();
} else {
return "";
}
}

public String getTextAreaText() {
return textarea.getText();
}

public int showDialog() {
return JOptionPane.showOptionDialog(null, this, "Sirena",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
new String[] { "Aceptar", "Cancelar" }, "Aceptar");
}

private static void createAndShowGui() {
ComplexDialog dlg = new ComplexDialog();
int response = dlg.showDialog();
if (response == 0) {
System.out.println("JTextArea's text is:");
System.err.println(dlg.getTextAreaText());

System.out.println("Combo box selections are: ");
for (String comboLabel : COMBO_LABELS) {

System.out.printf("%20s: %s%n", comboLabel, dlg.getComboChoice(comboLabel));
}
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Unable to make JDialog modal

Try making the dialog modal BEFORE you try and make it visible. You can't change the modal state once the dialog is made visible...

JDialog jd=new JDialog(loginpage.this,"User Registration");
jd.setModal(true);
jd.setLayout(null); // THIS IS A BAD IDEA //
jd.setLocationRelativeTo(null);
// This is somewhat pointless, you've set relative location, but know overridden it...
// You should also be relying on the layout manager and pack to determine the size...
jd.setBounds(400,300, 479, 329);
jd.setResizable(false);
setLocationRelativeTo(loginpage.this);

// Add you other components

jd.setVisible(true);

Make JFrame modal or show JDialog on taskbar

I finally solved it by making the main component a JPanel and then embedding it in a JFrame or in a JDialog.

Thanks for the idea Andrew Thompson



Related Topics



Leave a reply



Submit