Java应用程序窗口非常慢

时间:2015-01-19 20:47:54

标签: java mysql swing

您好我创建了一个Java Application Windown,它应该连接到数据库并更改订单状态,并且还会更详细地查看它们。但是没有理由这个应用程序变得非常慢并且没有执行UPDATE命令,所以代码:

/**
 * Create the application.
 */
public EstagioGUITeste() {
    initialize();
}

private Connection ligacao = null;
private JComboBox cbEstado;
private JTable table;

private void iniLigacao() {
    String url = "jdbc:mysql://localhost/science4estagio";
    String user = "root";
    String password = "";

    try {
        ligacao = DriverManager.getConnection(url, user, password);
    } catch (SQLException se) {
        se.getLocalizedMessage();
    }
}

private void closeLigacao() {
    try {
        if (ligacao != null) {
            ligacao.close();

        }
    } catch (SQLException se) {
        se.getLocalizedMessage();
    }
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 1012, 403);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new CardLayout(0, 0));
    JPanel panelLogin = new JPanel();
    frame.getContentPane().add(panelLogin, "panelLogin");
    GridBagLayout gbl_panelLogin = new GridBagLayout();
    gbl_panelLogin.columnWidths = new int[] { 225, 358, 225, 0 };
    gbl_panelLogin.rowHeights = new int[] { 39, 0, 0, 0, 0, 48, 0 };
    gbl_panelLogin.columnWeights = new double[] { 1.0, 0.0, 1.0,
            Double.MIN_VALUE };
    gbl_panelLogin.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, Double.MIN_VALUE };
    panelLogin.setLayout(gbl_panelLogin);

    JLabel lblNewLabel = new JLabel("Login");
    lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 32));
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
    gbc_lblNewLabel.anchor = GridBagConstraints.NORTH;
    gbc_lblNewLabel.gridx = 1;
    gbc_lblNewLabel.gridy = 0;
    panelLogin.add(lblNewLabel, gbc_lblNewLabel);

    JLabel lblNewLabel_1 = new JLabel("User:");
    GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
    gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
    gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
    gbc_lblNewLabel_1.gridx = 0;
    gbc_lblNewLabel_1.gridy = 2;
    panelLogin.add(lblNewLabel_1, gbc_lblNewLabel_1);

    txtUser = new JTextField();
    GridBagConstraints gbc_txtUser = new GridBagConstraints();
    gbc_txtUser.insets = new Insets(0, 0, 5, 5);
    gbc_txtUser.fill = GridBagConstraints.HORIZONTAL;
    gbc_txtUser.gridx = 1;
    gbc_txtUser.gridy = 2;
    panelLogin.add(txtUser, gbc_txtUser);
    txtUser.setColumns(10);

    JLabel lblPassowrd = new JLabel("Password:");
    GridBagConstraints gbc_lblPassowrd = new GridBagConstraints();
    gbc_lblPassowrd.anchor = GridBagConstraints.EAST;
    gbc_lblPassowrd.insets = new Insets(0, 0, 5, 5);
    gbc_lblPassowrd.gridx = 0;
    gbc_lblPassowrd.gridy = 3;
    panelLogin.add(lblPassowrd, gbc_lblPassowrd);

    passwordField = new JPasswordField();
    passwordField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                iniLigacao();
                try {
                    String sql = "SELECT * FROM view_ecra2 ";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }

                closeLigacao();

                iniLigacao();
                try {
                    PreparedStatement inst = ligacao
                            .prepareStatement("SELECT * FROM utilizadorpassword WHERE User=? and Password=? ");
                    inst.setString(1, txtUser.getText());
                    inst.setString(2, passwordField.getText());
                    ResultSet resultado = inst.executeQuery();
                    int contador = 0;
                    while (resultado.next()) {
                        contador = contador + 1;

                    }
                    if (contador == 1) {
                        JOptionPane.showMessageDialog(null,
                                "Acesso Garantido\n");
                        CardLayout card = (CardLayout) frame
                                .getContentPane().getLayout();
                        card.show(frame.getContentPane(), "panelPrincipal");
                    } else if (contador > 1) {
                        JOptionPane.showMessageDialog(null,
                                "Utilizador e password duplicados");
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Utilizador e/ou password errados");
                    }
                    inst.close();
                } catch (SQLException e1) {
                    System.out
                            .println("Impossivel ligar à base de dados\n");
                    System.out.println(e1.getLocalizedMessage());
                }
                closeLigacao();
            }
        }
    });
    GridBagConstraints gbc_passwordField = new GridBagConstraints();
    gbc_passwordField.insets = new Insets(0, 0, 5, 5);
    gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
    gbc_passwordField.gridx = 1;
    gbc_passwordField.gridy = 3;
    panelLogin.add(passwordField, gbc_passwordField);

    JButton btnNewButton = new JButton("Entrar");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            iniLigacao();
            try {
                String sql = "SELECT * FROM view_ecra2;";
                PreparedStatement st = ligacao.prepareStatement(sql);
                ResultSet rs = st.executeQuery();
                table.setModel(DbUtils.resultSetToTableModel(rs));
            } catch (SQLException se) {
                se.getLocalizedMessage();
            }

            closeLigacao();

            iniLigacao();
            try {
                PreparedStatement inst = ligacao
                        .prepareStatement("SELECT * FROM utilizadorpassword WHERE User=? and Password=? ");
                inst.setString(1, txtUser.getText());
                inst.setString(2, passwordField.getText());
                ResultSet resultado = inst.executeQuery();
                int contador = 0;
                while (resultado.next()) {
                    contador = contador + 1;

                }
                if (contador == 1) {
                    JOptionPane.showMessageDialog(null,
                            "Acesso Garantido\n");
                    CardLayout card = (CardLayout) frame.getContentPane()
                            .getLayout();
                    card.show(frame.getContentPane(), "panelPrincipal");
                } else if (contador > 1) {
                    JOptionPane.showMessageDialog(null,
                            "Utilizador e password duplicados");
                } else {
                    JOptionPane.showMessageDialog(null,
                            "Utilizador e/ou password errados");
                }
                inst.close();
            } catch (SQLException e1) {
                System.out.println("Impossivel ligar à base de dados\n");
                System.out.println(e1.getLocalizedMessage());
            }
            closeLigacao();

        }
    });
    GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
    gbc_btnNewButton.insets = new Insets(0, 0, 0, 5);
    gbc_btnNewButton.gridx = 1;
    gbc_btnNewButton.gridy = 5;
    panelLogin.add(btnNewButton, gbc_btnNewButton);

    JPanel panelPrincipal = new JPanel();
    frame.getContentPane().add(panelPrincipal, "panelPrincipal");
    GridBagLayout gbl_panelPrincipal = new GridBagLayout();
    gbl_panelPrincipal.columnWidths = new int[] { 26, 44, 78, 169, 124, 69,
            24, 0 };
    gbl_panelPrincipal.rowHeights = new int[] { 66, 104, 41, 0 };
    gbl_panelPrincipal.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0,
            1.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_panelPrincipal.rowWeights = new double[] { 0.0, 1.0, 0.0,
            Double.MIN_VALUE };
    panelPrincipal.setLayout(gbl_panelPrincipal);

    JButton btnCarregarDados = new JButton("Recarregar dados");
    btnCarregarDados.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            iniLigacao();
            try {
                String sql = "SELECT * FROM view_ecra2;";
                PreparedStatement st = ligacao.prepareStatement(sql);
                ResultSet rs = st.executeQuery();
                table.setModel(DbUtils.resultSetToTableModel(rs));
            } catch (SQLException se) {
                se.getLocalizedMessage();
            }
            cbEstado.setSelectedIndex(0);
            closeLigacao();
    }});
    JLabel lblNewLabel_2 = new JLabel("");
    lblNewLabel_2.setIcon(new ImageIcon("C:\\workspace\\Science4youTestes\\LogoPanelPrincipal.png"));
    GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
    gbc_lblNewLabel_2.fill = GridBagConstraints.BOTH;
    gbc_lblNewLabel_2.gridwidth = 5;
    gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
    gbc_lblNewLabel_2.gridx = 0;
    gbc_lblNewLabel_2.gridy = 0;
    panelPrincipal.add(lblNewLabel_2, gbc_lblNewLabel_2);
    GridBagConstraints gbc_btnCarregarDados = new GridBagConstraints();
    gbc_btnCarregarDados.insets = new Insets(0, 0, 5, 5);
    gbc_btnCarregarDados.fill = GridBagConstraints.BOTH;
    gbc_btnCarregarDados.gridx = 5;
    gbc_btnCarregarDados.gridy = 0;
    panelPrincipal.add(btnCarregarDados, gbc_btnCarregarDados);

    JScrollPane scrollPane = new JScrollPane();
    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridwidth = 5;
    gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
    gbc_scrollPane.gridx = 1;
    gbc_scrollPane.gridy = 1;
    panelPrincipal.add(scrollPane, gbc_scrollPane);

    table = new JTable();
    scrollPane.setViewportView(table);

    JLabel lblOrganizarPor = new JLabel("Mostrar Estado:");
    GridBagConstraints gbc_lblOrganizarPor = new GridBagConstraints();
    gbc_lblOrganizarPor.anchor = GridBagConstraints.EAST;
    gbc_lblOrganizarPor.insets = new Insets(0, 0, 0, 5);
    gbc_lblOrganizarPor.gridx = 1;
    gbc_lblOrganizarPor.gridy = 2;
    panelPrincipal.add(lblOrganizarPor, gbc_lblOrganizarPor);

    cbEstado = new JComboBox();
    cbEstado.setMaximumRowCount(4);
    cbEstado.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Object selected = cbEstado.getSelectedItem();
            iniLigacao();
            if (selected.toString().equals("Pendente")) {
                try {
                    String sql = "SELECT * FROM view_ecra2 WHERE Estado='P - Pendente' ORDER BY ID_Encomenda DESC";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                    st.executeQuery();
                    st.executeUpdate();
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
            } else if (selected.toString().equals("Confirmada")) {
                try {
                    String sql = "SELECT * FROM view_ecra2 WHERE Estado='C - Confirmada' ORDER BY ID_Encomenda DESC";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                    st.executeQuery();
                    st.executeUpdate();
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
            } else if (selected.toString().equals("Anulada")) {
                try {
                    String sql = "SELECT * FROM view_ecra2 WHERE Estado='X - Anulada' ORDER BY ID_Encomenda DESC";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                    st.executeQuery();
                    st.executeUpdate();
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
            } else if (selected.toString().equals("Reembolsada")) {
                try {
                    String sql = "SELECT * FROM view_ecra2 WHERE Estado='R - Reembolsada' ORDER BY ID_Encomenda DESC";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                    st.executeQuery();
                    st.executeUpdate();
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
            } else if (selected.toString().equals("Enviada")) {
                try {
                    String sql = "SELECT * FROM view_ecra2 WHERE Estado='S - Enviada' ORDER BY ID_Encomenda DESC";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                    st.executeQuery();
                    st.executeUpdate();
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
            } else {
                iniLigacao();
                try {
                    String sql = "SELECT * FROM view_ecra2";
                    PreparedStatement st = ligacao.prepareStatement(sql);
                    ResultSet rs = st.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));
                } catch (SQLException se) {
                    se.getLocalizedMessage();
                }
                cbEstado.setSelectedIndex(0);
                closeLigacao();

            }
            closeLigacao();
        }
    });
    cbEstado.setModel(new DefaultComboBoxModel(new String[] { "Enviada",
            "Reembolsada", "Pendente", "Confirmada", "Anulada" }));
    cbEstado.insertItemAt("", 0);
    cbEstado.setSelectedIndex(0);
    GridBagConstraints gbc_cbEstado = new GridBagConstraints();
    gbc_cbEstado.insets = new Insets(0, 0, 0, 5);
    gbc_cbEstado.gridx = 2;
    gbc_cbEstado.gridy = 2;
    panelPrincipal.add(cbEstado, gbc_cbEstado);

    JButton btnAlterarEstado = new JButton("Alterar Estado");
    btnAlterarEstado.addActionListener(new ActionListener() {
        private String targetSwitch;
        private long targetIDb;
        public void actionPerformed(ActionEvent e) {
                radPanel.add(btnEnv);
                radPanel.add(btnCon);
                radPanel.add(btnPen);
                radPanel.add(btnRee);
                radPanel.add(btnAnu);
                if(table.getSelectedRowCount()==0){
                    JOptionPane.showMessageDialog(frame, "Não selecionou nada");
                }else {
                int resposta2 = JOptionPane.showOptionDialog(null,
                        radPanel, "Altere o Estado da Encomenda",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (resposta2 == JOptionPane.OK_OPTION) {
                    int resposta = JOptionPane.showConfirmDialog(frame,
                            "Deseja alterar mesmo o estado da encomenda?",
                            "Confirme a eliminação",
                            JOptionPane.YES_NO_OPTION);
                    if (resposta == JOptionPane.YES_OPTION) {
                        Object targetIdteste = table.getValueAt(table.getSelectedRow(), 0);
                        try {
                            targetIDb = (long) targetIdteste;
                        } catch (ClassCastException ce){
                            ce.getLocalizedMessage();
                            ce.printStackTrace();
                        }

                        iniLigacao();
                        try{
                            PreparedStatement stt = ligacao
                                    .prepareStatement("SELECT view_ecra2_bg.Estado FROM view_ecra2_bg WHERE ID_Encomenda_BG=?");
                            stt.setLong(1, targetIDb);
                            ResultSet resul = stt.executeQuery();
                            resul.next();                               
                            String estadoAtual =resul.getString(1);
                            if(estadoAtual == "S"){
                                btnEnv.setSelected(true);
                            }
                        }catch(SQLException se){
                            se.getLocalizedMessage();
                        }

                        closeLigacao();



                        iniLigacao();
                        try {
                            PreparedStatement stt = ligacao
                                    .prepareStatement("UPDATE view_ecra2_bg SET Estado_BG='?' WHERE ID_Encomenda_BG=?");
                            Object targetSwitcher = btnGrp.getSelection().getSelectedObjects();

                            if(btnEnv.isSelected()){
                                stt.setString(1, "S");
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }else if(btnCon.isSelected()){
                                stt.setString(1, "C");
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }else if(btnPen.isSelected()){
                                stt.setString(1, "P");
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }else if(btnRee.isSelected()){
                                stt.setString(1, "R");
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }else if(btnAnu.isSelected()){
                                stt.setString(1, "X");
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }else {

                            }
                            if (targetSwitch!=null) {
                                System.out.println(targetSwitch);
                                stt.setLong(2, targetIDb);
                                stt.executeUpdate();
                            }
                            iniLigacao();
                            try {
                                String sql = "SELECT * FROM view_ecra2";
                                PreparedStatement st = ligacao.prepareStatement(sql);
                                ResultSet rs = st.executeQuery();
                                table.setModel(DbUtils.resultSetToTableModel(rs));
                            } catch (SQLException se) {
                                se.getLocalizedMessage();
                            }
                            cbEstado.setSelectedIndex(0);
                            closeLigacao();
                          } catch (SQLException se) {
                            se.getLocalizedMessage();
                        } catch(NullPointerException ne){
                            ne.getLocalizedMessage();
                            ne.printStackTrace();
                        }
                        closeLigacao();
                    }
                }
            }
    }
    });
    GridBagConstraints gbc_btnAlterarEstado = new GridBagConstraints();
    gbc_btnAlterarEstado.insets = new Insets(0, 0, 0, 5);
    gbc_btnAlterarEstado.gridx = 3;
    gbc_btnAlterarEstado.gridy = 2;
    panelPrincipal.add(btnAlterarEstado, gbc_btnAlterarEstado);
    JButton btnDetalhesDeEncomenda = new JButton("Detalhes de encomenda");
    btnDetalhesDeEncomenda.addActionListener(new ActionListener() {
        private long targetIDb;

        public void actionPerformed(ActionEvent arg0) {
            if(table.getSelectedRowCount()==0){
                JOptionPane.showMessageDialog(frame, "Não selecionou nada");
            }else {
            Object targetIdteste = table.getValueAt(table.getSelectedRow(), 0);
            String targetNome = table.getValueAt(table.getSelectedRow(), 4).toString();
            try {
                targetIDb = (long) targetIdteste;
            } catch (ClassCastException ce){
                ce.getLocalizedMessage();
                ce.printStackTrace();
            }
            iniLigacao();
            try {
                String sql = "SELECT Nome_Item, Quantidade, Preço FROM view_ecra3_bg WHERE ID_Encomenda=?";
                PreparedStatement st = ligacao.prepareStatement(sql);
                st.setLong(1, targetIDb);
                ResultSet rs = st.executeQuery();
                table_ecra2.setModel(DbUtils.resultSetToTableModel(rs));

                textNomeShow.setText(targetNome);
                textIdShow.setText(String.valueOf(targetIDb));

                Double precoTotal = 0.0;

                int numItems = table_ecra2.getRowCount();

                for (int i = 0; i < numItems; i++) {
                    precoTotal += Double.parseDouble(table_ecra2
                            .getValueAt(i, 2).toString());
                }
                textTotal.setText(precoTotal+"€");

            } catch (SQLException se) {
                se.getLocalizedMessage();
            }
            CardLayout card = (CardLayout) frame.getContentPane().getLayout();
            card.show(frame.getContentPane(), "panelEncomenda");
            }
        }
    });
    GridBagConstraints gbc_btnDetalhesDeEncomenda = new GridBagConstraints();
    gbc_btnDetalhesDeEncomenda.insets = new Insets(0, 0, 0, 5);
    gbc_btnDetalhesDeEncomenda.gridx = 5;
    gbc_btnDetalhesDeEncomenda.gridy = 2;
    panelPrincipal.add(btnDetalhesDeEncomenda, gbc_btnDetalhesDeEncomenda);

    JPanel panelEncomenda = new JPanel();
    frame.getContentPane().add(panelEncomenda, "panelEncomenda");
    GridBagLayout gbl_panelEncomenda = new GridBagLayout();
    gbl_panelEncomenda.columnWidths = new int[] { 181, 315, 20, 82, 184, 36, 0, 189, 73, 62, 0 };
    gbl_panelEncomenda.rowHeights = new int[] { 37, 0, 0, 0, 0 };
    gbl_panelEncomenda.columnWeights = new double[] { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
            Double.MIN_VALUE };
    gbl_panelEncomenda.rowWeights = new double[] { 0.0, 0.0, 1.0, 0.0,
            Double.MIN_VALUE };
    panelEncomenda.setLayout(gbl_panelEncomenda);

    JLabel label = new JLabel("");
    label.setIcon(new ImageIcon("C:\\workspace\\Science4youTestes\\LogoPanelPrincipal.png"));
    GridBagConstraints gbc_label = new GridBagConstraints();
    gbc_label.fill = GridBagConstraints.HORIZONTAL;
    gbc_label.gridwidth = 5;
    gbc_label.gridheight = 2;
    gbc_label.insets = new Insets(0, 0, 5, 5);
    gbc_label.gridx = 0;
    gbc_label.gridy = 0;
    panelEncomenda.add(label, gbc_label);

                                    JLabel lblId_1 = new JLabel("ID:");
                                    GridBagConstraints gbc_lblId_1 = new GridBagConstraints();
                                    gbc_lblId_1.anchor = GridBagConstraints.EAST;
                                    gbc_lblId_1.insets = new Insets(0, 0, 5, 5);
                                    gbc_lblId_1.gridx = 5;
                                    gbc_lblId_1.gridy = 0;
                                    panelEncomenda.add(lblId_1, gbc_lblId_1);

                            textIdShow = new JTextField();
                            textIdShow.setEditable(false);
                            GridBagConstraints gbc_textIdShow = new GridBagConstraints();
                            gbc_textIdShow.gridwidth = 2;
                            gbc_textIdShow.fill = GridBagConstraints.HORIZONTAL;
                            gbc_textIdShow.insets = new Insets(0, 0, 5, 5);
                            gbc_textIdShow.gridx = 7;
                            gbc_textIdShow.gridy = 0;
                            panelEncomenda.add(textIdShow, gbc_textIdShow);
                            textIdShow.setColumns(10);

                    JLabel lblNome_1 = new JLabel("Nome:");
                    GridBagConstraints gbc_lblNome_1 = new GridBagConstraints();
                    gbc_lblNome_1.anchor = GridBagConstraints.EAST;
                    gbc_lblNome_1.insets = new Insets(0, 0, 5, 5);
                    gbc_lblNome_1.gridx = 5;
                    gbc_lblNome_1.gridy = 1;
                    panelEncomenda.add(lblNome_1, gbc_lblNome_1);

                                            textNomeShow = new JTextField();
                                            textNomeShow.setEditable(false);
                                            GridBagConstraints gbc_textNomeShow = new GridBagConstraints();
                                            gbc_textNomeShow.gridwidth = 2;
                                            gbc_textNomeShow.fill = GridBagConstraints.HORIZONTAL;
                                            gbc_textNomeShow.insets = new Insets(0, 0, 5, 5);
                                            gbc_textNomeShow.gridx = 7;
                                            gbc_textNomeShow.gridy = 1;
                                            panelEncomenda.add(textNomeShow, gbc_textNomeShow);
                                            textNomeShow.setColumns(10);

                                    JScrollPane scrollPane_1 = new JScrollPane();
                                    GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
                                    gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
                                    gbc_scrollPane_1.gridwidth = 7;
                                    gbc_scrollPane_1.insets = new Insets(0, 0, 5, 5);
                                    gbc_scrollPane_1.gridx = 1;
                                    gbc_scrollPane_1.gridy = 2;
                                    panelEncomenda.add(scrollPane_1, gbc_scrollPane_1);

                                            table_ecra2 = new JTable();
                                            table_ecra2.setModel(new DefaultTableModel(new Object[][] {},
                                                    new String[] {}));
                                            scrollPane_1.setViewportView(table_ecra2);

                            JButton btnVoltarAoMenu = new JButton("Voltar ao menu Principal");
                            btnVoltarAoMenu.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent arg0) {
                                    iniLigacao();
                                    try {
                                        String sql = "SELECT * FROM view_ecra2;";
                                        PreparedStatement st = ligacao.prepareStatement(sql);
                                        ResultSet rs = st.executeQuery();
                                        table.setModel(DbUtils.resultSetToTableModel(rs));
                                        CardLayout card = (CardLayout) frame.getContentPane().getLayout();
                                        card.show(frame.getContentPane(), "panelPrincipal");
                                    } catch (SQLException e) {
                                        e.printStackTrace();
                                    }
                                    closeLigacao();
                                }
                            });
                            GridBagConstraints gbc_btnVoltarAoMenu = new GridBagConstraints();
                            gbc_btnVoltarAoMenu.anchor = GridBagConstraints.WEST;
                            gbc_btnVoltarAoMenu.insets = new Insets(0, 0, 0, 5);
                            gbc_btnVoltarAoMenu.gridx = 1;
                            gbc_btnVoltarAoMenu.gridy = 3;
                            panelEncomenda.add(btnVoltarAoMenu, gbc_btnVoltarAoMenu);

                            JLabel lblTotal = new JLabel("Total:");
                            GridBagConstraints gbc_lblTotal = new GridBagConstraints();
                            gbc_lblTotal.anchor = GridBagConstraints.EAST;
                            gbc_lblTotal.insets = new Insets(0, 0, 0, 5);
                            gbc_lblTotal.gridx = 5;
                            gbc_lblTotal.gridy = 3;
                            panelEncomenda.add(lblTotal, gbc_lblTotal);

                    textTotal = new JTextField();
                    textTotal.setEditable(false);
                    GridBagConstraints gbc_textTotal = new GridBagConstraints();
                    gbc_textTotal.gridwidth = 2;
                    gbc_textTotal.fill = GridBagConstraints.HORIZONTAL;
                    gbc_textTotal.insets = new Insets(0, 0, 0, 5);
                    gbc_textTotal.gridx = 7;
                    gbc_textTotal.gridy = 3;
                    panelEncomenda.add(textTotal, gbc_textTotal);
                    textTotal.setColumns(10);
}

} 提前谢谢

