-1

** I have updated my question per help and comments I received. Now my question is: After calling the following code:

SearchBox searchBox = new SearchBox(); // SearchBox extends JDialog
int state = searchBox.showSearchDialog(); // Sets visible to true and returns state

I want to let the user enter input in the searchBox (JDialog). So basically "halt" my JFrame class when searchBox.showSearchDialog() is called (shouldn't it do that already?? It is not even after setVisible(true) is called). And then once the user presses OK in the JDialog (searchBox class) "resume" my JFrame class and call the String query = searchBox.getQuery();.

I thought that sine setVisible(true) is called from the searchBox.showSearchDialog() method is should halt but it does not. My code just runs through from:

seachBox = new SearchBox();
int state = seachBox.showSeachDialog();
String query = searchBox.getQuery();

without stopping. So my query string is coming back all wrong because the user never had a chance to input anything before my code calls that method.

JFrame Class:

import java.awt.Cursor;

@SuppressWarnings("serial") public class DataPersistance extends JFrame {

private JPanel contentPane;
private JTable table;
private DataPersistanceController controller;
private DatabaseConnector dbConnector;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    // Sets the look and feel to be like windows
    try
    {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e1)
    {
        e1.printStackTrace();
    } catch (InstantiationException e1)
    {
        e1.printStackTrace();
    } catch (IllegalAccessException e1)
    {
        e1.printStackTrace();
    } catch (UnsupportedLookAndFeelException e1)
    {
        e1.printStackTrace();
    }

    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                DataPersistance frame = new DataPersistance();
                frame.setVisible(true);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 * 
 * @throws SQLException
 */
public DataPersistance() throws SQLException
{
    this.controller = new DataPersistanceController();
    this.dbConnector = new DatabaseConnector();

    setTitle("Data Persistance Tool - Enterra Solutions, LLC.");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1000, 750);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    mnFile.setMnemonic(KeyEvent.VK_F);
    menuBar.add(mnFile);

    JMenuItem mntmConnect = new JMenuItem("Connect");
    mnFile.add(mntmConnect);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            dispose();
        }
    });
    mnFile.add(mntmExit);

    JMenu mnEdit = new JMenu("Edit");
    mnEdit.setMnemonic(KeyEvent.VK_E);
    menuBar.add(mnEdit);

    JMenuItem mntmCopyResults = new JMenuItem("Copy Results");
    mnEdit.add(mntmCopyResults);

    JMenu mnTools = new JMenu("Tools");
    mnTools.setMnemonic(KeyEvent.VK_T);
    menuBar.add(mnTools);

    JMenuItem mntmKbLoad = new JMenuItem("Auto Load (from KB)");
    mnTools.add(mntmKbLoad);

    JMenuItem mntmManualLoadke = new JMenuItem("Manual Load (.ke file)");
    mntmManualLoadke.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            JFileChooser fChoose = new JFileChooser();

            fChoose.setFileFilter(new FileFilter()
            {
                @Override
                public boolean accept(File f)
                {
                    return (f.isFile()
                            && (f.getName().toLowerCase().endsWith(".txt") || f
                                    .getName().toLowerCase()
                                    .endsWith(".ke")) || f.isDirectory());
                }

                @Override
                public String getDescription()
                {
                    return null;
                }
            });

            // showOpenDialog returns some value. Did not use.
            fChoose.showOpenDialog(contentPane);

            fChoose.setVisible(true);

            if (fChoose.getSelectedFile() != null)
            {
                try
                {
                    setCursor(Cursor
                            .getPredefinedCursor(Cursor.WAIT_CURSOR));
                    controller.manuallyLoadRecipes(fChoose
                            .getSelectedFile());

                } catch (FileNotFoundException e1)
                {
                    setCursor(Cursor
                            .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    JOptionPane
                            .showMessageDialog(
                                    contentPane,
                                    "There was a problem loading file into the database.",
                                    "Load Error", JOptionPane.ERROR_MESSAGE);

                    System.out.println("File not found");
                    return;

                } catch (SQLException e1)
                {
                    setCursor(Cursor
                            .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    JOptionPane
                            .showMessageDialog(
                                    contentPane,
                                    "There was a problem loading file into the database.",
                                    "Load Error", JOptionPane.ERROR_MESSAGE);
                    System.out.println("SQL Error");
                    return;

                }

                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                JOptionPane.showMessageDialog(contentPane,
                        "Load was successful.");

            }
        }
    });
    mnTools.add(mntmManualLoadke);

    JMenuItem mntmGenerateKeText = new JMenuItem("Generate KE Text");
    mnTools.add(mntmGenerateKeText);

    JMenuItem mntmDeleteRecipies = new JMenuItem("Delete Recipies");
    mnTools.add(mntmDeleteRecipies);

    JMenu mnSettings = new JMenu("Settings");
    mnSettings.setMnemonic(KeyEvent.VK_S);
    menuBar.add(mnSettings);

    JMenuItem mntmView = new JMenuItem("View");
    mnSettings.add(mntmView);

    JMenuItem mntmConnectionPreferences = new JMenuItem(
            "Connection Preferences");
    mnSettings.add(mntmConnectionPreferences);

    JMenu mnHelp = new JMenu("Help");
    mnHelp.setMnemonic(KeyEvent.VK_H);
    menuBar.add(mnHelp);

    JMenuItem mntmReadmeFile = new JMenuItem("Readme");
    mnHelp.add(mntmReadmeFile);

    JMenuItem mntmAboutDataPersistance = new JMenuItem("About");
    mntmAboutDataPersistance.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            JDialog aboutWindow = new AboutDialog();
            aboutWindow.setVisible(true);
        }
    });

    mnHelp.add(mntmAboutDataPersistance);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    gbl_contentPane.columnWidths = new int[]
    { 36, 23, 82, 464, 243, 0, 0 };
    gbl_contentPane.rowHeights = new int[]
    { 0, 0, 0, 9, 127, 0, 0, 0, 0, 0 };
    gbl_contentPane.columnWeights = new double[]
    { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_contentPane.rowWeights = new double[]
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE };
    contentPane.setLayout(gbl_contentPane);

    JToolBar toolBar = new JToolBar();
    toolBar.setFloatable(false);
    GridBagConstraints gbc_toolBar = new GridBagConstraints();
    gbc_toolBar.anchor = GridBagConstraints.LINE_START;
    gbc_toolBar.gridwidth = 6;
    gbc_toolBar.insets = new Insets(0, 0, 5, 0);
    gbc_toolBar.gridx = 0;
    gbc_toolBar.gridy = 0;
    contentPane.add(toolBar, gbc_toolBar);

    JButton btnNewButton = new JButton("Search");
    btnNewButton.setHorizontalAlignment(SwingConstants.LEFT);
    btnNewButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            // TODO when search button is clicked
            SearchBox searchBox = new SearchBox();
            int state = searchBox.showSearchDialog();
            String query = searchBox.getQuery();

            if (state == searchBox.OK_STATE)
            {
                try
                {
                    ResultSet results = dbConnector.executeQuery(query);
                    DefaultTableModel tm = (DefaultTableModel) table
                            .getModel();
                    table.setModel(DbUtils.resultSetToTableModel(results));
                    tm.fireTableDataChanged();

                } catch (SQLException e1)
                {
                    e1.printStackTrace();
                }
            }

        }
    });
    toolBar.add(btnNewButton);

    JSeparator separator = new JSeparator();
    GridBagConstraints gbc_separator = new GridBagConstraints();
    gbc_separator.fill = GridBagConstraints.HORIZONTAL;
    gbc_separator.gridwidth = 6;
    gbc_separator.insets = new Insets(0, 0, 5, 5);
    gbc_separator.gridx = 0;
    gbc_separator.gridy = 1;
    contentPane.add(separator, gbc_separator);

    JLabel lblNewLabel = new JLabel("Data Persistance Tool");
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.gridwidth = 6;
    gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
    gbc_lblNewLabel.gridx = 0;
    gbc_lblNewLabel.gridy = 2;
    contentPane.add(lblNewLabel, gbc_lblNewLabel);
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 35));

    // ========= CREATE JTABLE AND POPULATE WIH MODEL =========
    table = new JTable();
    table.setModel(dbConnector.getAllFromDatabaseTableModel());
    table.addMouseListener(new MouseAdapter()
    {
        public void mouseClicked(MouseEvent e)
        {
            if (e.getClickCount() == 2)
            {
                JTable target = (JTable) e.getSource();
                int row = target.getSelectedRow();
                int column = target.getSelectedColumn();
                // do some action
            }
        }
    });

    // table.setMinimumSize(new Dimension(200, 400));
    // table.setPreferredSize(new Dimension(200, 600));
    table.setAutoCreateRowSorter(true);
    table.setFillsViewportHeight(true);
    table.getColumnModel().getColumn(0).setPreferredWidth(10);
    table.getColumnModel().getColumn(1).setPreferredWidth(5);
    // table = new JTable();
    GridBagConstraints gbc_table = new GridBagConstraints();
    gbc_table.insets = new Insets(0, 0, 5, 0);
    gbc_table.gridwidth = 6;
    gbc_table.gridheight = 4;
    gbc_table.fill = GridBagConstraints.BOTH;
    gbc_table.gridx = 0;
    gbc_table.gridy = 4;

    // TODO Lines commented because of memory
    // insert table inside scrollpane
    JScrollPane scrollPane = new JScrollPane(table);
    // add table inside scrollpane
    contentPane.add(scrollPane, gbc_table);

    JLabel lblV = new JLabel("v1.0.0 - Enterra Solutions, LLC.");
    GridBagConstraints gbc_lblV = new GridBagConstraints();
    gbc_lblV.gridwidth = 6;
    gbc_lblV.gridx = 0;
    gbc_lblV.gridy = 8;
    contentPane.add(lblV, gbc_lblV);

    JButton btnRefresh = new JButton("Refresh");
    btnRefresh.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            try
            {
                DefaultTableModel tm = (DefaultTableModel) table.getModel();
                table.setModel(dbConnector.getAllFromDatabaseTableModel());
                tm.fireTableDataChanged();

            } catch (SQLException e1)
            {
                e1.printStackTrace();
            }
        }
    });
    toolBar.add(btnRefresh);
}

}

