Os exemplos deste artigo compartilham o código específico do código -fonte do sistema de gerenciamento de informações do aluno Java para sua referência. O conteúdo específico é o seguinte
1. Classe dostudetManage (interface principal)
pacote com.sms3; importar java.awt.*; importar javax.swing.*; importar java.awt.event.*; classe pública StudentManage estende o jframe implementa o ActionListener { / ** * @param args * / public static void main (string [] args) {// tlo-gen-generated método stub new StudentManage (); } // ======== Controle do painel Private jlabel querylab = null; privado jtextfield querytxt = null; private jbutton querybtn = null; private jbutton allbtn = null; Private Jtable ResultTB = NULL; private jscrollPane jsp = null; private jbutton addbtn = null; private jbutton deletebtn = null; private jbutton updateBtn = null; private jpanel top = nulo; Partido JPanel privado = nulo; // ======= STUMODEL PRIVADO SM = NULL; // construtor public studentManage () {/**************************************** querytxt = new jtextfield (10); querybtn = new jbutton ("Query"); allbtn = new jbutton ("All"); ///0t. querybtn.setActionCommand ("Query"); allbtn.addactionListener (isto); allbtn.setActionCommand ("All"); // =========== Coluna de adição e deliciosidade addBtn = new JButton ("Add"); deletebtn = novo jbutton ("delete"); updateBtn = new jbutton ("modify"); /// ... addbtn.setActionCommand ("Add"); deletebtn.addactionListener (isto); deletebtn.setActionCommand ("delete"); deletebtn.addactionListener (isto); deletebtn.setActionCommand ("delete"); updatebtn.addactionListener (this); updateBtn.SetActionCommand ("Update"); // ======== Crie o layout geral da janela // ...... barra de consulta de nível superior = novo jpanel (); top.add (Querylab); top.add (Querytxt); top.add (Querybtn); top.add (allbtn); // ....... Bottom.Add (addBtn); Bottom.Add (DeleteBtn); Bottom.add (UpdateBtn); // ...... barra de exibição de nível médio sm = new stumodel (); String sql = "selecione * de stu"; Sm.QuerySTU (SQL, NULL); resultadotb = novo jtable (sm); jsp = novo jscrollPane (resultadoTB); ///0tuct o layout geral this.add (top, borderlayout.north); this.add (jsp, borderlayout.center); this.add (Bottom, borderlayout.south); // ======= Defina a propriedade da janela this.SetSize (400, 300); this.setDefaultCloseoperation (jframe.exit_on_close); this.setVisible (true); this.setResizable (false); } // Ouça @Override public void ActionPerformed (ActionEvent E) {// TODO Método Geralgenado Stub if (E.GetActionCommand (). Equals ("Query")) { /***************** if (name.Length ()! = 0) {// ========= Quando a entrada do nome é válida, execute a consulta ///5 String [] paras = {name}; ///... update o modelo jtableUpdate (sql, paras); } else {// ========== Quando o nome estiver vazio, defina o lembrete JoptionPane.showMessagedialog (this, "a entrada de nome não pode estar vazia"); }} else if (e.getActionCommand (). Equals ("add")) { / ************************************** / new Stuadddialog (this, "Adicionar informações do aluno", verdadeiro); String sql = "selecione * de stu"; jTableUpdate (SQL, NULL); } else if (e.getActionCommand (). Equals ("all")) { / ************************************** todos os programas ************************* / string sql = "selecione*de stu"; jTableUpdate (SQL, NULL); } else if (e.getActionCommand (). Equals ("Delete")) { /************************************** /// ======== Obtenha o número da linha de seleção int ser rOWNUM = this.ResultTB.GetSelectedRow (); if (rownum == -1) {joptionpane.showMessagedialog (isto, "Selecione uma linha"); retornar ; } // ======== Obtenha o número de identificação do aluno string stuid = (string) sm.getValuEat (rownum, 0); // ========= Exclua o aluno String sql = "Exclua do Stu Where Stuid =?"; String [] paras = {stuid}; Stumodel tmp = new stumodel (); tmp.cudstu (SQL, paras); // ========== Atualizar modelo SQL = "SELECT * FROM STU"; jTableUpdate (SQL, NULL); } else if (e.getActionCommand (). Equals ("update")) { /****************************** Modificar ************************** /// ========== Obtenha o número da linha de seleção int. if (rownum == -1) {joptionpane.showMessagedialog (isto, "Selecione uma linha"); retornar ; } new StuUpDatedialog (isto, "Modifique as informações do aluno", True, SM, ROWNUM); String sql = "selecione * de stu"; jTableUpdate (SQL, NULL); }} // ========== Atualize os dados em jtable public void jTableUpdate (String sql, string [] paras) {//...create modelo sm = new stumodel (); Sm.QueryStu (SQL, parágrafos); /// ... update o resultadotb.setModel (SM); }}2. Classe de Stumodel (modelo de banco de dados do aluno)
pacote com.sms3; importar java.sql.resultset; importar java.util.Vector; importar javax.swing.table.abstracttableModel; classe pública Stumodel estende abstrataTableModel {columnNames de vetor privado; Vector de vetor privado; // public stumodel () {string sql = "selecione * de stu"; String [] paras = {}; } // ======== Adicione e exclua os alunos public boolean Cudstu (String sql, string [] paras) {return sqlhelper (). Cudexecute (sql, paras); } // ========= dúvida o aluno public void querystu (string sql, string [] paras) {sqlhelper sqlhelper = null; // ========= Inicialize JTABLE Information ColumnNames = new Vector (); rowdates = new Vector (); columnNames.add ("Número do aluno"); columnNames.add ("nome"); columnNames.add ("gênero"); columnNames.add ("Age"); columnNames.add ("home"); columnNames.add ("parte"); tente {sqlhelper = new sqlhelper (); ResultSet rs = sqlhelper.QueryExecute (SQL, parágrafos); while (rs.Next ()) {Vector Row = new Vector (); row.add (rs.getString (1)); row.add (rs.getString (2)); row.add (rs.getString (3)); row.add (rs.getString (4)); row.add (rs.getString (5)); row.add (rs.getString (6)); rowdates.add (linha); }} catch (Exceção e) {// TODO: lide a exceção} finalmente {sqlhelper.close (); }} @Override public int getColumnCount () {// TODO Method Auto-Gerated Stub Return this.columnNames.size (); } @Override public int getRowCount () {// TODO Method Auto-Gerated Stub Return this.rowdates.size (); } @Override Public Object getValuEat (int linha, int col) {// TODO Método Gerado Auto-Gerado Stub if (! Rowdates.isEmpty ()) retornar ((vetor) this.rowdates.get (linha)). Get (col); mais retornar nulo; } @Override public String getColumnName (int column) {// TODO Method Auto-Gerated Stub Return (String) this.columnNames.get (colun); }}3. Classe Stuadddialog (Adicione subinterface Informações do aluno)
pacote com.sms3; importar java.awt.borderlayout; importar java.awt.dialog; importar java.awt.frame; importar java.awt.gridlayout; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar javax.swing.*; A classe pública Stuadddialog estende o JDialog implementa o ActionListener {// ========= Controle do painel // ...... Barra de título esquerda Private Jlabel Idlab, Namelab, Sexlab, agelab, jglab, Deptlab; ///... Selecione Preencha as informações sobre o direito de preencher a coluna Private JTextField Idtxt, Nametxt, Sextxt, AGETXT, JGTXT, Depttxt; /// ....Add e cancelar o botão Private JButton addbtn, cancelbtn; ///0ty..Layout Controle privado jpanel à esquerda, centro, fundo; // construtor public stuadddialog (proprietário do quadro, título da string, modal booleano) {// ======== Reescreva o método da classe pai Super (proprietário, título, modal); // =========== A coluna de tag à esquerda é idlab = new Jlabel ("Número do aluno:"); namelab = new jlabel ("nome:"); sexlab = new jlabel ("gênero:"); agelab = new jlabel ("idade:"); jglab = new jlabel ("cidade natal:"); Deptlab = new Jlabel ("Direction:"); // ========= Preencha a coluna de informações à direita é idtxt = new jtextfield (); nametxt = new jtextfield (); sexxt = new jtextfield (); AGETXT = new JTextField (); AGETXT = new JTextField (); AGETXT = new JTextField (); jgtxt = new jtextfield (); DeptTxt = new JTextField (); // ========== Adicionar e cancelar botões addbtn = new jbutton ("add"); cancelbtn = new jbutton ("cancel"); ///....Add Ouça addbtn.addactionListener (this); addbtn.setActionCommand ("Add"); cancelbtn.addactionListener (isto); cancelbtn.setActionCommand ("cancel"); // ======= Crie layout // ...... Crie coluna esquerda = new JPanel (); left.setLayout (New GridLayout (6, 1)); esquerda.add (idlab); esquerda.add (namelab); esquerda.add (sexlab); esquerda.add (agelab); esquerda.add (jglab); esquerda.add (Deptlab); ///....Crie o centro da coluna direita = new JPanel (); Center.setLayout (New GridLayout (6, 1)); Center.add (IDTXT); Center.Add (Nametxt); Center.add (sexxt); Center.Add (AGETXT); Center.add (jgtxt); Center.Add (DeptTxt); // =================== O botão Adicionar e Cancelar no botão subjacente = novo jpanel (); Bottom.Add (addBtn); Bottom.add (cancelbtn); // ========= Layout geral this.add (esquerda, borderlayout.west); this.add (centro, borderlayout.center); this.add (Bottom, borderlayout.south); // ========== Defina o atributo de janela this.SetSize (300, 250); this.setResizable (false); this.setVisible (true); } @Override public void ActionPerformed (ActionEvent E) {// TODO Método Gerado Auto-Goldado if (E.GetActionCommand (). Equals ("Add")) { / ***************************** String sql = "inserir nos valores da STU (?,?,?,,? ,?)"; String [] paras = {idtxt.getText (), nametxt.getText (), sexxt.getText (), agetxt.getText (), jgtxt.getText (), depttxt.getText ()}; se (! // ======== Feche a janela this.dispose (); } else if (e.getActionCommand (). Equals ("cancel")) {// ======== Feche a janela this.dispose (); }}}4. StuUpDatedialog Class (Modifique a subinterface do aluno)
pacote com.sms3; importar java.awt.borderlayout; importar java.awt.frame; importar java.awt.gridlayout; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar javax.swing.jbutton; importar javax.swing.jdialog; importar javax.swing.jlabel; importar javax.swing.JOptionPane; importar javax.swing.jpanel; importar javax.swing.jpanel; importar javax.swing.jtextfield; importar javax.swing.table.abstracttableModel; classe pública StuUpDatedialog estende JDialog implementa ActionListener {// ========= Controles de painel // ...... Barra de título esquerda Private Jlabel Idlab, Namelab, Sexlab, AgeLab, JGLAB, Deptlab; ///0… direito Selecione preencher a coluna Private JTextField Idtxt, Nametxt, Sextxt, AgeTxt, Jgtxt, Depttxt; //...Add e Cancelar botão Private JButton addbtn, cancelbtn; ///0ty..Layout Controle privado jpanel à esquerda, centro, fundo; // construtor public stuupdatedialog (proprietário do quadro, título da string, modal booleano, stumodel sm, int rownum) {// ========= Reescreva o método da classe pai (proprietário, título, modal); // =========== A barra de etiqueta esquerda Idlab = new Jlabel ("Número do aluno:"); namelab = new jlabel ("nome:"); sexlab = new jlabel ("gênero:"); agelab = new jlabel ("idade:"); jglab = new jlabel ("cidade natal:"); Deptlab = new Jlabel ("Dimension:"); // ======== preencha as informações no lado direito idtxt = new jtextfield (); idtxt.settext ((string) sm.getValueat (rownum, 0)); idtxt.setEditable (false); nametxt = new jtextfield (); nametxt.settext ((string) sm.getValueat (rownum, 1)); sexxt = new jtextfield (); sexxt.settext ((string) sm.getValueat (rownum, 2)); AGETXT = new JTextField (); AGETXT.SETTEXT ((String) Sm.getValuEat (ROWNUM, 3)); jgtxt = new jtextfield (); jgtxt.settext ((string) sm.getValueat (rownum, 4)); DeptTxt = new JTextField (); Depttxt.Settext ((String) Sm.getValueat (ROWNUM, 5)); // ======== Adicionar e cancelar botões addbtn = new jbutton ("modify"); cancelbtn = new jbutton ("cancel"); ///....Add Ouça addbtn.addactionListener (this); addbtn.setActionCommand ("Update"); cancelbtn.addactionListener (isto); cancelbtn.setActionCommand ("cancel"); // ======== Crie layout // ...... Crie esquerda = new JPanel (); left.setLayout (New GridLayout (6, 1)); esquerda.add (idlab); esquerda.add (namelab); esquerda.add (sexlab); esquerda.add (agelab); esquerda.add (jglab); esquerda.add (Deptlab); ///....Crie o centro da coluna direita = new JPanel (); Center.setLayout (New GridLayout (6, 1)); Center.add (IDTXT); Center.Add (Nametxt); Center.add (sexxt); Center.Add (AGETXT); Center.add (jgtxt); Center.Add (DeptTxt); // ============ A camada inferior Adicionar e cancelar o botão inferior = new JPanel (); Bottom.Add (addBtn); Bottom.add (cancelbtn); // ======== Layout geral this.add (esquerda, borderlayout.west); this.add (centro, borderlayout.center); this.add (Bottom, borderlayout.south); // ========== Defina o atributo de janela this.SetSize (300, 250); this.setResizable (false); this.setVisible (true); } @Override public void ActionPerformed (ActionEvent E) {// TODO Método Geralado Auto Stub if (E.GetActionCommand (). Equals ("Update")) { / ******************************* String sql = "update stu set atuname =?, Stusex =?, Stuage =?, Stujg =?, Studep =? Onde stuid =?"; String [] paras = {nametxt.getText (), sexxt.getText (), agetxt.getText (), jgtxt.getText (), depttxt.getText (), idtxt.getText ()}; If (! // ======== Feche a janela this.dispose (); } else if (e.getActionCommand (). Equals ("cancel")) {// ======== Feche a janela this.dispose (); }}} 5. Classe Sqlhelper (classe de banco de dados mais baixa)
pacote com.sms3; importar java.sql.*; classe pública sqlhelper {// ========= DATABASE CONEXÃO PRIVADA CT = NULL; Private PreparedStatement PS = NULL; Resultado privado rs = nulo; private string driver = "com.microsoft.sqlserver.jdbc.sqlserverdriver"; private string url = "jdbc: sqlserver: //127.0.0.1: 1433; banco de dados = studentman"; String privada User = "SA"; private string passwd = "****"; // ========== Query Public ResultSet QueryExecute (String sql, String [] paras) {try {// ======== 1. Carregar a classe do driver.ForName (driver); // ======== 2. Connect CT = DriverManager.getConnection (URL, Usuário, Passwd); // ======== 3. Create preparado pS = ct.Preparestatement (SQL); // ======== 4. Atribua um valor ao ponto de interrogação se (paras! }} // ======= 5. Executar rs = ps.executeQuery (); } catch (Exceção e) {// TODO: lidar com a exceção e.printStackTrace (); } finalmente {//this.close (); } // ========= Retorno Retorno Rs Rs; } // ======== Adicione ou exclua public boolean cudexecute (string sql, string [] paras) {boolean b = true; tente {// ======== 1. Carregar a classe do driver.ForName (driver); // ======= 2. Connect CT = DriverManager.getConnection (URL, Usuário, Passwd); // ======= 3. Create preparado pS = ct.Preparestatement (SQL); // ======== 4. Atribua um valor ao ponto de interrogação para (int i = 0; i <paras.length; i ++) {ps.SetString (i+1, paras [i]); } // ======== 5. Execute if (ps.executeUpdate ()! = 1) b = false; } catch (Exceção e) {// TODO: manipular a exceção b = false; E.PrintStackTrace (); } finalmente {this.close (); } // ========== Retorno Retorno de Retorno B; } // ========== Fechar recursos public void Close () {tente {if (rs! = Null) rs.close (); if (ps! = null) ps.close (); if (ct! = null) ct.close (); } Catch (Exceção E2) {// TODO: lidar com a Exceção E2.PrintStackTrace (); }}}Interface principal
Adicionar interface de informações do aluno
Modifique a interface de informações do aluno
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.