2 个答案:

答案 0 :(得分:4)

有一连串的问题......

首先...

Swing是一个单线程环境,这意味着无论何时在事件调度线程的上下文中执行长时间运行或阻塞操作,都会阻止处理事件队列,这会使您的应用程序显示为冷冻......因为它有

有关详细信息,请参阅Concurrency in Swing

有许多方法可以解决这个问题,但请记住,Swing也不是线程安全的,这意味着UI元素的任何交互,修改或创建都必须在Event Dispatching Thread的上下文中完成。解决此问题的一种更简单的方法是使用SwingWorker,它允许您对用户界面进行publish更新,并在EDT的上下文中process进行更新。

有关详细信息,请参阅Worker Threads and SwingWorker ...

其次...

KeyListener不适合与任何文本组件一起使用,有一系列原因,但在您的情况下,您无法保证 Enter 是操作键这个平台可能会引起一些用户的问题(当你尝试改变它时,人们会习惯于工作并且不喜欢它)。

请参阅How to Write an Action Listeners,了解更为合适的方法,以便在字段被执行时得到通知&#34;

第三...

资源管理,基本上,你创建了一堆资源,但你没有适当地管理它们......

例如,这......

try {
    String sql = "SELECT * FROM view_ecra2 ";
    PreparedStatement st = ligacao.prepareStatement(sql);
    ResultSet rs = st.executeQuery();
    table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException se) {
    se.getLocalizedMessage();
}