Now, the JDialogSearch box comes up. Here is the full class:

import java.awt.BorderLayout;

@SuppressWarnings("serial")
public class SearchBox extends JDialog
{
private final JPanel contentPanel = new JPanel();
private JTextField textFieldGUID;
private JTextField textFieldTitle;
private JTextField textFieldCallsFor;
private JTextField textFieldContains;
public static final int OK_STATE = 0;
public static final int CANCEL_STATE = 1;
private int state = CANCEL_STATE;
String query;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    try
    {
        SearchBox dialog = new SearchBox();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

/**
 * Create the dialog.
 */
public SearchBox()
{
    setBounds(100, 100, 350, 300);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.WEST);
    GridBagLayout gbl_contentPanel = new GridBagLayout();
    gbl_contentPanel.columnWidths = new int[]
    { 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20 };
    gbl_contentPanel.rowHeights = new int[]
    { 34, 0, 0, 0, 0, 0, 0, 0, 20 };
    gbl_contentPanel.columnWeights = new double[]
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0,
            Double.MIN_VALUE };
    gbl_contentPanel.rowWeights = new double[]
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
    contentPanel.setLayout(gbl_contentPanel);

    JLabel lblNewLabel = new JLabel("Recipe Search");
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.anchor = GridBagConstraints.NORTH;
    gbc_lblNewLabel.gridwidth = 14;
    gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
    gbc_lblNewLabel.gridx = 0;
    gbc_lblNewLabel.gridy = 0;
    contentPanel.add(lblNewLabel, gbc_lblNewLabel);

