I am somewhat new to UI Development in Java and Swing. I would like to open a dialog when I click an item in my JMenuBar and then validate that dialog before closing it (so pressing the X or the ok button will not work unless the users input meets certain conditions).
At the moment, my project is structured like this:
Window.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Window {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(Window::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Stackoverflow - Testproject");
JMenuBar menubar = new JMenuBar();
JMenu j_menu_test = new JMenu("Test");
JMenuItem j_menuitem_clickme = new JMenuItem("Click me");
j_menu_test.add(j_menuitem_clickme);
j_menuitem_clickme.addActionListener(new Open_Dialog());
menubar.add(j_menu_test);
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
static class Open_Dialog implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
DialogPanel dialog = new DialogPanel();
int result = JOptionPane.showConfirmDialog(null, dialog, "Test", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
//do something
}
}
}
}
And the content of my dialog in DialogPanel.java
import javax.swing.*;
public class DialogPanel extends JPanel {
private JTextField id_field = new JTextField(20);
public DialogPanel() {
add(new JLabel("Insert something to validate here:"));
add(id_field);
}
}
Now obviously this does not do any dialog validation yet. I have been trying to get that to work, and I have found a working example of dialog validation but I can't seem to integrate it/get the whole thing to run. If I take the example from the link, how do I call dialog? I think I am not supposed to use the JOptionPane but everytime I try to display a JDialog any other way I get an "Boxlayout cannot be shared" error. Please help me integrate this into my code.