应该更像......

String sql = "SELECT * FROM view_ecra2 ";
try (PreparedStatement st = ligacao.prepareStatement(sql)) {
    try (ResultSet rs = st.executeQuery()) {
        table.setModel(DbUtils.resultSetToTableModel(rs));
    }
} catch (SQLException se) {
    se.getLocalizedMessage();
}

try-with-resources将确保PreparedStaementResultSet正确关闭,这将确保数据库不会泄漏资源,这可能会影响性能

有关详细信息,请参阅The try-with-resources Statement

附加...

您用于&#34;密码的功能&#34;并且Entrar按钮看起来是相同的,而不是复制代码,尝试编写一个方法,您可以从ActionListener调用,或者甚至编写一个可以应用的ActionListener两个组成部分......

使用绝对路径lblNewLabel_2.setIcon(new ImageIcon("C:\\workspace\\Science4youTestes\\LogoPanelPrincipal.png"));是一个非常糟糕的主意,因为资源的位置对于其他计算机来说可能不相同。

更好的解决方案是将资源嵌入应用程序上下文中。使用Eclipse和Netbeans,您可以通过将资源放在项目的src目录中来实现,这将确保在构建应用程序时,它们将捆绑在生成的jar文件中。

然后,您需要使用Class#getResourceClass#getResourceAsStream加载它们,具体取决于您的需求。

例如,如果将LogoPanelPrincipal.png放在项目resources/images目录中的src目录中,则需要使用类似......

的内容。
BufferedImage img = ImageIO.read(getClass().getResource("resources/images/LogoPanelPrincipal.png");
lblNewLabel_2.setIcon(new ImageIcon(img));

使用ImageIO.read的原因是因为如果图像无法加载,它会抛出IOException,而不像ImageIcon,如果图像可以&#39,它会无声地失败因某种原因加载......

有关详细信息,请参阅Reading/Loading an Image

永远不要将密码信息存储在未加密的数据库中(如果这只是您自己正在做的事情,请务必小心,您应该始终遵循最佳做法)。

不是存储密码,而是应该为密码生成某种哈希(例如MD5)并将其发送到数据库,这样你就不会通过网络发送密码信息,在那里它可以被截获...

答案 1 :(得分:0)

您正在对事件调度线程执行数据库操作,该线程将阻止GUI。 您应该使用SwingWorker