    final JCheckBox chckbxGuid = new JCheckBox("GUID");
    GridBagConstraints gbc_chckbxGuid = new GridBagConstraints();
    gbc_chckbxGuid.anchor = GridBagConstraints.WEST;
    gbc_chckbxGuid.insets = new Insets(0, 0, 5, 5);
    gbc_chckbxGuid.gridx = 0;
    gbc_chckbxGuid.gridy = 1;
    contentPanel.add(chckbxGuid, gbc_chckbxGuid);

    textFieldGUID = new JTextField();
    GridBagConstraints gbc_textField = new GridBagConstraints();
    gbc_textField.gridwidth = 11;
    gbc_textField.insets = new Insets(0, 0, 5, 5);
    gbc_textField.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField.gridx = 2;
    gbc_textField.gridy = 1;
    contentPanel.add(textFieldGUID, gbc_textField);
    textFieldGUID.setColumns(10);

    final JCheckBox chckbxTitle = new JCheckBox("Title");
    GridBagConstraints gbc_chckbxTitle = new GridBagConstraints();
    gbc_chckbxTitle.anchor = GridBagConstraints.WEST;
    gbc_chckbxTitle.insets = new Insets(0, 0, 5, 5);
    gbc_chckbxTitle.gridx = 0;
    gbc_chckbxTitle.gridy = 2;
    contentPanel.add(chckbxTitle, gbc_chckbxTitle);

