简体   繁体   English

如何从父JFrame访问JDialog信息?

[英]How to Access JDialog information from parent JFrame?

** 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). 我想让用户在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). 因此,基本上在searchBox.showSearchDialog()时“停止”了我的JFrame类searchBox.showSearchDialog()它是否应该这样做?甚至在setVisible(true)之后也没有)。 And then once the user presses OK in the JDialog (searchBox class) "resume" my JFrame class and call the String query = searchBox.getQuery(); 然后,一旦用户在JDialog(searchBox类)中按OK,“恢复”我的JFrame类并调用String query = searchBox.getQuery(); .

I thought that sine setVisible(true) is called from the searchBox.showSearchDialog() method is should halt but it does not. 我认为从searchBox.showSearchDialog()方法调用的正弦setVisible(true)应该停止,但不是。 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: JFrame类别:

import java.awt.Cursor;

@SuppressWarnings("serial") public class DataPersistance extends JFrame { @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);
}

}

Now, the JDialogSearch box comes up. 现在, JDialogSearch框出现。 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;
}

}

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... 然后在你的电话代码,你会打电话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);

Of course, you could simple use a JOptionPane , but that would depend on your requirements. 当然,您可以简单地使用JOptionPane ,但这取决于您的要求。

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 在对话框构造函数中,您应该调用setModal(true) ,在上一节末尾提供的链接中对此进行了详细讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM