使用条件处置“模态”对话框

时间:2014-06-14 09:26:25

标签: java swing jtable joptionpane

我有一个模式jDialog,我希望在使用JOptionPane在另一个Dialog中显示错误消息后满足特定条件时处理。我试图在JOptionPane对话框之后使用dispose()方法,但我的模态对话框仍然打开。 我的代码的相关部分如下:

    import java.awt.Component;
    import java.sql.*;
    import java.text.SimpleDateFormat;
    import javax.swing.JOptionPane;
    import javax.swing.table.DefaultTableModel;

    public class ReviewPatients extends javax.swing.JDialog {

    public ReviewPatients(java.awt.Frame parent, boolean modal) {
    super(parent, modal);

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "Name", "Address", "Number"
        }
    ) {
        Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class
        };
        boolean[] canEdit = new boolean [] {
            false, false, false
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(jTable1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1012, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );

    pack();


    jScrollPane1.setVisible(false);

e: 
{    
           try
            {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3307/doctor","root","Pranav123");
            String query="SELECT * FROM records_table WHERE Name LIKE 'some_name';";
            Statement st = con.createStatement();
            ResultSet rs= st.executeQuery(query);



            DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();

                //Clearing the table
                int rows=tmodel.getRowCount();
                while(rows>0)
                {
                    tmodel.removeRow(0);
                    rows--;
                }
                jTable1.setModel(tmodel);

            while(rs.next())
            {

                //Putting data into table
                tmodel.addRow(new Object[] {rs.getString(1),rs.getString(2),rs.getInt(4)});
                jTable1.setModel(tmodel);
            }

            }
            catch(Exception e)
            {
                System.out.println("Error: "+e);
            }

        if(jTable1.getRowCount()==0)
            {
                JOptionPane.showMessageDialog(this, "No records exist!");
                dispose();
                break e;
            }



         //Showing data   
        jScrollPane1.setVisible(true);


}    

public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            ReviewPatients dialog = new ReviewPatients(new javax.swing.JFrame(), true);
            dialog.setVisible(true);
        }
    });
}

e是我在发生错误时用于退出块的标签。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

JOptionPane中的所有静态方法都会创建模式对话框,即代码的执行会停止,直到用户解除对话框为止。如果要创建非模态对话框,请直接使用JDialog。有关详细信息,请参阅Java Swing Tutorial

<强>更新

如果我没有错,那么当没有记录时,您正在尝试 NOT 显示ReviewPatients对话框。如果是这种情况,最简单的解决方案就是将dispose()替换为System.exit(1)

更好的解决方案是检查数据库中是否有记录,并且:

  • 如果有记录,请创建ReviewPatients对话框并使用数据填充表格。
  • 如果没有记录,请显示JOptionPane以通知用户没有记录,并终止该程序。

另请注意:虽然允许,但请尽量不要将AWT组件与Swing组件混合使用(请参阅another Stack Overflow answer for the reasons)。

答案 1 :(得分:1)

我看到了许多问题,其中一些可能是相关的:

  • 不需要重复拨打setModel(),可能会意外通知听力表。

  • 清除DefaultTableModel的更简单方法是通过setRowCount(0)

  • 检查模型,而不是检查视图是否成功。更好的是,只需在异常处理程序中显示JOptionPane

  • 对话框的父级应该是JFrame

  • 还可以考虑使用SwingWorker更新表格模型。

经测试:

import java.sql.*;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * @see http://stackoverflow.com/a/24220593/230513
 */
public class ReviewPatients extends javax.swing.JDialog {

    public ReviewPatients(JFrame parent, boolean modal) {
        super(parent, modal);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        JTable table = new JTable();
        table.setModel(new DefaultTableModel(
            new Object[][]{},
            new String[]{
                "Name", "Address", "Number"
            }
        ) {
            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean[]{
                false, false, false
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(table, javax.swing.GroupLayout.PREFERRED_SIZE, 800, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(table, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
        this.setLocationRelativeTo(null);

        try {
            Class.forName("org.h2.Driver");
            Connection con = DriverManager.getConnection("jdbc:h2:file:~/src/java/jdbc/test;IFEXISTS=TRUE", "sa", "");
            String query = "SELECT * FROM CUSTOMER;";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(query);
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            while (rs.next()) {
                model.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getString(3)});
            }

        } catch (Exception e) {
            System.out.println("Error: " + e);
            JOptionPane.showMessageDialog(null, "No records exist!");
        }
        this.setVisible(true);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.pack();
                f.setVisible(true);
                ReviewPatients dialog = new ReviewPatients(f, true);
            }
        });
    }
}