    textFieldTitle = new JTextField();
    GridBagConstraints gbc_textField_1 = new GridBagConstraints();
    gbc_textField_1.gridwidth = 11;
    gbc_textField_1.insets = new Insets(0, 0, 5, 5);
    gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField_1.gridx = 2;
    gbc_textField_1.gridy = 2;
    contentPanel.add(textFieldTitle, gbc_textField_1);
    textFieldTitle.setColumns(10);

    final JCheckBox chckbxCallsFor = new JCheckBox("Calls for");
    GridBagConstraints gbc_chckbxCallsFor = new GridBagConstraints();
    gbc_chckbxCallsFor.anchor = GridBagConstraints.WEST;
    gbc_chckbxCallsFor.insets = new Insets(0, 0, 5, 5);
    gbc_chckbxCallsFor.gridx = 0;
    gbc_chckbxCallsFor.gridy = 3;
    contentPanel.add(chckbxCallsFor, gbc_chckbxCallsFor);

    textFieldCallsFor = new JTextField();
    GridBagConstraints gbc_textField_2 = new GridBagConstraints();
    gbc_textField_2.gridwidth = 11;
    gbc_textField_2.insets = new Insets(0, 0, 5, 5);
    gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField_2.gridx = 2;
    gbc_textField_2.gridy = 3;
    contentPanel.add(textFieldCallsFor, gbc_textField_2);
    textFieldCallsFor.setColumns(10);

    final JCheckBox chckbxContains = new JCheckBox("Contains ");
    GridBagConstraints gbc_chckbxContains = new GridBagConstraints();
    gbc_chckbxContains.insets = new Insets(0, 0, 5, 5);
    gbc_chckbxContains.gridx = 0;
    gbc_chckbxContains.gridy = 4;
    contentPanel.add(chckbxContains, gbc_chckbxContains);

    textFieldContains = new JTextField();
    GridBagConstraints gbc_textField_3 = new GridBagConstraints();
    gbc_textField_3.gridwidth = 11;
    gbc_textField_3.insets = new Insets(0, 0, 5, 5);
    gbc_textField_3.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField_3.gridx = 2;
    gbc_textField_3.gridy = 4;
    contentPanel.add(textFieldContains, gbc_textField_3);
    textFieldContains.setColumns(10);

    JButton btnNewButton = new JButton("Search");
    btnNewButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            // TODO when search button is clicked
            query = "SELECT * FROM `temp`.`KB_Recipies`";

            // add WHERE if needed
            if (chckbxGuid.isSelected() || chckbxTitle.isSelected()
                    || chckbxCallsFor.isSelected()
                    || chckbxContains.isSelected())
            {
                query += " WHERE ";
            }
            // --------------------

            if (chckbxGuid.isSelected())
            {
                query += "fpItemGUID=" + textFieldGUID.getText();

                // add AND if needed
                if (chckbxTitle.isSelected() || chckbxCallsFor.isSelected()
                        || chckbxContains.isSelected())
                {
                    query += " AND ";
                }
            }

            if (chckbxTitle.isSelected())
            {
                query += "recipeTitle=" + textFieldTitle.getText();

                // add AND if needed
                if (chckbxCallsFor.isSelected()
                        || chckbxContains.isSelected())
                {
                    query += " AND ";
                }
            }
            // if (chckbxCallsFor.isSelected())
            // {
            // query += "fpItemGUID=" + textFieldGUID.getText();
            // // add AND if needed
            // if (chckbxContains.isSelected())
            // {
            // query += " AND ";
            // }
            // }
            // if (chckbxContains.isSelected())
            // {
            // query += "fpItemGUID=" + textFieldGUID.getText();
            // }
            query += ";";

            state = OK_STATE;

            dispose();
        }

    });

    GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
    gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
    gbc_btnNewButton.gridwidth = 14;
    gbc_btnNewButton.gridx = 0;
    gbc_btnNewButton.gridy = 6;
    contentPanel.add(btnNewButton, gbc_btnNewButton);
}

public boolean isBoxSelected()
{
    return true;
}

public String getQuery()
{
    return this.query;
}

public int showSearchDialog()
{
    // Other setup...
    setVisible(true);
    return state;
}

}
Richie Episcopo
  • 383
  • 1
  • 3
  • 15
  • For better help sooner, post an [SSCCE](http://sscce.org/). But typically, don't extend `JDialog` (or `JFrame`) just use an instance of them. In that case, you can put the text fields (etc.) in the main code & inspect them after the dialog is dismissed. Or in this case, perhaps a `JOptionPane` would do. I'll know more when I see an SSCCE. – Andrew Thompson Jul 11 '13 at 04:52
  • Sorry for the caps, I did not mean to convey yelling just stressing a point. But @AndrewThompson I updated my question with an (almost) full class because the full class is huge due to the GUI and grid layout code. All pertinent code is there. Could you please take a look (I slightly updated my question as well). Thank you! – Richie Episcopo Jul 11 '13 at 14:33
  • An 'almost full' class is *not* an SSCCE. Please read the document carefully for the reasons to post one. – Andrew Thompson Jul 11 '13 at 14:37
  • OK, edited now with the full code. Sorry about that. – Richie Episcopo Jul 11 '13 at 14:47
  • *"the full code"* You're either not reading, or not understanding, the SSCCE document! An SSCCE is ***one*** source file.. – Andrew Thompson Jul 11 '13 at 14:50
  • I am confused, I read and reread the document. Could you elaborate? By "file" do you want me to attach a .java file here somehow or paste in the code? And I can't have just one because my issue is across classes – Richie Episcopo Jul 11 '13 at 15:06
  • *"I can't have just one because my issue is across classes"* Aha! That is the misunderstanding. An SSCCE *can* have a number of classes, they just *cannot be declared `public`* and must be 'shoved in' at the end of the `main` source or made into inner classes. Also, please carefully review your message before submitting it. It is still not using code formatting correctly on the 2nd line of the 1st class. – Andrew Thompson Jul 11 '13 at 15:10
  • The SSCCE was a bit overkill for this problem, I appreciate your help but the solution to this problem was very simple and did not require an SSCCE. – Richie Episcopo Jul 11 '13 at 21:27

1 Answers1

5

Your dialog needs to provide some kind of getter that the caller can call to get back the state...

public class JDialogSearch ... {
    public static final int OK_STATE = 0;
    public static final int CANCEL_STATE = 1;
    // Cause it's really nice to know what the use did
    // ie canceled, okay'ed, didn't find results, what ever...
    private int state = CANCEL_STATE;
    private String searchResult;

    //....///

    OK.addActionListener( new ActionListener() {

        private class OKListener implements ActionListener 
        {
            public void actionPerformed(ActionEvent e) {
                searchResult = someSearchField.getText(); // Or what ever you need
                state = OK_STATE;
                dispose(); // close window
            }
        }
    });

    //...//

    public int showSearchDialog() {
        // Other setup...
        setVisible(true);
        return state;
    }

    public String getSearchResult() {
        return searchResult;
    }

Then in your call code you would call showSearchDialog and if the user clicks Ok, get the search result...

JDialogSeach dialog = new JDialogSeach(); // seach box implementation of JDialog
switch (dialog.showSearchDialog()) {
    case JDialogSeach.OK_STATE:
        mySearchResult = dialog.getSearchResult();
        break;
}
dialog.setVisible(true);

Of course, you could simple use a JOptionPane, but that would depend on your requirements.

Check out How to make Dialogs for more details

Updated

In order to make the application execution halt while the dialog is visible, you need to make the dialog modal.

In the dialogs constructor, you should be calling setModal(true), which is discussed at length in the link provided at the end of the last section

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Great, thank you for your help. It got me a litle closer, but now my code is not "halting" when setVisible(true) is called. I completly redid my original post could you take a look at it with my updated question? Thank you again! – Richie Episcopo Jul 11 '13 at 14:34
  • This was it! Thank you! I am new at GUI and didn't realize this had to be called. – Richie Episcopo Jul 11 '13 at 21:26