-1

** 我已根据收到的帮助和评论更新了我的问题。现在我的问题是:调用以下代码后:

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

我想让用户在搜索框(JDialog)中输入输入。所以基本上在被调用时“停止”我的 JFrame 类searchBox.showSearchDialog()(它不应该已经这样做了吗??甚至在setVisible(true)被调用之后)。然后,一旦用户在 JDialog(searchBox 类)中按下 OK,“恢复”我的 JFrame 类并调用String query = searchBox.getQuery();.

我认为从 searchBox.showSearchDialog() 方法调用正弦 setVisible(true) 应该停止但它没有。我的代码只是从:

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

不停止。所以我的查询字符串全部错误,因为在我的代码调用该方法之前,用户从来没有机会输入任何内容。

JFrame班级:

import java.awt.Cursor;

@SuppressWarnings("serial") 公共类 DataPersistance 扩展 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);
}

}

现在,JDialogSearch盒子出现了。这是完整的课程:

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;
}

}
4

1 回答 1

5

您的对话框需要提供某种吸气剂,调用者可以调用它来恢复状态......

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;
    }

然后在您的调用代码中调用showSearchDialog,如果用户单击Ok,则获取搜索结果...

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

当然,您可以简单地使用 a JOptionPane,但这取决于您的要求。

查看如何制作对话框以获取更多详细信息

更新

为了使应用程序在对话框可见时停止执行,您需要使对话框成为模态。

在 dialogs 构造函数中,您应该调用setModal(true),这在上一节末尾提供的链接中进行了详细讨论

于 2013-07-11T05:18:48.797 回答