Sistema de gerenciamento de campus baseado em Swing

1. Introdução

1.1 Histórico do projeto

Nossa escola organiza e organiza ativamente os alunos para participar de várias atividades culturais do campus, como ciência e tecnologia, literatura e arte e esportes em todos os níveis, e integra a educação ideológica e moral em atividades culturais animadas e específicas do campus. Devido à comunicação inconveniente em todos os níveis da escola, no processo de preparação do evento, seja o registro dos participantes do evento, o registro do público ou a coordenação dos organizadores, é uma tarefa demorada, trabalhosa e chata.

Do ponto de vista dos participantes do evento, toda vez que eles participam de um evento, eles precisam preencher um formulário de inscrição, e o local para enviar o formulário de inscrição geralmente é diferente: existem várias caixas de correio, mensagens de texto e assim por diante. Isso vai desperdiçar o tempo de todos, podendo até perder lugares e oportunidades; por outro lado, na perspectiva do organizador do evento, coletar fichas de inscrição e fazer estatísticas e resumi-las é muito trabalhoso e chato, aliado à pressão acadêmica, até certo ponto suprimiu o entusiasmo dos organizadores e participantes do evento. Em geral, falta um sistema eficiente de gerenciamento de informações cadastrais. Embora muitos alunos possuam computadores, eles não dão conta das características de eficiência do computador, e os recursos ociosos são mais proeminentes.Este é o ambiente para o desenvolvimento do sistema de gerenciamento de informações cadastrais.

1.2 Significado do projeto

As atividades culturais do campus são a alma do desenvolvimento escolar e uma forma importante de unir os corações das pessoas, mostrar a imagem da escola e melhorar a reputação da escola. Tem uma influência sutil na formação e continuação do bom espírito escolar de uma escola e Xuefeng, e na visão de vida e valores da escola.Esta influência e papel são muitas vezes incomparáveis ​​a qualquer currículo. Sob a maré de desenvolver vigorosamente as atividades culturais do campus em nossa escola, o entusiasmo dos alunos melhorou muito, mas o aumento na quantidade de atividades fez com que os alunos que organizam as atividades se sentissem pressionados enquanto sobrecarregavam seus estudos. Este artigo expõe a função, o design e a realização desse tipo de sistema de gerenciamento de informações por meio da prática real de desenvolvimento do sistema de gerenciamento de informações de registro de atividades no campus. Este artigo apresenta o projeto do sistema de gerenciamento de informações de registro de atividades do campus e o processo de realização das funções do sistema. Este sistema pode ser aplicado à gestão da informação das atividades de registo na nossa escola. É composto por vários módulos funcionais, como publicação de atividades, verificação de atividades, registo de atividades, verificação e exportação do estado de registo de atividades, etc., e realiza a rede informática gestão de tais informações.

Ao mesmo tempo, o sistema de gerenciamento de registro de atividades do campus pode gerenciar a privacidade pessoal em grande medida, definindo níveis de administrador de maneira hierárquica e baseada em blocos. Atualmente, existem poucos projetos ou sistemas relacionados que implementam especificamente tais funções no mercado , e quase nada.Projetos semelhantes podem ser usados ​​como comparação, e a perspectiva de mercado é ampla.

1.3 Principais tarefas do sistema

Usando a ideia de programação orientada a objetos e linguagem de programação Java, projete e desenvolva o sistema de gerenciamento de informações de registro de atividades do campus. O sistema pode

(1) Insira, modifique e leia as informações de senha da conta pessoal no banco de dados (banco de dados MySQL)

(2) Insira, modifique e leia informações pessoais básicas do banco de dados (banco de dados MySQL).

(3) Insira e modifique as informações da atividade no banco de dados; seja capaz de rastrear, filtrar e exibir as informações da atividade lidas no banco de dados (número da atividade, nome da atividade, editor, etc.).

(4) Ser capaz de exibir cada atividade em detalhes e concluir as seguintes funções.

① Atividades cadastrais: Quando for constatado que as atividades cadastrais não atendem aos requisitos, como horário não coincidente, escopo fora do escopo, etc., o cadastramento não poderá ser feito. Em outros casos, o cadastramento poderá ser bem sucedido.

② O status do registro é exibido de acordo com a ordem do registro.

③ O editor pode personalizar e exportar o formulário de registro de informações pessoais dos candidatos para o evento publicado.

2 projeto de esquema de sistema  

2.1 Análise de Demanda

Existem muitas sociedades, associações, clubes, etc. nesta escola. A escola atinge o objetivo de desenvolvimento integral dos alunos por meio de gestão relevante e qualificação de grupos de alunos, e várias atividades realizadas por várias associações também melhoram as habilidades de organização, liderança e comunicação dos alunos. No entanto, com o crescimento da equipe da comunidade, mais e mais atividades estão sendo realizadas e muitos problemas surgiram na vida cotidiana. Os alunos precisam preencher suas informações pessoais de forma mecânica e tediosa repetidamente para preencher o formulário de inscrição, e o os organizadores também precisam escrever um por um.Informações estatísticas de registro e, devido a diferentes meios de comunicação, haverá fenômenos injustos, como omissão e relatórios incorretos.Metodos eficazes são urgentemente necessários para resolver esses problemas.

Objetivo geral do projeto: os usuários podem usar o sistema de gerenciamento de registro de eventos do campus para se registrar em eventos escolares, como publicar eventos, registrar eventos, gerar e exportar formulários de registro e assim por diante. Isso facilita muito a operação de registro de eventos do usuário, não apenas economiza tempo, mas também melhora a precisão, o que pode atingir o dobro do resultado com metade do esforço.

Estratégia geral de design: O sistema de gerenciamento de registro de atividades do campus adota uma estrutura de módulo hierárquica de cima para baixo. Para módulos de alto nível, use uma estratégia de design centrada na transação para decompor gradualmente um módulo grande em módulos menores e relativamente simples. Para módulos de baixo nível, uma estratégia de design centrada na transformação é adotada. A fim de melhorar a coesão de cada módulo e reduzir o acoplamento entre os módulos, cada módulo é concebido como um módulo com uma única função (ou seja, coesão funcional), de modo que a conexão entre os módulos seja totalmente controlada e chamada pelo módulo principal . implementação (ou seja, não acoplado diretamente).

O sistema de gerenciamento de registro de atividade do campus é necessário para ser capaz de gerenciar todas as informações pessoais e informações cadastrais de maneira unificada, consultar e navegar pelos assuntos cadastrais de acordo com as condições (faculdades, cursos, turmas), gerar e exportar tabelas estatísticas de status de registro e consultar , navegar e modificar Os resultados são agregados no banco de dados.

As principais funções específicas são as seguintes:

(1) Registrar conta

(2) Entrar

(3) Modificar senha

(4) Modificar informações pessoais

(5) Os administradores têm autoridade para publicar atividades em todos os níveis

(6) Visualize e inscreva-se nas atividades

(7) O editor do evento pode exportar a tabela de detalhes do nível de informações do candidato

2.2 Fluxograma do sistema

Entrando no programa primeiro entra no módulo de login, que pode realizar o registro e login do usuário. Após o login bem-sucedido, entre na interface do menu principal.Existem pequenas diferenças entre usuários comuns e usuários administradores, mas os métodos de uso geral são os mesmos. As principais funções incluem publicar atividades, visualizar atividades e registrar atividades, etc.

Figura 2.1 Fluxograma principal 

2.3 Análise da estrutura funcional

(1) Registrar conta

Depois de entrar no painel de login, clique no botão de registro para entrar no painel de registro. Você pode preencher o número da conta de registro (número de aluno) e nome e selecionar sua faculdade, especialização e classe na árvore à direita. Neste momento, clique em Registrar agora, se o número da conta no banco de dados não tiver sido registrado ou ainda houver itens vazios nas cinco informações básicas, uma caixa de erro será exibida para solicitar que o usuário verifique a entrada. Até que a entrada atenda às condições acima, os dados serão gravados no banco de dados após o envio ser bem-sucedido e a interface de login será retornada.

Figura 2.2 Fluxograma de registro de conta

(2) Entrar

Digite a senha da conta no painel de login, você pode inseri-la manualmente ou rapidamente de acordo com a senha da conta que você lembra e clique em Login. Em comparação com o banco de dados, se a senha da conta estiver correta, retorne ao nível do usuário e, se você clicar em Lembrar senha, a conta de login será adicionada ao arquivo de configuração de senha da conta e, em seguida, entrará na interface principal. Por outro lado, se a senha da conta for inserida incorretamente, as etapas acima não serão executadas e uma janela pop-up solicitará que o usuário digite novamente a senha da conta.

Figura 2.3 Fluxograma de informações de login

(3) Modificar senha

Clique em Alterar senha e a janela Alterar senha será exibida. Digite a senha original e a nova senha, clique para modificar a senha, execute algumas verificações de racionalidade e grave-a no banco de dados após a verificação ser razoável.

Figura 2.4 Fluxograma de alteração de senha

(4) Modificar informações pessoais

Clique no botão modificar, defina o botão salvar como opcional, defina o botão modificar como não selecionável, defina a parte de informações modificáveis ​​como modo de modificação, modifique as informações pessoais, clique em salvar e envie o aplicativo para o banco de dados e defina o botão salvar como não selecionável após o sucesso, defina o botão de modificação como opcional e defina o modo de peça modificada como modo não modificável.

Figura 2.5 Fluxograma de modificação de informações pessoais

(5) Os administradores têm autoridade para publicar atividades em todos os níveis

Se você for um administrador, poderá publicar atividades em todos os níveis, e o escopo de liberação específico está relacionado ao seu próprio nível de usuário. Clique no botão Publicar evento para preencher e selecionar os atributos relevantes do evento. Se não houver itens em branco, você pode optar por publicar o evento imediatamente, e o sistema gerará automaticamente o horário de lançamento, número do evento, etc. Depois de enviar com sucesso o aplicativo para o banco de dados, feche a janela e retorne ao menu principal.

Figura 2.6  Fluxograma da atividade de publicação

(6) Visualize e inscreva-se nas atividades

Após logar com sucesso e entrar no painel, ele chamará automaticamente uma função para atualizar a lista de atividades (também pode ser atualizada manualmente posteriormente), e listar todas as atividades que podem ser cadastradas no âmbito do próprio. Você pode clicar no botão atividades dentro do tempo de registro para ver detalhes e ordenar por tempo de registro Preencha o breve formulário de status de registro e registre-se.Se você já se registrou, ele mostrará que o registro falhou.

Figura 2.7  Fluxograma de registro de atividades 

(7) O editor do evento pode exportar a tabela de detalhes do nível de informações do candidato

O editor do evento também pode exportar o formulário de inscrição de acordo com a ordem de inscrição. Você pode selecionar as informações necessárias, clicar em Exportar e uma janela pop-up aparecerá. Selecione as informações do candidato e a ordem das informações que o candidato precisa remover automaticamente os mesmos itens e itens vazios antes de exportar. Um arquivo Excel, formulário de registro gerado automaticamente.

Figura 2.8  Registro de exportação de atividades

3 Ambiente de desenvolvimento de software do sistema  

3 .1 Eclipse 

O Eclipse é um conhecido ambiente de desenvolvimento integrado (IDE) gratuito de plataforma cruzada. Inicialmente, era usado principalmente para o desenvolvimento da linguagem Java, mas agora algumas pessoas usam plug-ins para torná-lo uma ferramenta de desenvolvimento para outras linguagens de computador, como C++ e Python. O próprio Eclipse é apenas uma plataforma de estrutura, mas o suporte de muitos plug-ins faz com que o Eclipse tenha a flexibilidade que outros softwares IDE com funções relativamente fixas dificilmente podem ter. Muitos desenvolvedores de software usam o Eclipse como estrutura para desenvolver seu próprio IDE.

Figura 3.1 Eclipse IDE 2018-12

3 .2 Navicat Premium

O Navicat Premium é um conjunto de ferramentas de desenvolvimento de banco de dados que podem se conectar a bancos de dados MySQL, MariaDB, MongoDB, SQL Server, Oracle, PostgreSQL e SQLite simultaneamente a partir de um único aplicativo. É compatível com bancos de dados em nuvem, como Amazon RDS, Amazon Aurora, Amazon Redshift, Microsoft Azure, Oracle Cloud, MongoDB Atlas, Alibaba Cloud, Tencent Cloud e Huawei Cloud. Os bancos de dados podem ser criados, gerenciados e mantidos de forma rápida e fácil.

Figura 3.2 Navicat Premium 12.0.18

3 .3 MySQL

MySQL é um sistema de gerenciamento de banco de dados relacional , desenvolvido pela empresa sueca MySQL AB  , que é  um produto da Oracle  . O MySQL é um dos sistemas de gerenciamento de banco de dados relacional mais populares.Em termos  de aplicativos WEB  , o MySQL é um dos melhores   softwares RDBMS (Relational Database Management System, sistema de gerenciamento de banco de dados relacional).

MySQL é um sistema de gerenciamento de banco de dados relacional.Bancos de dados relacionais armazenam dados em diferentes tabelas em vez de colocar todos os dados em um grande warehouse, o que aumenta a velocidade e melhora a flexibilidade.

A linguagem SQL usada pelo MySQL é a linguagem padronizada mais comumente usada para acessar bancos de dados . O software MySQL adota uma política de autorização dupla, que é dividida em edição comunitária e edição comercial . Devido ao seu pequeno tamanho, velocidade rápida, baixo custo geral de propriedade, especialmente o recurso de código aberto , o MySQL é geralmente escolhido como o site para o desenvolvimento de sites de pequeno, médio e grande porte banco de dados .

As principais vantagens do MYSQL são: (1) velocidade de execução rápida; (2) boa portabilidade e pode funcionar em várias plataformas de sistema diferentes. (3) Forneça interfaces ricas, como C++, Java, Php, etc.; (4) Linguagem de consulta de suporte, MYSQL pode usar a sintaxe SQL padrão e suportar aplicativos ODBC (Open Database Connectivity); (5) Controle de grade e os dados warehouse também é muito poderoso; (6) Boa segurança e conectividade: sistema de autoridade e senha muito flexível e seguro, permitindo a autenticação do host. Ao se conectar ao servidor, todas as senhas são criptografadas para garantir a segurança da senha. E como o MySQL está em rede, ele pode ser acessado em qualquer lugar na Internet para melhorar a eficiência do compartilhamento de dados.

Figura 3.3 MySQL

4 Projeto de banco de dados  

4.1 Estrutura de dados principal

(1) Tabela de contas (tb_account)

Tabela 4.1 Tabela de contas

nome

tipo

comprimento

Padrões

chave

observação

admin_name

varchar

20

nulo

chave primária

conta

admin_pwd

varchar

50

000

senha

admin_level

smallint

6

0

nível de usuário

(2) Tabela de informações do personagem (tb_person)

Tabela 4.2 Tabela de informações do personagem

nome

tipo

comprimento

Padrões

chave

observação

admin_name

varchar

20

nulo

chave primária

conta

nome real do administrador

varchar

20

nulo

Nome

admin_academy

varchar

20

nulo

faculdade

admin_major

varchar

20

nulo

principal

admin_class

varchar

20

nulo

aula

admin_TEL

varchar

20

nulo

Telefone

admin_QQ

varchar

20

nulo

Qq

admin_WeChat

varchar

20

nulo

WeChat

admin_IDnum

varchar

20

nulo

número de identidade

admin_policy

varchar

20

nulo

estatuto Político

admin_address

varchar

20

nulo

endereço

admin_hometown

varchar

20

nulo

lugar nativo

admin_dormitório

varchar

20

nulo

número do quarto

outro1

varchar

20

nulo

outro 1

outro2

varchar

20

nulo

outros 2

(3) Tabela de atividades (tb_activity)

Tabela 4.3 Tabela de atividades

nome

tipo

comprimento

Padrões

chave

observação

núm_atividade

varchar

20

nulo

chave primária

Número da atividade

activity_name

varchar

20

nulo

nome da atividade

intervalo_atividade

varchar

20

nulo

Faixa de lançamento

admin_name

varchar

20

nulo

Conta do editor

activity_begintime

varchar

20

nulo

Hora de início do registro

Activity_endtime

varchar

20

nulo

Fim do tempo

content_atividade

varchar

200

nulo

Detalhes do evento

(4) Ficha de inscrição da atividade (tb_enroll)

Tabela 4.4 Formulário de Cadastro de Atividade

nome

tipo

comprimento

Padrões

chave

observação

núm_atividade

varchar

20

nulo

chave primária

Número da atividade

admin_name

varchar

20

nulo

conta

5 Projeto e implementação da função do sistema  

5.1 Função de login _ 

5.1.1 Interface de login

Quando os usuários fazem login no sistema, eles precisam inserir o número da conta e a senha por meio dessa interface e, em seguida, clicar no botão "Login" para fazer o login. O design da interface de registro é mostrado na Figura 5.1

Figura 5.1 Design da interface de login 

5.1.2 Arquivos e classes envolvidos neste módulo

 Através de uma análise detalhada, a organização dos arquivos e classes envolvidos neste módulo no projeto é apresentada na Figura 5.2.

 Figura 5.2 Organização dos  arquivos do módulo

(1) Classe de entidade

Essa classe é usada principalmente para encapsular as informações do usuário: número da conta, senha, nível do usuário e outras informações.O diagrama de classes é mostrado na Figura 5.3.

Conta

-admin_name: String

-admin_pwd:String

-admin_level:int

Fornece métodos getter e setter para cada variável de membro, bem como um método de construção de parâmetro completo e um método de construção com três parâmetros (admin_name, admin_pwd, admin_level) e reescreve o método toString

5.3 Account类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 账户实体类

*/

public class Account {

// 账号、密码

private String admin_name;

private String admin_pwd;

// 等级 0:普通用户 1-4 班系院校四级管理员

private int admin_level;

public Account() {}

public Account(String admin_name, String admin_pwd, int admin_level) {

super();

this.admin_name = admin_name;

this.admin_pwd = admin_pwd;

this.admin_level = admin_level;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getAdmin_pwd() {

return admin_pwd;

}

public void setAdmin_pwd(String admin_pwd) {

this.admin_pwd = admin_pwd;

}

public int getAdmin_level() {

return admin_level;

}

public void setAdmin_level(int admin_level) {

this.admin_level = admin_level;

}

@Override

public String toString() {

return "Account [admin_name=" + admin_name + ", admin_pwd=" + admin_pwd + ", admin_level=" + admin_level + "]";

}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的AccountDao,主要用来完成对表tb_account的增删改查操作。登录主要用到里面的查询方法。核心代码如下:

/**

 *  关于登录

 *  @param name 账号

 *  @param pwd 密码

 *  @return 返回账户信息,不正确返回null

 */

public Account login(String name, String pwd) {

Account acc = null;

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 创建语句执行器

Statement stat = conn.createStatement();

// 执行并返回结果

String sql = "select * from tb_account where admin_name='" + name + "' and admin_pwd='" + pwd + "'";

ResultSet rs = stat.executeQuery(sql);

// 迭代

if(rs.next()) {

String admin_name = rs.getString("admin_name");

String admin_pwd = rs.getString("admin_pwd");

int admin_level = rs.getInt("admin_level");

// 组装成对象

acc = new Account(admin_name, admin_pwd, admin_level);

}

// 关闭

rs.close();

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return acc;

}

(3)界面层

定义LoginFrame用于实现登陆界面,主要有登录按钮、注册按钮等。主要实现代码:new LoginFrame().setVisible(true);

图5.4 界面组件图

实现代码:

package com.wd.registration.view;

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import javax.swing.DefaultComboBoxModel;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JRadioButton;

import javax.swing.JTextField;

import javax.swing.border.EmptyBorder;

import javax.swing.event.DocumentEvent;

import javax.swing.event.DocumentListener;

import com.wd.registration.dao.AccountDao;

import com.wd.registration.entity.Account;

import com.wd.registration.utils.ConfigUtils;

public class LoginFrame extends JFrame implements ActionListener { // 实现监听接口

private JPanel contentPane;

private static JPasswordField txtPwd;

private JTextField txtAdminName;

private JButton btnLogin;

private JButton btnRegister;

private JButton btnNewButton_1;

private JRadioButton rdbtnNewRadioButton;

private static HashMap<String,String> cutils = ConfigUtils.getUserMap();

/**

 * Create the frame.

 */

public LoginFrame() {

setTitle("\u6821\u56ED\u6D3B\u52A8\u62A5\u540D\u7CFB\u7EDFV2.0");

setBounds(100, 100, 600, 610);

// 不允许改变大小

setResizable(false);

// 默认居中

setLocationRelativeTo(null);

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel();

lblNewLabel.setIcon(new ImageIcon(LoginFrame.class.getResource("/image/header.jpg")));

lblNewLabel.setBounds(42, 13, 500, 315);

contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("\u8D26\u53F7");

lblNewLabel_1.setIcon(new ImageIcon(LoginFrame.class.getResource("/image/user.png")));

lblNewLabel_1.setFont(new Font("华文仿宋", Font.BOLD, 24));

lblNewLabel_1.setBounds(52, 341, 72, 34);

contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("\u5BC6\u7801");

lblNewLabel_2.setIcon(new ImageIcon(LoginFrame.class.getResource("/image/pwd.png")));

lblNewLabel_2.setFont(new Font("华文仿宋", Font.BOLD, 24));

lblNewLabel_2.setBounds(50, 388, 72, 34);

contentPane.add(lblNewLabel_2);

List<String> UID = new ArrayList<String>();

        for(String key : cutils.keySet()) {

         UID.add(key);

}

txtAdminName = new JTextField();

setupAutoComplete(txtAdminName, UID);

txtAdminName.setBounds(138, 341, 404, 34);

contentPane.add(txtAdminName);

txtAdminName.setColumns(10);

txtPwd = new JPasswordField();

txtPwd.setBounds(138, 391, 304, 34);

contentPane.add(txtPwd);

btnLogin = new JButton("\u767B\u5F55");

btnLogin.setIcon(new ImageIcon(LoginFrame.class.getResource("/image/log_in.png")));

// 给登录按钮添加监听器

btnLogin.addActionListener(this);

btnLogin.setFont(new Font("楷体", Font.BOLD, 18));

btnLogin.setBounds(110, 450, 142, 40);

contentPane.add(btnLogin);

btnRegister = new JButton("\u6CE8\u518C");

btnRegister.setIcon(new ImageIcon(LoginFrame.class.getResource("/image/log_in.png")));

btnRegister.addActionListener(this);

btnRegister.setFont(new Font("楷体", Font.BOLD, 18));

btnRegister.setBounds(340, 450, 142, 40);

contentPane.add(btnRegister);

rdbtnNewRadioButton = new JRadioButton("\u8BB0\u4F4F\u5BC6\u7801");

rdbtnNewRadioButton.setFont(new Font("仿宋", Font.BOLD, 12));

rdbtnNewRadioButton.setBounds(452, 394, 90, 30);

contentPane.add(rdbtnNewRadioButton);

btnNewButton_1 = new JButton("\u5173\u4E8E");

btnNewButton_1.addActionListener(this);

btnNewButton_1.setBounds(470, 523, 72, 27);

contentPane.add(btnNewButton_1);

// 添加键盘监听

this.getRootPane().setDefaultButton(btnLogin);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "退出系统?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

        // 退出系统

         LoginFrame.this.dispose();

        }

    }

});

}

public void actionPerformed(ActionEvent e) {

// 如果按下的是登录

if(e.getSource()==btnLogin) {

login();

}

// 如果按下的是注册

else if (e.getSource()==btnRegister) {

register();

}

// 如果按下的是关于

else if (e.getSource()==btnNewButton_1) {

JOptionPane.showMessageDialog(this, "大数据1901出品");

}

else {

JOptionPane.showMessageDialog(this, "未知的操作", "错误", JOptionPane.ERROR_MESSAGE);

}

}

private void register() {

try {

new RegisterFrame().setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

private void login() {

// 取得账号和密码

String admin_name = txtAdminName.getText();

String admin_pwd = txtPwd.getText();

// 调用DAO层login比对

AccountDao dao = new AccountDao();

Account account = dao.login(admin_name, admin_pwd);

// 根据对象是否为空来做下一步操作

if(account==null) {

JOptionPane.showMessageDialog(this, "账号或密码错误", "错误", JOptionPane.ERROR_MESSAGE);

}

else {

//如果有记住密码

if(rdbtnNewRadioButton.isSelected()) {

// 将新加账号密码加入HashMap

cutils.put(account.getAdmin_name(), account.getAdmin_pwd());

ConfigUtils.saveMapToFile(cutils);

}

this.dispose();

try {

// 生成主窗口,将用户名和用户等级传入

MainFrame frame = new MainFrame(account.getAdmin_name(), account.getAdmin_level());

frame.setVisible(true);

} catch (Exception e1) {

e1.printStackTrace();

}

}

}

private static boolean isAdjusting(JComboBox cbInput) {

        if (cbInput.getClientProperty("is_adjusting") instanceof Boolean) { //返回具有指定键的属性的值。只有添加的属性将返回不空(non-null)的值

         return (Boolean) cbInput.getClientProperty("is_adjusting");

        }

        return false;

    }

private static void setAdjusting(JComboBox cbInput, boolean adjusting) {

        cbInput.putClientProperty("is_adjusting", adjusting); //对由另一个模块创建的组件进行注释

        //向此组件添加任意键/值"客户端属性"。

    }

public static void setupAutoComplete(JTextField txtInput, List<String> items) {

        DefaultComboBoxModel model = new DefaultComboBoxModel();

        JComboBox cbInput = new JComboBox(model) { //model与宽度设置(长度与文本框相当)

            @ Override

         public Dimension getPreferredSize() {

                return new Dimension(super.getPreferredSize().width, 0);

            }

        };

        

        setAdjusting(cbInput, false); //先默认全部都没有被adjust

        for (String item : items) { //把列表加到model中

            model.addElement(item);

        }

        

        cbInput.setSelectedItem(null); //将组合框显示区域中的选定项设置为参数中的对象,一开始没有

        

        //Combobox的监听

        cbInput.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                if (!isAdjusting(cbInput)) { //调整完了 已经补全的话进入

                    if (cbInput.getSelectedItem() != null) {

                     txtPwd.setText(cutils.get(cbInput.getSelectedItem().toString()));

                        txtInput.setText(cbInput.getSelectedItem().toString()); //把他显示在txtInput上

                    }

                }

            }

        });

        //监听JtextArea增添修改

        txtInput.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {

                updateList();

            }

            public void removeUpdate(DocumentEvent e) {

                updateList();

            }

            public void changedUpdate(DocumentEvent e) {

                updateList();

            }

            private void updateList() {

                setAdjusting(cbInput, true);

                model.removeAllElements();

                String input = txtInput.getText();

                if (!input.isEmpty()) {

                    for (String item : items) {

                        if (item.toLowerCase().startsWith(input.toLowerCase())) {

                            model.addElement(item);

                        }

                    }

                }

                cbInput.setPopupVisible(model.getSize() > 0);

                setAdjusting(cbInput, false);

            }

        });

        txtInput.setLayout(new BorderLayout());

        txtInput.add(cbInput, BorderLayout.SOUTH);

    }

}

5.2 注册功能

5.2.1 注册界面

用户在进行注册时,需要通过该界面输入学号/工号、姓名、学院、专业、班级,然后点击“立即注册”按钮进行注册,注册界面效果如图5.5所示。

 图5.5 注册界面效果

5.2.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.6所示。

图5.6 模块文件的组织

(1)实体类

该类主要用于封装用户的信息:帐号、密码和用户等级等信息,类图如图5.7所示。

Account

-admin_name:String

-admin_pwd:String

-admin_level:int

提供了每个成员变量的getter和setter方法,还有全参构造方法、三个参数(admin_name,admin_pwd,admin_level)的构造方法,并重写了toString方法

5.7 Account类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 账户实体类

*/

public class Account {

// 账号、密码

private String admin_name;

private String admin_pwd;

// 等级 0:普通用户 1-4 班系院校四级管理员

private int admin_level;

public Account() {}

public Account(String admin_name, String admin_pwd, int admin_level) {

super();

this.admin_name = admin_name;

this.admin_pwd = admin_pwd;

this.admin_level = admin_level;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getAdmin_pwd() {

return admin_pwd;

}

public void setAdmin_pwd(String admin_pwd) {

this.admin_pwd = admin_pwd;

}

public int getAdmin_level() {

return admin_level;

}

public void setAdmin_level(int admin_level) {

this.admin_level = admin_level;

}

@Override

public String toString() {

return "Account [admin_name=" + admin_name + ", admin_pwd=" + admin_pwd + ", admin_level=" + admin_level + "]";

}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的AccountDao,主要用来完成对表tb_account的增删改查操作。登录主要用到里面的查询方法。核心代码如下:

/**

 *  插入账户信息

 *  @param name 账号

 */

public void insert(String name) {

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 编写SQL语句

String sql = "insert into tb_account(admin_name, admin_pwd, admin_level) value(?, \"000\", 0)";

// 创建预编译语句执行器

PreparedStatement stat = conn.prepareStatement(sql);

stat.setString(1, name);

// 执行

stat.executeUpdate();

// 关闭

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

(3)界面层

定义RegisterFrame用于实现注册界面,右边有一颗从滚动窗口里放的从文件里读出的一棵树,当选中叶子节点(班级)时会自动把路径上的学院、专业等填入框内,保证数据库内同一个信息的表达一致性。同时,还具有“空项提示”的功能,如果某一项信息为空,则在之下会显示一条提醒信息。

生成窗口代码为:new RegisterFrame().setVisible(true);

5.8 界面组件图

实现代码:

package com.wd.registration.view;

import java.awt.Color;

import java.awt.Font;

import java.awt.HeadlessException;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextField;

import javax.swing.JTree;

import javax.swing.SwingConstants;

import javax.swing.border.EmptyBorder;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreeSelectionModel;

import com.wd.registration.dao.AccountDao;

import com.wd.registration.dao.PersonDao;

import com.wd.registration.entity.Person;

import com.wd.registration.utils.XMLUtils;

public class RegisterFrame extends JDialog implements TreeSelectionListener, ActionListener {

private JPanel contentPane;

private JTextField textField;

private JTextField textField_1;

private JTextField textField_2;

private JTextField textField_3;

private JTree jtree;

private JTextField textField_4;

private JLabel lblNewLabel_2_0;

private JLabel lblNewLabel_2_1;

private JLabel lblNewLabel_2_2;

private JLabel lblNewLabel_2_3;

private JLabel lblNewLabel_2_4;

private Person pr;

/**

 * Create the frame.

 */

public RegisterFrame() {

setTitle("\u7528\u6237\u6CE8\u518C");

setBounds(100, 100, 590, 435);

setResizable(false);

setLocationRelativeTo(null);

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

// 创建一棵树

XMLUtils tree = new XMLUtils();

jtree = new JTree(tree.getRootTree());

jtree.addTreeSelectionListener(this);

//设置Tree的选择模式为一次只能选择一个节点

        jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

// 创建一个滚动面板用来装树

JScrollPane treeView = new JScrollPane(jtree);

treeView.setBounds(370, 13, 188, 362);

contentPane.add(treeView);

JPanel Infor_panel = new JPanel();

Infor_panel.setBounds(14, 13, 342, 310);

contentPane.add(Infor_panel);

Infor_panel.setLayout(null);

JLabel lblNewLabel = new JLabel("\u5B66\u53F7/\u5DE5\u53F7");

lblNewLabel.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/user.png")));

lblNewLabel.setFont(new Font("华文新魏", Font.PLAIN, 18));

lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel.setBounds(0, 36, 105, 18);

Infor_panel.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("\u59D3\u540D");

lblNewLabel_1.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/realname.png")));

lblNewLabel_1.setFont(new Font("华文新魏", Font.PLAIN, 18));

lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel_1.setBounds(13, 90, 91, 18);

Infor_panel.add(lblNewLabel_1);

textField = new JTextField();

textField.setBounds(112, 31, 205, 24);

Infor_panel.add(textField);

textField.setColumns(10);

textField_1 = new JTextField();

textField_1.setBounds(112, 86, 205, 24);

Infor_panel.add(textField_1);

textField_1.setColumns(10);

JLabel lblNewLabel_1_1 = new JLabel("\u5B66\u9662");

lblNewLabel_1_1.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/academy.png")));

lblNewLabel_1_1.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel_1_1.setFont(new Font("华文新魏", Font.PLAIN, 18));

lblNewLabel_1_1.setBounds(12, 144, 91, 18);

Infor_panel.add(lblNewLabel_1_1);

JLabel lblNewLabel_1_2 = new JLabel("\u4E13\u4E1A");

lblNewLabel_1_2.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/major.png")));

lblNewLabel_1_2.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel_1_2.setFont(new Font("华文新魏", Font.PLAIN, 18));

lblNewLabel_1_2.setBounds(11, 198, 91, 18);

Infor_panel.add(lblNewLabel_1_2);

JLabel lblNewLabel_1_3 = new JLabel("\u73ED\u7EA7");

lblNewLabel_1_3.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/class.png")));

lblNewLabel_1_3.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel_1_3.setFont(new Font("华文新魏", Font.PLAIN, 18));

lblNewLabel_1_3.setBounds(10, 252, 91, 18);

Infor_panel.add(lblNewLabel_1_3);

textField_2 = new JTextField();

textField_2.setEditable(false);

textField_2.setColumns(10);

textField_2.setBounds(112, 141, 205, 24);

Infor_panel.add(textField_2);

textField_3 = new JTextField();

textField_3.setEditable(false);

textField_3.setColumns(10);

textField_3.setBounds(112, 196, 205, 24);

Infor_panel.add(textField_3);

textField_4 = new JTextField();

textField_4.setEditable(false);

textField_4.setColumns(10);

textField_4.setBounds(112, 251, 205, 24);

Infor_panel.add(textField_4);

lblNewLabel_2_0 = new JLabel();

lblNewLabel_2_0.setForeground(Color.RED);

lblNewLabel_2_0.setBounds(112, 55, 125, 18);

Infor_panel.add(lblNewLabel_2_0);

lblNewLabel_2_1 = new JLabel();

lblNewLabel_2_1.setForeground(Color.RED);

lblNewLabel_2_1.setBounds(112, 110, 125, 18);

Infor_panel.add(lblNewLabel_2_1);

lblNewLabel_2_2 = new JLabel();

lblNewLabel_2_2.setForeground(Color.RED);

lblNewLabel_2_2.setBounds(112, 165, 125, 18);

Infor_panel.add(lblNewLabel_2_2);

lblNewLabel_2_3 = new JLabel();

lblNewLabel_2_3.setForeground(Color.RED);

lblNewLabel_2_3.setBounds(112, 220, 125, 18);

Infor_panel.add(lblNewLabel_2_3);

lblNewLabel_2_4 = new JLabel();

lblNewLabel_2_4.setForeground(Color.RED);

lblNewLabel_2_4.setBounds(112, 275, 125, 18);

Infor_panel.add(lblNewLabel_2_4);

JButton btnRegisterNow = new JButton("\u7ACB\u5373\u6CE8\u518C");

btnRegisterNow.addActionListener(this);

btnRegisterNow.setIcon(new ImageIcon(RegisterFrame.class.getResource("/image/log_in.png")));

btnRegisterNow.setBounds(14, 336, 342, 39);

contentPane.add(btnRegisterNow);

// 模态框

this.setModal(true);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "退出注册界面?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

        // 退出

         RegisterFrame.this.dispose();

        }

    }

});

}

// 在JTree上点选任何一个节点,都会触发TreeSelectionEvent事件

@Override

public void valueChanged(TreeSelectionEvent e) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode)jtree.getLastSelectedPathComponent();

// 防止啥也不选

if(node == null) {

return;

}

// 如果是树叶结点,把信息显示出来

if(node.isLeaf()){

textField_2.setText(node.getPath()[1].toString());

textField_3.setText(node.getPath()[2].toString());

textField_4.setText(node.getPath()[3].toString());

}

}

@Override

public void actionPerformed(ActionEvent e) {

// 实例化Person实体类

pr = new Person();

pr.setAdmin_name(textField.getText());

pr.setAdmin_realname(textField_1.getText());

pr.setAdmin_academy(textField_2.getText());

pr.setAdmin_major(textField_3.getText());

pr.setAdmin_class(textField_4.getText());

// 可执行标志true可以写入false未填完全

boolean notEmpty = true;

boolean[] temp = new PersonDao().canRegister(pr);

// 遍历数组,显示标签

for(int i = 0; i < temp.length; i++) {

if(temp[i] == false) {

notEmpty = false;

showLbls(i, "此项不可为空");

} else {

showLbls(i, "");

}

}

// 全部填满,可以继续

if (notEmpty) {

toDB(pr);

}

}

private void showLbls(int i, String content) {

switch(i) { // 显示label提示输入

case 0: lblNewLabel_2_0.setText(content); break;

case 1: lblNewLabel_2_1.setText(content); break;

case 2: lblNewLabel_2_2.setText(content); break;

case 3: lblNewLabel_2_3.setText(content); break;

case 4: lblNewLabel_2_4.setText(content); break;

}

}

// 写入数据库

private void toDB(Person pr) throws HeadlessException {

// 检测是否添加过数据库

if(new PersonDao().getInformation(pr.getAdmin_name()) != null) {

JOptionPane.showMessageDialog(this, "此账号已经注册过了,如有疑问请联系开发人员", "错误", JOptionPane.ERROR_MESSAGE);

}

else {

// 插入Person数据库

PersonDao newPrDao = new PersonDao();

newPrDao.insert(pr);

// 插入Account数据库

AccountDao newAccDao = new AccountDao();

newAccDao.insert(pr.getAdmin_name());

// 显示注册成功

JOptionPane.showMessageDialog(this, "账户注册成功,账号为学(工)号,初始密码为000,欢迎使用本系统");

this.dispose();

}

}

}

5.3 主界面功能

5.3.1 注册界面

用户在登录成功时,进入系统主页面,主界面包括个人信息修改、活动发布、活动列表,主界面效果如图5.9所示。

图5.9 界面效果

5.3.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.10所示。

图5.10 模块文件的组织

(1)界面层

定义MainFrame用于实现生成主界面与引导,包含个人信息面板部分(内含个人信息修改以及密码修改功能)、发布活动功能(用户等级大于0才能选择)和活动展实板块(右),也是程序的核心界面,是完成系统几乎所有功能的上级窗口。生成主窗口,需要将用户名和用户等级传入。

生成窗口代码为:MainFrame frame = new MainFrame(account.getAdmin_name(), account.getAdmin_level());frame.setVisible(true);

 图5.11 主界面组件

核心代码:

package com.wd.registration.view;

import java.awt.Color;

import java.awt.Font;

import java.awt.HeadlessException;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.Collections;

import java.util.Date;

import java.util.List;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextField;

import javax.swing.ListSelectionModel;

import javax.swing.border.EmptyBorder;

import javax.swing.border.LineBorder;

import javax.swing.border.TitledBorder;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

import javax.swing.table.DefaultTableModel;

import com.wd.registration.dao.ActivityDao;

import com.wd.registration.dao.PersonDao;

import com.wd.registration.dao.PostDao;

import com.wd.registration.entity.Activity;

import com.wd.registration.entity.Person;

/**

 * 显示主界面

*/

public class MainFrame extends JFrame implements ActionListener {

private JPanel contentPane;

private JTextField textField;

private JTextField textField_1;

private JTextField textField_2;

private JTextField textField_3;

private JTextField textField_4;

private JTextField textField_5;

private JTextField textField_6;

private JTextField textField_7;

private JTextField textField_8;

private JTextField textField_9;

private JTextField textField_10;

private JTextField textField_11;

private JTextField textField_12;

private JTextField textField_13;

private JTextField textField_14;

private JButton btnNewButton_2;

private JTable table;

private JButton btnStartChange;

private JButton btnRefresh;

private JLabel lblNewLabel_15;

private JLabel lblNewLabel_16;

private JLabel lblNewLabel_17;

private JLabel lblNewLabel_18;

private JButton btnStopChange;

private PersonDao pdao;

private Person pr;

private JButton btnpubButton;

private JLabel lblNewLabel_19;

private JLabel lblNewLabel_20;

private JLabel lblNewLabel_21;

private JPanel panel_refreshtb;

private DefaultTableModel dtm; // 表单

private int level;

/**

 * Create the frame.

 */

public MainFrame(String admin_name, int admin_level) {

// 获取个人信息

pdao = new PersonDao();

pr = pdao.getInformation(admin_name);

level = admin_level;

// 设置窗口

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle("\u6821\u56ED\u6D3B\u52A8\u62A5\u540D\u7CFB\u7EDF\u5BA2\u6237\u7AEFV2.0");

setBounds(300, 300, 1350, 900);

// 不允许改变大小

setResizable(false);

// 默认居中

setLocationRelativeTo(null);

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JPanel panel_account = new JPanel();

panel_account.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 2, true), "\u4E2A\u4EBA\u4FE1\u606F\u90E8\u5206", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));

panel_account.setBounds(40, 30, 350, 545);

contentPane.add(panel_account);

panel_account.setLayout(null);

JLabel lblNewLabel = new JLabel("\u5B66\u53F7");

lblNewLabel.setIcon(new ImageIcon(MainFrame.class.getResource("/image/user.png")));

lblNewLabel.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel.setBounds(30, 50, 57, 18);

panel_account.add(lblNewLabel);

textField = new JTextField();

textField.setText(pr.getAdmin_name());

textField.setBounds(94, 45, 152, 24);

textField.setEditable(false);

panel_account.add(textField);

textField.setColumns(10);

btnNewButton_2 = new JButton("\u4FEE\u6539\u5BC6\u7801");

btnNewButton_2.setFont(new Font("宋体", Font.BOLD, 12));

btnNewButton_2.setBounds(258, 45, 78, 27);

btnNewButton_2.addActionListener(this);

panel_account.add(btnNewButton_2);

JLabel lblNewLabel_1 = new JLabel("\u59D3\u540D");

lblNewLabel_1.setIcon(new ImageIcon(MainFrame.class.getResource("/image/realname.png")));

lblNewLabel_1.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_1.setBounds(30, 81, 57, 18);

panel_account.add(lblNewLabel_1);

textField_1 = new JTextField();

textField_1.setText(pr.getAdmin_realname());

textField_1.setBounds(94, 76, 152, 24);

textField_1.setEditable(false);

panel_account.add(textField_1);

textField_1.setColumns(10);

JLabel lblNewLabel_2 = new JLabel("\u5B66\u9662");

lblNewLabel_2.setIcon(new ImageIcon(MainFrame.class.getResource("/image/academy.png")));

lblNewLabel_2.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_2.setBounds(25, 110, 57, 18);

panel_account.add(lblNewLabel_2);

textField_2 = new JTextField();

textField_2.setText(pr.getAdmin_academy());

textField_2.setBounds(94, 105, 152, 24);

textField_2.setEditable(false);

panel_account.add(textField_2);

textField_2.setColumns(10);

JLabel lblNewLabel_3 = new JLabel("\u4E13\u4E1A");

lblNewLabel_3.setIcon(new ImageIcon(MainFrame.class.getResource("/image/major.png")));

lblNewLabel_3.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_3.setBounds(23, 139, 61, 18);

panel_account.add(lblNewLabel_3);

textField_3 = new JTextField();

textField_3.setText(pr.getAdmin_major());

textField_3.setBounds(94, 134, 152, 24);

textField_3.setEditable(false);

panel_account.add(textField_3);

textField_3.setColumns(10);

JLabel lblNewLabel_4 = new JLabel("\u73ED\u7EA7");

lblNewLabel_4.setIcon(new ImageIcon(MainFrame.class.getResource("/image/class.png")));

lblNewLabel_4.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_4.setBounds(19, 168, 61, 18);

panel_account.add(lblNewLabel_4);

textField_4 = new JTextField();

textField_4.setText(pr.getAdmin_class());

textField_4.setBounds(94, 163, 152, 24);

textField_4.setEditable(false);

panel_account.add(textField_4);

textField_4.setColumns(10);

JLabel lblNewLabel_5 = new JLabel("\u7535\u8BDD");

lblNewLabel_5.setIcon(new ImageIcon(MainFrame.class.getResource("/image/telephone.png")));

lblNewLabel_5.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_5.setBounds(30, 197, 57, 18);

panel_account.add(lblNewLabel_5);

textField_5 = new JTextField();

textField_5.setText(pr.getAdmin_TEL());

textField_5.setBounds(94, 192, 152, 24);

textField_5.setEditable(false);

panel_account.add(textField_5);

textField_5.setColumns(10);

JLabel lblNewLabel_6 = new JLabel("QQ");

lblNewLabel_6.setIcon(new ImageIcon(MainFrame.class.getResource("/image/QQ.png")));

lblNewLabel_6.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_6.setBounds(30, 226, 53, 18);

panel_account.add(lblNewLabel_6);

textField_6 = new JTextField();

textField_6.setText(pr.getAdmin_QQ());

textField_6.setBounds(94, 221, 152, 24);

textField_6.setEditable(false);

panel_account.add(textField_6);

textField_6.setColumns(10);

JLabel lblNewLabel_7 = new JLabel("\u5FAE\u4FE1");

lblNewLabel_7.setIcon(new ImageIcon(MainFrame.class.getResource("/image/Wechat.png")));

lblNewLabel_7.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_7.setBounds(26, 255, 57, 18);

panel_account.add(lblNewLabel_7);

textField_7 = new JTextField();

textField_7.setText(pr.getAdmin_WeChat());

textField_7.setBounds(94, 250, 152, 24);

textField_7.setEditable(false);

panel_account.add(textField_7);

textField_7.setColumns(10);

JLabel lblNewLabel_8 = new JLabel("\u8EAB\u4EFD\u8BC1");

lblNewLabel_8.setIcon(new ImageIcon(MainFrame.class.getResource("/image/id_card.png")));

lblNewLabel_8.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_8.setBounds(15, 284, 77, 18);

panel_account.add(lblNewLabel_8);

textField_8 = new JTextField();

textField_8.setText(pr.getAdmin_IDnum());

textField_8.setBounds(94, 279, 152, 24);

textField_8.setEditable(false);

panel_account.add(textField_8);

textField_8.setColumns(10);

JLabel lblNewLabel_9 = new JLabel("\u653F\u6CBB\u9762\u8C8C");

lblNewLabel_9.setIcon(new ImageIcon(MainFrame.class.getResource("/image/Flag_red.png")));

lblNewLabel_9.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_9.setBounds(10, 313, 80, 18);

panel_account.add(lblNewLabel_9);

textField_9 = new JTextField();

textField_9.setText(pr.getAdmin_politice());

textField_9.setBounds(94, 308, 152, 24);

textField_9.setEditable(false);

panel_account.add(textField_9);

textField_9.setColumns(10);

JLabel lblNewLabel_10 = new JLabel("\u5BB6\u5EAD\u4F4F\u5740");

lblNewLabel_10.setIcon(new ImageIcon(MainFrame.class.getResource("/image/map.png")));

lblNewLabel_10.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_10.setBounds(8, 342, 88, 18);

panel_account.add(lblNewLabel_10);

textField_10 = new JTextField();

textField_10.setText(pr.getAdmin_address());

textField_10.setBounds(94, 337, 152, 24);

textField_10.setEditable(false);

panel_account.add(textField_10);

textField_10.setColumns(10);

JLabel lblNewLabel_11 = new JLabel("\u7C4D\u8D2F");

lblNewLabel_11.setIcon(new ImageIcon(MainFrame.class.getResource("/image/map2.png")));

lblNewLabel_11.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_11.setBounds(25, 371, 61, 18);

panel_account.add(lblNewLabel_11);

textField_11 = new JTextField();

textField_11.setText(pr.getAdmin_hometown());

textField_11.setBounds(94, 366, 152, 24);

textField_11.setEditable(false);

panel_account.add(textField_11);

textField_11.setColumns(10);

JLabel lblNewLabel_12 = new JLabel("\u5BDD\u5BA4\u53F7");

lblNewLabel_12.setIcon(new ImageIcon(MainFrame.class.getResource("/image/sleep.png")));

lblNewLabel_12.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_12.setBounds(19, 400, 70, 18);

panel_account.add(lblNewLabel_12);

textField_12 = new JTextField();

textField_12.setText(pr.getAdmin_dormitory());

textField_12.setBounds(94, 395, 152, 24);

textField_12.setEditable(false);

panel_account.add(textField_12);

textField_12.setColumns(10);

JLabel lblNewLabel_13 = new JLabel("\u5176\u4ED61");

lblNewLabel_13.setIcon(new ImageIcon(MainFrame.class.getResource("/image/Misc_Designs.png")));

lblNewLabel_13.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_13.setBounds(26, 429, 61, 18);

panel_account.add(lblNewLabel_13);

textField_13 = new JTextField();

textField_13.setText(pr.getOther1());

textField_13.setBounds(94, 424, 152, 24);

textField_13.setEditable(false);

panel_account.add(textField_13);

textField_13.setColumns(10);

JLabel lblNewLabel_14 = new JLabel("\u5176\u4ED62");

lblNewLabel_14.setIcon(new ImageIcon(MainFrame.class.getResource("/image/Misc_Designs.png")));

lblNewLabel_14.setFont(new Font("华文琥珀", Font.PLAIN, 15));

lblNewLabel_14.setBounds(26, 458, 61, 18);

panel_account.add(lblNewLabel_14);

textField_14 = new JTextField();

textField_14.setText(pr.getOther2());

textField_14.setBounds(94, 453, 152, 24);

textField_14.setEditable(false);

panel_account.add(textField_14);

textField_14.setColumns(10);

btnStartChange = new JButton("\u70B9\u51FB\u4FEE\u6539");

btnStartChange.setFont(new Font("宋体", Font.BOLD, 12));

btnStartChange.setBounds(46, 489, 105, 38);

btnStartChange.addActionListener(this);

panel_account.add(btnStartChange);

lblNewLabel_15 = new JLabel("\u4F8B\uFF1A\u6E56\u5357\u6D4F\u9633");

lblNewLabel_15.setFont(new Font("宋体", Font.BOLD, 12));

lblNewLabel_15.setBounds(252, 371, 84, 18);

panel_account.add(lblNewLabel_15);

lblNewLabel_16 = new JLabel("\u4F8B\uFF1A\u884C\u56DBA109");

lblNewLabel_16.setFont(new Font("宋体", Font.BOLD, 12));

lblNewLabel_16.setBounds(252, 400, 84, 18);

panel_account.add(lblNewLabel_16);

lblNewLabel_18 = new JLabel("<-\u4EE5\u4E0B\u53EF\u4FEE\u6539");

lblNewLabel_18.setFont(new Font("宋体", Font.BOLD, 12));

lblNewLabel_18.setBounds(252, 178, 84, 18);

panel_account.add(lblNewLabel_18);

btnStopChange = new JButton("\u4FEE\u6539\u5B8C\u6210");

btnStopChange.setEnabled(false);

btnStopChange.setFont(new Font("宋体", Font.BOLD, 12));

btnStopChange.setBounds(197, 490, 105, 37);

btnStopChange.addActionListener(this);

panel_account.add(btnStopChange);

JPanel panel_announcement = new JPanel();

panel_announcement.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 2, true), "\u6D3B\u52A8\u53D1\u5E03\u677F\u5757", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));

panel_announcement.setBounds(40, 588, 350, 252);

contentPane.add(panel_announcement);

panel_announcement.setLayout(null);

btnpubButton = new JButton("\u70B9\u51FB\u53D1\u5E03\u6D3B\u52A8");

// 如果具有管理员权限,开放btnpubButton按钮

if(admin_level == 0) {

btnpubButton.setEnabled(false);

}

btnpubButton.setIcon(new ImageIcon(MainFrame.class.getResource("/image/plus.png")));

btnpubButton.setFont(new Font("华文彩云", Font.BOLD, 30));

btnpubButton.addActionListener(this);

btnpubButton.setBounds(14, 132, 322, 107);

panel_announcement.add(btnpubButton);

lblNewLabel_19 = new JLabel("\u83B7\u53D6\u53D1\u5E03\u6D3B\u52A8\u6743\u9650\u8BF7\u8054\u7CFB\u9879\u76EE\u5F00\u53D1\u4EBA\u5458");

lblNewLabel_19.setFont(new Font("幼圆", Font.PLAIN, 18));

lblNewLabel_19.setBounds(14, 35, 322, 32);

panel_announcement.add(lblNewLabel_19);

lblNewLabel_20 = new JLabel("\u7535\u8BDD\uFF1A18867422127");

lblNewLabel_20.setFont(new Font("幼圆", Font.PLAIN, 16));

lblNewLabel_20.setBounds(14, 65, 160, 32);

panel_announcement.add(lblNewLabel_20);

lblNewLabel_21 = new JLabel("QQ\uFF1A1753899653");

lblNewLabel_21.setFont(new Font("幼圆", Font.PLAIN, 16));

lblNewLabel_21.setBounds(30, 90, 135, 32);

panel_announcement.add(lblNewLabel_21);

JScrollPane scrollPane = new JScrollPane();

scrollPane.setBounds(405, 30, 834, 810);

contentPane.add(scrollPane);

// 建立表格

String[] header = {"活动编号", "活动名称", "活动发布者", "报名开始时间", "报名截止时间"};

dtm = new DefaultTableModel(null, header) {

// 禁止编辑表格

    @Override

    public boolean isCellEditable(int row, int column) {

        return false;

    }

};

refreshtb(); // 初始化表格

table = new JTable(dtm);

scrollPane.setViewportView(table);

// 设置表格内容颜色

        table.setForeground(Color.BLACK);                   // 字体颜色

        table.setFont(new Font(null, Font.PLAIN, 13));      // 字体样式

        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色

        table.setSelectionBackground(Color.LIGHT_GRAY);     // 选中后字体背景

        table.setGridColor(Color.GRAY);                     // 网格颜色

        // 设置表头

        table.getTableHeader().setFont(new Font(null, Font.BOLD, 18));  // 设置表头名称字体样式

        table.getTableHeader().setForeground(Color.RED);                // 设置表头名称字体颜色

        table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽

        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高

        table.setRowHeight(30);

        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        ListSelectionModel rowSM = table.getSelectionModel();

        //监听选中行

        rowSM.addListSelectionListener(new ListSelectionListener() {

         public void valueChanged(ListSelectionEvent e) {

         //只处理鼠标按下

         if(e.getValueIsAdjusting() == false) {

         return;

         }

         ListSelectionModel lsm = (ListSelectionModel) e.getSource();

         // 没有选择过

         if(!lsm.isSelectionEmpty()) {

         int selectedRow = lsm.getMinSelectionIndex();

         String nowT = new PostDao().formatTime(new Date());

         toEnrollFrame(selectedRow, nowT);

         }

         }

         // 打开活动查看面板

private void toEnrollFrame(int selectedRow, String nowT) throws HeadlessException {

if((nowT.compareTo(table.getValueAt(selectedRow, 3).toString()) >= 0 && nowT.compareTo(table.getValueAt(selectedRow, 4).toString()) <= 0)) {

try {

ActivityFrame frame = new ActivityFrame(new ActivityDao().getActivity(table.getValueAt(selectedRow, 0).toString()), pr.getAdmin_name());

frame.setVisible(true);

} catch (Exception e2) {

e2.printStackTrace();

}

}

else {

JOptionPane.showMessageDialog(null, "不在可报名时间内,不可查询", "", JOptionPane.ERROR_MESSAGE);

}

}

        });

panel_refreshtb = new JPanel();

panel_refreshtb.setBounds(1253, 30, 77, 88);

contentPane.add(panel_refreshtb);

panel_refreshtb.setLayout(null);

btnRefresh = new JButton();

btnRefresh.setBounds(0, 0, 65, 65);

panel_refreshtb.add(btnRefresh);

btnRefresh.addActionListener(this);

btnRefresh.setIcon(new ImageIcon(MainFrame.class.getResource("/image/refresh.png")));

lblNewLabel_17 = new JLabel("\u5237\u65B0\u5217\u8868");

lblNewLabel_17.setBounds(10, 70, 67, 18);

panel_refreshtb.add(lblNewLabel_17);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "退出登录?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

        // 退出系统

         MainFrame.this.dispose();

         // 显示登录界面

         new LoginFrame().setVisible(true);

        }

    }

});

}

@Override

public void actionPerformed(ActionEvent e) {

// 刷新表格

if (e.getSource()==btnRefresh) {

refreshtb();

}

// 开放编辑

if (e.getSource()==btnStartChange) {

changes(true);

}

// 结束编辑,保存数据

if (e.getSource()==btnStopChange) {

changes(false);

//写入数据库

pdao.update(pr);

JOptionPane.showMessageDialog(this, "修改成功");

}

// 发布活动

if (e.getSource()==btnpubButton) {

try {

PostFrame frame = new PostFrame(level, pr);

frame.setVisible(true);

} catch (Exception e1) {

e1.printStackTrace();

}

}

// 修改密码

if (e.getSource()==btnNewButton_2) {

try {

new ChangePwdFrame(pr.getAdmin_name()).setVisible(true);

} catch (Exception e1) {

e1.printStackTrace();

}

}

}

private void refreshtb() {

// 删除原有的数据

while(true) {

try {

dtm.removeRow(0);

} catch (Exception e1) {

break;

}

}

// 输入新表数据

List<Activity> temp = new ActivityDao().getInformation(pr.getAdmin_academy(), pr.getAdmin_major(), pr.getAdmin_class());

Collections.reverse(temp);

for(Activity act : temp) {

dtm.addRow(new Object[]{act.getActivity_num(), act.getActivity_name(), new PersonDao().getInformation(act.getAdmin_name()).getAdmin_realname(), act.getActivity_begintime(), act.getActivity_endtime()});

}

}

// 修改个人信息

private void changes(boolean flag) {

btnStopChange.setEnabled(flag);

btnStartChange.setEnabled(!flag);

textField_5.setEditable(flag);

pr.setAdmin_TEL(textField_5.getText());

textField_6.setEditable(flag);

pr.setAdmin_QQ(textField_6.getText());

textField_7.setEditable(flag);

pr.setAdmin_WeChat(textField_7.getText());

textField_8.setEditable(flag);

pr.setAdmin_IDnum(textField_8.getText());

textField_9.setEditable(flag);

pr.setAdmin_politice(textField_9.getText());

textField_10.setEditable(flag);

pr.setAdmin_address(textField_10.getText());

textField_11.setEditable(flag);

pr.setAdmin_hometown(textField_11.getText());

textField_12.setEditable(flag);

pr.setAdmin_dormitory(textField_12.getText());

textField_13.setEditable(flag);

pr.setOther1(textField_13.getText());

textField_14.setEditable(flag);

pr.setOther2(textField_14.getText());

}

}

5.4 更改密码功能

5.4.1 更改密码界面

用户在需要修改密码时,点击修改密码,输入原密码、新密码,然后点击确认修改即可修改成功。更改密码界面效果如图5.12所示。

 图5.12 更改密码界面效果

5.4.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.13所示。

图5.13 模块文件的组织

(1)实体类

该类主要用于封装用户的信息:帐号、密码和用户等级等信息,类图如图5.14所示。

Account

-admin_name:String

-admin_pwd:String

-admin_level:int

提供了每个成员变量的getter和setter方法,还有全参构造方法、三个参数(admin_name,admin_pwd,admin_level)的构造方法,并重写了toString方法

图5.14 Account类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 账户实体类

*/

public class Account {

// 账号、密码

private String admin_name;

private String admin_pwd;

// 等级 0:普通用户 1-4 班系院校四级管理员

private int admin_level;

public Account() {}

public Account(String admin_name, String admin_pwd, int admin_level) {

super();

this.admin_name = admin_name;

this.admin_pwd = admin_pwd;

this.admin_level = admin_level;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getAdmin_pwd() {

return admin_pwd;

}

public void setAdmin_pwd(String admin_pwd) {

this.admin_pwd = admin_pwd;

}

public int getAdmin_level() {

return admin_level;

}

public void setAdmin_level(int admin_level) {

this.admin_level = admin_level;

}

@Override

public String toString() {

return "Account [admin_name=" + admin_name + ", admin_pwd=" + admin_pwd + ", admin_level=" + admin_level + "]";

}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的AccountDao,主要用来完成对表tb_account的增删改查操作。登录主要用到里面的查询方法。核心代码如下:

/**

 *  修改密码

 *  @param name 账号

 *  @param oldpwd

 *  @param newpwd

 *  @return boolean 是否成功

 */

public boolean changePwd(String name, String oldpwd, String newpwd) {

if(login(name, oldpwd) != null) {

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 编写SQL语句

String sql = "update tb_account set admin_pwd=? where admin_name=?";

// 创建预编译语句执行器

PreparedStatement stat = conn.prepareStatement(sql);

stat.setString(1, newpwd);

stat.setString(2, name);

// 执行

stat.executeUpdate();

// 关闭

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return true;

}else {

return false;

}

}

(3)界面层

定义ChangePwdFrame用于更改密码界面与引导。具体生成窗口的代码为:new ChangePwdFrame(pr.getAdmin_name()).setVisible(true);

 图5.15 界面组件图

核心代码:

package com.wd.registration.view;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.border.EmptyBorder;

import com.wd.registration.dao.AccountDao;

public class ChangePwdFrame extends JDialog implements ActionListener {

private JPanel contentPane;

private JPasswordField passwordField;

private JPasswordField passwordField_1;

private String username;

/**

 * Create the frame.

 */

public ChangePwdFrame(String username) {

this.username = username;

setBounds(50, 50, 225, 200);

setResizable(false);

setLocationRelativeTo(null);

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("\u539F\u5BC6\u7801\uFF1A");

lblNewLabel.setBounds(14, 33, 72, 18);

contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("\u65B0\u5BC6\u7801\uFF1A");

lblNewLabel_1.setBounds(14, 64, 72, 18);

contentPane.add(lblNewLabel_1);

passwordField = new JPasswordField();

passwordField.setBounds(78, 30, 115, 24);

contentPane.add(passwordField);

passwordField_1 = new JPasswordField();

passwordField_1.setBounds(78, 61, 115, 24);

contentPane.add(passwordField_1);

JButton btnNewButton = new JButton("\u786E\u8BA4\u4FEE\u6539");

btnNewButton.setBounds(48, 113, 113, 27);

this.getRootPane().setDefaultButton(btnNewButton);

contentPane.add(btnNewButton);

btnNewButton.addActionListener(this);

// 模态框

this.setModal(true);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "退出?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

         // 退出

         ChangePwdFrame.this.dispose();

        }

    }

});

}

@Override

public void actionPerformed(ActionEvent arg0) {

String oldpwd = String.valueOf(passwordField.getPassword());

String newpwd = String.valueOf(passwordField_1.getPassword());

if(newpwd.equals("")) {

JOptionPane.showMessageDialog(null, "密码不能为空");

} else if (newpwd.contains("=")){

JOptionPane.showMessageDialog(null, "密码不能含有字符‘=’");

} else if (newpwd.equals(oldpwd)){

JOptionPane.showMessageDialog(null, "密码未改变");

} else {

if(new AccountDao().changePwd(username, oldpwd, newpwd)) {

JOptionPane.showMessageDialog(null, "密码修改成功");

dispose();

} else {

JOptionPane.showMessageDialog(null, "密码修改失败,请检查原密码是否输入错误", "", JOptionPane.ERROR_MESSAGE);

}

}

}

}

5.5 个人信息修改功能

5.5.1 更改个人信息界面

用户在需要修改信息时,点击修改按钮,输入需修改的电话、QQ、微信、身份证、政治面貌、家庭地址、籍贯、寝室号、其他1、其他2信息,然后点击修改完成。修改个人信息界面效果如图5.16所示。

 图5.16 修改个人信息界面效果

5.5.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.17所示。

 图5.17 模块文件的组织

(1)实体类

该类主要用于封装用户个人的信息:账号(学号)、姓名、学院、专业、班级、电话、QQ、微信号、身份证号、政治面貌、家庭地址、籍贯、寝室、其他1、其他2信息,类图如图5.18所示。

Person

-admin_name: String

-admin_realname: String

-admin_academy:String

-admin_major:String

-admin_class:String

-admin_TEL:String

-admin_QQ:String

--admin_IDnum:String

-admin_politice:String

-admin_address:String

-admin_hometown:String

-admin_dormitory:String

-other1:String

-other2:String

提供了每个成员变量的getter和setter方法,还有全参构造方法、十四个参数(admin_name、admin_realname等)的构造方法,并重写了toString方法

图5.18 Person类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 个人信息实体类

*/

public class Person {

// 账号(学号)

private String admin_name;

// 姓名

private String admin_realname;

// 学院

private String admin_academy;

// 专业

private String admin_major;

// 班级

private String admin_class;

// 电话

private String admin_TEL;

// QQ

private String admin_QQ;

// 微信号

private String admin_WeChat;

// 身份证号

private String admin_IDnum;

// 政治面貌

private String admin_politice;

// 家庭地址

private String admin_address;

// 籍贯

private String admin_hometown;

// 寝室

private String admin_dormitory;

// 其他1

private String other1;

// 其他2

private String other2;

@Override

public String toString() {

return "Person [admin_name=" + admin_name + ", admin_realname=" + admin_realname + ", admin_academy="

+ admin_academy + ", admin_major=" + admin_major + ", admin_class=" + admin_class + ", admin_TEL="

+ admin_TEL + ", admin_QQ=" + admin_QQ + ", admin_WeChat=" + admin_WeChat + ", admin_IDnum="

+ admin_IDnum + ", admin_politice=" + admin_politice + ", admin_address=" + admin_address

+ ", admin_hometown=" + admin_hometown + ", admin_dormitory=" + admin_dormitory + ", other1=" + other1

+ ", other2=" + other2 + "]";

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getAdmin_realname() {

return admin_realname;

}

public void setAdmin_realname(String admin_realname) {

this.admin_realname = admin_realname;

}

public String getAdmin_academy() {

return admin_academy;

}

public void setAdmin_academy(String admin_academy) {

this.admin_academy = admin_academy;

}

public String getAdmin_major() {

return admin_major;

}

public void setAdmin_major(String admin_major) {

this.admin_major = admin_major;

}

public String getAdmin_class() {

return admin_class;

}

public void setAdmin_class(String admin_class) {

this.admin_class = admin_class;

}

public String getAdmin_TEL() {

return admin_TEL;

}

public void setAdmin_TEL(String admin_TEL) {

this.admin_TEL = admin_TEL;

}

public String getAdmin_QQ() {

return admin_QQ;

}

public void setAdmin_QQ(String admin_QQ) {

this.admin_QQ = admin_QQ;

}

public String getAdmin_WeChat() {

return admin_WeChat;

}

public void setAdmin_WeChat(String admin_WeChat) {

this.admin_WeChat = admin_WeChat;

}

public String getAdmin_IDnum() {

return admin_IDnum;

}

public void setAdmin_IDnum(String admin_IDnum) {

this.admin_IDnum = admin_IDnum;

}

public String getAdmin_politice() {

return admin_politice;

}

public void setAdmin_politice(String admin_politice) {

this.admin_politice = admin_politice;

}

public String getAdmin_address() {

return admin_address;

}

public void setAdmin_address(String admin_address) {

this.admin_address = admin_address;

}

public String getAdmin_hometown() {

return admin_hometown;

}

public void setAdmin_hometown(String admin_hometown) {

this.admin_hometown = admin_hometown;

}

public String getAdmin_dormitory() {

return admin_dormitory;

}

public void setAdmin_dormitory(String admin_dormitory) {

this.admin_dormitory = admin_dormitory;

}

public String getOther1() {

return other1;

}

public void setOther1(String other1) {

this.other1 = other1;

}

public String getOther2() {

return other2;

}

public void setOther2(String other2) {

this.other2 = other2;

}

public Person(String admin_name, String admin_realname, String admin_academy, String admin_major,

String admin_class, String admin_TEL, String admin_QQ, String admin_WeChat, String admin_IDnum,

String admin_politice, String admin_address, String admin_hometown, String admin_dormitory, String other1,

String other2) {

super();

this.admin_name = admin_name;

this.admin_realname = admin_realname;

this.admin_academy = admin_academy;

this.admin_major = admin_major;

this.admin_class = admin_class;

this.admin_TEL = admin_TEL;

this.admin_QQ = admin_QQ;

this.admin_WeChat = admin_WeChat;

this.admin_IDnum = admin_IDnum;

this.admin_politice = admin_politice;

this.admin_address = admin_address;

this.admin_hometown = admin_hometown;

this.admin_dormitory = admin_dormitory;

this.other1 = other1;

this.other2 = other2;

}

public Person() {}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的PersonDao,主要用来完成对表tb_person的增删改查操作。登录主要用到里面的查询方法。核心代码如下:

package com.wd.registration.dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.List;

import com.wd.registration.entity.Person;

import com.wd.registration.utils.DBUtils;

/**

 * 个人数据处理层

*/

public class PersonDao {

/**

 *  获取个人信息

 *  @param name 账号

 *  @return 返回个人信息,不正确返回null

 */

public Person getInformation(String name) {

Person pr = null;

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 创建语句执行器

Statement stat = conn.createStatement();

// 执行并返回结果

String sql = "select * from tb_person where admin_name=" + name;

ResultSet rs = stat.executeQuery(sql);

// 迭代

if(rs.next()) {

String admin_name = rs.getString("admin_name");

String admin_realname = rs.getString("admin_realname");

String admin_academy = rs.getString("admin_academy");

String admin_major = rs.getString("admin_major");

String admin_class = rs.getString("admin_class");

String admin_TEL = rs.getString("admin_TEL");

String admin_QQ = rs.getString("admin_QQ");

String admin_WeChat = rs.getString("admin_WeChat");

String admin_IDnum = rs.getString("admin_IDnum");

String admin_politice = rs.getString("admin_politice");

String admin_address = rs.getString("admin_address");

String admin_hometown = rs.getString("admin_hometown");

String admin_dormitory = rs.getString("admin_dormitory");

String other1 = rs.getString("other1");

String other2 = rs.getString("other2");

// 组装成对象

pr = new Person(admin_name, admin_realname, admin_academy, admin_major, admin_class, admin_TEL, admin_QQ, admin_WeChat, admin_IDnum, admin_politice, admin_address, admin_hometown, admin_dormitory, other1, other2);

}

// 关闭

rs.close();

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return pr;

}

/**

 *  存储个人信息

 *  @param Person 信息

 */

public void insert(Person pr) {

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 编写SQL语句

String sql = "insert into tb_person(admin_name, admin_realname, admin_academy, admin_major, admin_class) value(?, ?, ?, ?, ?)";

// 创建预编译语句执行器

PreparedStatement stat = conn.prepareStatement(sql);

stat.setString(1, pr.getAdmin_name());

stat.setString(2, pr.getAdmin_realname());

stat.setString(3, pr.getAdmin_academy());

stat.setString(4, pr.getAdmin_major());

stat.setString(5, pr.getAdmin_class());

// 执行

stat.executeUpdate();

// 关闭

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

 *  能否具备五大基本信息,可否注册成功注册

 *  @param name 五个信息String[]

 *  @return boolean数组表示几个成功

 */

public boolean[] canRegister(Person pr) {

boolean[] flag = {true, true, true, true, true};

if(pr.getAdmin_name().equals("")) flag[0] = false;

if(pr.getAdmin_realname().equals("")) flag[1] = false;

if(pr.getAdmin_academy().equals("")) flag[2] = false;

if(pr.getAdmin_major().equals("")) flag[3] = false;

if(pr.getAdmin_class().equals("")) flag[4] = false;

return flag;

}

/**

 *  更新个人信息

 *  @param Person 信息

 */

public void update(Person pr) {

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 编写SQL语句

String sql = "update tb_person set admin_TEL=?, admin_QQ=?, admin_WeChat=?,"

+ " admin_IDnum=?, admin_politice=?, admin_address=?, admin_hometown=?,"

+ " admin_dormitory=?, other1=?, other2=? where admin_name=?";

// 创建预编译语句执行器

PreparedStatement stat = conn.prepareStatement(sql);

stat.setString(1, pr.getAdmin_TEL());

stat.setString(2, pr.getAdmin_QQ());

stat.setString(3, pr.getAdmin_WeChat());

stat.setString(4, pr.getAdmin_IDnum());

stat.setString(5, pr.getAdmin_politice());

stat.setString(6, pr.getAdmin_address());

stat.setString(7, pr.getAdmin_hometown());

stat.setString(8, pr.getAdmin_dormitory());

stat.setString(9, pr.getOther1());

stat.setString(10, pr.getOther2());

stat.setString(11, pr.getAdmin_name());

// 执行

stat.executeUpdate();

// 关闭

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

5.6 发布活动功能

5.6.1 发布活动界面

用户需要发布活动时,点击发布活动按钮,跳转至活动发布界面。在界面输入发布范围、发布名称、发布时间、活动地点、报名持续时间、加分情况、其他事项,然后点击立即发布即可发布成功。发布活动界面效果如图5.19所示。

 图5.19 发布活动界面效果

5.6.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.20所示。

 图5.20 模块文件的组织

(1)实体类

该类主要用于封装发布活动的信息:活动号、活动名、活动发布范围、发布人、活动开始时间、活动结束时间等,类图如图5.21所示。

Activity

-activity_num: String

-activity_name: String

-activity_range:String

-admin_name:String

-activity_begintime:String

-activity_endtime:String

-activity_content:String

提供了每个成员变量的getter和setter方法,还有全参构造方法、七参数(activity_num、activity_name等)的构造方法,并重写了toString方法

图5.21 Activity类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 活动信息实体类

*/

public class Activity {

private String activity_num;

private String activity_name;

private String activity_range;

private String admin_name;

private String activity_begintime;

private String activity_endtime;

private String activity_content;

public String getActivity_num() {

return activity_num;

}

public void setActivity_num(String activity_num) {

this.activity_num = activity_num;

}

public String getActivity_name() {

return activity_name;

}

public void setActivity_name(String activity_name) {

this.activity_name = activity_name;

}

public String getActivity_range() {

return activity_range;

}

public void setActivity_range(String activity_range) {

this.activity_range = activity_range;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getActivity_begintime() {

return activity_begintime;

}

public void setActivity_begintime(String activity_begintime) {

this.activity_begintime = activity_begintime;

}

public String getActivity_endtime() {

return activity_endtime;

}

public void setActivity_endtime(String activity_endtime) {

this.activity_endtime = activity_endtime;

}

public String getActivity_content() {

return activity_content;

}

public void setActivity_content(String activity_content) {

this.activity_content = activity_content;

}

public Activity(String activity_num, String activity_name, String activity_range, String admin_name,

String activity_begintime, String activity_endtime, String activity_content) {

super();

this.activity_num = activity_num;

this.activity_name = activity_name;

this.activity_range = activity_range;

this.admin_name = admin_name;

this.activity_begintime = activity_begintime;

this.activity_endtime = activity_endtime;

this.activity_content = activity_content;

}

public Activity() {}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的ActivityDao,主要用来完成对表tb_activity的增删改查操作。发布活动主要用到里面的新增方法。核心代码如下:

/**

 *  发布新活动信息

 *  @param 信息

 */

public void insert(Activity act) {

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 编写SQL语句

String sql = "insert into tb_activity(activity_num, activity_name, activity_range, admin_name, activity_begintime, activity_endtime, activity_content) value(?, ?, ?, ?, ?, ?, ?)";

// 创建预编译语句执行器

PreparedStatement stat = conn.prepareStatement(sql);

stat.setString(1, act.getActivity_num());

stat.setString(2, act.getActivity_name());

stat.setString(3, act.getActivity_range());

stat.setString(4, act.getAdmin_name());

stat.setString(5, act.getActivity_begintime());

stat.setString(6, act.getActivity_endtime());

stat.setString(7, act.getActivity_content());

// 执行

stat.executeUpdate();

// 关闭

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

(3)界面层

定义PostFrame用于实现发布活动界面与引导,可以选择发布范围(根据发布者的所在学院专业班级以及发布者的用户等级而定)、发布活动具体信息(如:名称、时间、地点、持续时间、加分情况等等)。生成窗口的代码:PostFrame frame = new PostFrame(level, pr);frame.setVisible(true);

 图5.22 界面组件图

核心代码:

package com.wd.registration.view;

import java.awt.BorderLayout;

import java.awt.HeadlessException;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.Calendar;

import java.util.Date;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JSpinner;

import javax.swing.JSpinner.DefaultEditor;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.SpinnerNumberModel;

import javax.swing.SwingConstants;

import javax.swing.border.EmptyBorder;

import com.wd.registration.dao.ActivityDao;

import com.wd.registration.dao.PostDao;

import com.wd.registration.entity.Activity;

import com.wd.registration.entity.Person;

import com.wd.registration.entity.Post;

public class PostFrame extends JDialog {

private JPanel contentPane;

private JTextField textField_1;

private JTextField textField_3;

private JTextField textField;

private JTextArea textArea;

private JComboBox comboBox;

private JSpinner spinner;

private JSpinner spinner_1;

private DefaultEditor editor;

private JSpinner spinner_2_0, spinner_2_1, spinner_2_2, spinner_2_3;

/**

 * Create the frame.

 */

public PostFrame(int level, Person pr) {

setTitle("\u6D3B\u52A8\u53D1\u5E03");

setBounds(100, 100, 450, 400);

setResizable(false);

setLocationRelativeTo(null);

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

contentPane.setLayout(new BorderLayout(0, 0));

setContentPane(contentPane);

JButton btnNewButton = new JButton("\u7ACB\u5373\u53D1\u5E03");

contentPane.add(btnNewButton, BorderLayout.SOUTH);

btnNewButton.addActionListener((event)->{

if(textArea.getText().length() >= 130) {

JOptionPane.showMessageDialog(null, "其他事项字数过多", "", JOptionPane.ERROR_MESSAGE);

}

else {

// 发布活动至数据库

postActivity(pr);

}

});

JPanel main_panel = new JPanel();

contentPane.add(main_panel, BorderLayout.CENTER);

main_panel.setLayout(null);

JLabel lblNewLabel_1 = new JLabel("\u53D1\u5E03\u8303\u56F4\uFF1A");

lblNewLabel_1.setBounds(38, 10, 75, 18);

main_panel.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("\u6D3B\u52A8\u540D\u79F0\uFF1A");

lblNewLabel_2.setBounds(38, 41, 75, 18);

main_panel.add(lblNewLabel_2);

textField_1 = new JTextField();

textField_1.setBounds(121, 38, 301, 24);

main_panel.add(textField_1);

textField_1.setColumns(10);

JLabel lblNewLabel_3 = new JLabel("\u6D3B\u52A8\u65F6\u95F4\uFF1A");

lblNewLabel_3.setBounds(40, 72, 75, 18);

main_panel.add(lblNewLabel_3);

JLabel lblNewLabel_3_1 = new JLabel("\u6D3B\u52A8\u5730\u70B9\uFF1A");

lblNewLabel_3_1.setBounds(38, 103, 75, 18);

main_panel.add(lblNewLabel_3_1);

textField_3 = new JTextField();

textField_3.setBounds(121, 100, 301, 24);

main_panel.add(textField_3);

textField_3.setColumns(10);

JLabel lblNewLabel_5 = new JLabel("\u62A5\u540D\u6301\u7EED\u65F6\u95F4\uFF1A");

lblNewLabel_5.setBounds(8, 134, 105, 18);

main_panel.add(lblNewLabel_5);

JLabel lblNewLabel_4 = new JLabel("\u5176\u4ED6\u4E8B\u9879\uFF1A");

lblNewLabel_4.setBounds(38, 221, 75, 18);

main_panel.add(lblNewLabel_4);

spinner = new JSpinner(new SpinnerNumberModel(1, 1, 10, 0.5));

spinner.setBounds(121, 131, 48, 24);

main_panel.add(spinner);

editor = (DefaultEditor) spinner.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_6 = new JLabel("\u5929");

lblNewLabel_6.setBounds(176, 134, 21, 18);

main_panel.add(lblNewLabel_6);

comboBox = new JComboBox(getList(level, pr));

comboBox.setBounds(121, 7, 301, 24);

main_panel.add(comboBox);

JLabel lblNewLabel_8 = new JLabel("\u52A0\u5206\u60C5\u51B5\uFF1A");

lblNewLabel_8.setBounds(224, 134, 75, 18);

main_panel.add(lblNewLabel_8);

spinner_1 = new JSpinner(new SpinnerNumberModel(0, 0, 5, 0.5));

spinner_1.setBounds(306, 131, 48, 24);

main_panel.add(spinner_1);

editor = (DefaultEditor) spinner_1.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_6_1 = new JLabel("\u5206");

lblNewLabel_6_1.setBounds(363, 134, 21, 18);

main_panel.add(lblNewLabel_6_1);

textArea = new JTextArea();

textArea.setBounds(121, 168, 301, 124);

main_panel.add(textArea);

textArea.setLineWrap(true);

spinner_2_0 = new JSpinner(new SpinnerNumberModel(2020, 2020, 2050, 1));

spinner_2_0.setBounds(121, 69, 56, 24);

main_panel.add(spinner_2_0);

editor = (DefaultEditor) spinner_2_0.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_9 = new JLabel("\u5E74");

lblNewLabel_9.setBounds(180, 72, 21, 18);

main_panel.add(lblNewLabel_9);

spinner_2_1 = new JSpinner(new SpinnerNumberModel(1, 1, 12, 1));

spinner_2_1.setBounds(200, 69, 36, 24);

main_panel.add(spinner_2_1);

editor = (DefaultEditor) spinner_2_1.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_9_1 = new JLabel("\u6708");

lblNewLabel_9_1.setBounds(235, 72, 21, 18);

main_panel.add(lblNewLabel_9_1);

spinner_2_2 = new JSpinner(new SpinnerNumberModel(1, 1, 31, 1));

spinner_2_2.setBounds(255, 69, 36, 24);

main_panel.add(spinner_2_2);

editor = (DefaultEditor) spinner_2_2.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_9_1_1 = new JLabel("\u65E5");

lblNewLabel_9_1_1.setBounds(290, 72, 21, 18);

main_panel.add(lblNewLabel_9_1_1);

spinner_2_3 = new JSpinner(new SpinnerNumberModel(1, 1, 24, 1));

spinner_2_3.setBounds(310, 69, 36, 24);

main_panel.add(spinner_2_3);

editor = (DefaultEditor) spinner_2_3.getEditor();

editor.getTextField().setEditable(false);

JLabel lblNewLabel_9_1_1_1 = new JLabel("\u65F6");

lblNewLabel_9_1_1_1.setBounds(350, 72, 21, 18);

main_panel.add(lblNewLabel_9_1_1_1);

JButton btnNewButton_1 = new JButton("now");

btnNewButton_1.setBounds(374, 68, 48, 27);

main_panel.add(btnNewButton_1);

btnNewButton_1.addActionListener((event)->{

Calendar now = Calendar.getInstance();

spinner_2_0.setValue(now.get(Calendar.YEAR));

spinner_2_1.setValue(now.get(Calendar.MONTH) + 1);

spinner_2_2.setValue(now.get(Calendar.DAY_OF_MONTH));

spinner_2_3.setValue(now.get(Calendar.HOUR_OF_DAY));

});

JPanel notice_panel = new JPanel();

contentPane.add(notice_panel, BorderLayout.NORTH);

notice_panel.setLayout(new BoxLayout(notice_panel, BoxLayout.X_AXIS));

JLabel lblNewLabel = new JLabel("\u60A8\u62E5\u6709");

notice_panel.add(lblNewLabel);

textField = new JTextField();

textField.setHorizontalAlignment(SwingConstants.CENTER);

textField.setEditable(false);

//根据管理员等级不同switch不同的权限

switch(level) {

case 1:textField.setText("班级");break;

case 2:textField.setText("专业");break;

case 3:textField.setText("学院");break;

default:textField.setText("学校");break; //case 4

}

notice_panel.add(textField);

textField.setColumns(10);

JLabel lblNewLabel_7 = new JLabel("\u6D3B\u52A8\u53D1\u5E03\u6743\u9650\uFF0C\u83B7\u53D6\u66F4\u9AD8\u7EA7\u6743\u9650\u8BF7\u8054\u7CFB\u9879\u76EE\u5F00\u53D1\u4EBA\u5458");

notice_panel.add(lblNewLabel_7);

// 模态框

this.setModal(true);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "确认取消发布?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

        // 退出

         PostFrame.this.dispose();

        }

    }

});

}

private void postActivity(Person pr) throws NumberFormatException, HeadlessException {

Date nowTime = new Date();

PostDao pod = new PostDao();

Post po = pod.setPost(nowTime, String.valueOf(comboBox.getSelectedItem()), textField_1.getText(),

String.valueOf(spinner_2_0.getValue()), String.valueOf(spinner_2_1.getValue()), String.valueOf(spinner_2_2.getValue()),

String.valueOf(spinner_2_3.getValue()), textField_3.getText(), Double.parseDouble(String.valueOf(spinner.getValue())),

String.valueOf(spinner_1.getValue()), textArea.getText());

if(pod.canPost(po) == true) {

// 将Post对象改装成Activity对象

Activity act = new Activity();

act.setActivity_num(pod.newOrderNum(nowTime));

act.setActivity_name(po.getActivity_name());

act.setActivity_range(po.getActivity_range());

act.setAdmin_name(pr.getAdmin_name());

act.setActivity_begintime(pod.formatTime(nowTime));

act.setActivity_endtime(pod.formatTime(pod.addDate(nowTime, po.getActivity_duration())));

act.setActivity_content(po.toString());

// 将Activity发布到数据库

new ActivityDao().insert(act);

JOptionPane.showMessageDialog(null, "发布成功,主面板点击刷新可查看所需内容");

this.dispose();

}

else {

JOptionPane.showMessageDialog(null, "内容均不可为空", "", JOptionPane.ERROR_MESSAGE);

}

}

private String[] getList(int level, Person pr) {

String[] list = new String[level];

switch(level) {

case 4: list[3] = "中北大学";

case 3: list[2] = pr.getAdmin_academy();

case 2: list[1] = pr.getAdmin_major();

case 1: list[0] = pr.getAdmin_class();

}

return list;

}

}

5.7 查看活动详情功能

5.7.1 查看活动详情界面

用户在需要看发布的新的活动时,点击活动进入活动详情,在里面可以看到活动的具体信息,如果想要报名可以点击报名按钮完成报名。查看活动详情界面效果如图5.23所示。

 图5.23 查看活动详情界面效果

5.7.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.24所示。

 图5.24 模块文件的组织

(1)实体类

该类主要用于封装活动的信息:活动号、活动名、活动发布范围、发布人、活动开始时间、活动结束时间等,类图如图5.25所示。

Activity

-activity_num: String

-activity_name: String

-activity_range:String

-admin_name:String

-activity_begintime:String

-activity_endtime:String

-activity_content:String

提供了每个成员变量的getter和setter方法,还有全参构造方法、七参数(activity_num、activity_name等)的构造方法,并重写了toString方法

图5.25 Activity类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 活动信息实体类

*/

public class Activity {

private String activity_num;

private String activity_name;

private String activity_range;

private String admin_name;

private String activity_begintime;

private String activity_endtime;

private String activity_content;

public String getActivity_num() {

return activity_num;

}

public void setActivity_num(String activity_num) {

this.activity_num = activity_num;

}

public String getActivity_name() {

return activity_name;

}

public void setActivity_name(String activity_name) {

this.activity_name = activity_name;

}

public String getActivity_range() {

return activity_range;

}

public void setActivity_range(String activity_range) {

this.activity_range = activity_range;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public String getActivity_begintime() {

return activity_begintime;

}

public void setActivity_begintime(String activity_begintime) {

this.activity_begintime = activity_begintime;

}

public String getActivity_endtime() {

return activity_endtime;

}

public void setActivity_endtime(String activity_endtime) {

this.activity_endtime = activity_endtime;

}

public String getActivity_content() {

return activity_content;

}

public void setActivity_content(String activity_content) {

this.activity_content = activity_content;

}

public Activity(String activity_num, String activity_name, String activity_range, String admin_name,

String activity_begintime, String activity_endtime, String activity_content) {

super();

this.activity_num = activity_num;

this.activity_name = activity_name;

this.activity_range = activity_range;

this.admin_name = admin_name;

this.activity_begintime = activity_begintime;

this.activity_endtime = activity_endtime;

this.activity_content = activity_content;

}

public Activity() {}

}

该类主要用于封装报名的信息:活动号、报名者账号,类图如图5.26所示。

Enroll

-activity_num: String

-admin_name: String

提供了每个成员变量的getter和setter方法,还有全参构造方法、两个参数(activity_num、admin_name)的构造方法,并重写了toString方法

图5.26 Enroll类图

核心代码如下:

package com.wd.registration.entity;

/**

 * 报名实体类

*/

public class Enroll {

// 活动号

private String activity_num;

// 报名者账号

private String admin_name;

public Enroll(String activity_num, String admin_name) {

super();

this.activity_num = activity_num;

this.admin_name = admin_name;

}

public String getActivity_num() {

return activity_num;

}

public void setActivity_num(String activity_num) {

this.activity_num = activity_num;

}

public String getAdmin_name() {

return admin_name;

}

public void setAdmin_name(String admin_name) {

this.admin_name = admin_name;

}

public Enroll() {}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的ActivityDao,主要用来完成对表tb_activity的增删改查操作。活动详情查看主要用到里面的查询方法。核心代码如下:

/**

 *  获取列表信息

 *  @param name 账号

 *  @return 返回个人信息,不正确返回null

 */

public List<Activity> getInformation(String admin_academy, String admin_major, String admin_class) {

List<Activity> actArr = new ArrayList();

Activity act = null;

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 创建语句执行器

Statement stat = conn.createStatement();

// 执行并返回结果

String sql = "select * from tb_activity where activity_range='" + admin_academy + "' or activity_range='"

+ admin_major + "' or activity_range='" + admin_class + "' or activity_range='长沙理工大学'";

ResultSet rs = stat.executeQuery(sql);

// 迭代

while(rs.next()) {

String activity_num = rs.getString("activity_num");

String activity_name = rs.getString("activity_name");

String activity_range = rs.getString("activity_range");

String admin_name = rs.getString("admin_name");

String activity_begintime = rs.getString("activity_begintime");

String activity_endtime = rs.getString("activity_endtime");

String activity_content = rs.getString("activity_content");

// 组装成对象

act = new Activity(activity_num, activity_name, activity_range, admin_name, activity_begintime, activity_endtime, activity_content);

actArr.add(act);

}

// 关闭

rs.close();

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return actArr;

}

/**

 *  关于活动

 *  @param name 账号

 *  @return 返回活动信息

 */

public Activity getActivity(String num) {

Activity act = null;

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 创建语句执行器

Statement stat = conn.createStatement();

// 执行并返回结果

String sql = "select * from tb_activity where activity_num='" + num + "'";

ResultSet rs = stat.executeQuery(sql);

// 迭代

if(rs.next()) {

String activity_num = rs.getString("activity_num");

String activity_name = rs.getString("activity_name");

String activity_range = rs.getString("activity_range");

String admin_name = rs.getString("admin_name");

String activity_begintime = rs.getString("activity_begintime");

String activity_endtime = rs.getString("activity_endtime");

String activity_content = rs.getString("activity_content");

// 组装成对象

act = new Activity(activity_num, activity_name, activity_range, admin_name, activity_begintime, activity_endtime, activity_content);

}

// 关闭

rs.close();

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return act;

}

Dao层用来定义操作数据库的EnrollDao,主要用来完成对表tb_enroll的增删改查操作。活动详情查看主要用到里面的查询方法。核心代码如下:

package com.wd.registration.dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import com.wd.registration.entity.Enroll;

import com.wd.registration.entity.Person;

import com.wd.registration.utils.DBUtils;

/**

 * 报名数据处理

*/

public class EnrollDao {

/**

 *  插入报名信息,如果有过就不能加

 *  @param name 账号

 *  @return 是否插入成功

 */

public boolean insert(Enroll en) {

boolean flag = true;

Connection conn = null;

Statement stat = null;

ResultSet rs = null;

PreparedStatement stat1 = null;

try {

// 利用数据库工具获取连接

conn = DBUtils.getConnection();

// 创建语句执行器

stat = conn.createStatement();

// 执行并返回结果

String sql = "select * from tb_enroll where activity_num='" + en.getActivity_num() + "'and admin_name='" + en.getAdmin_name() + "'";

rs = stat.executeQuery(sql);

// 迭代

if(rs.next()) {

flag = false;

} else {

String sql1 = "insert into tb_enroll(activity_num, admin_name) value(?, ?)";

// 创建预编译语句执行器

stat1 = conn.prepareStatement(sql1);

stat1.setString(1, en.getActivity_num());

stat1.setString(2, en.getAdmin_name());

// 执行

stat1.executeUpdate();

stat1.close();

}

} catch (Exception e) {

flag = false;

} finally {

// 关闭连接等

try {

rs.close();

stat.close();

conn.close();

} catch (Exception e1) {

e1.printStackTrace();

}

}

return flag;

}

/**

 *  获取报名人员列表

 *  @param 活动号

 *  @return 报名人员列表

 */

public List<Person> getInformation(String activity_num) {

List<Person> prArr = new ArrayList();

Person pr = null;

try {

// 利用数据库工具获取连接

Connection conn = DBUtils.getConnection();

// 创建语句执行器

Statement stat = conn.createStatement();

// 执行并返回结果

String sql = "select admin_name from tb_enroll where activity_num='" + activity_num + "'";

ResultSet rs = stat.executeQuery(sql);

// 迭代

while(rs.next()) {

pr = new PersonDao().getInformation(rs.getString("admin_name"));

prArr.add(pr);

}

// 关闭

rs.close();

stat.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

return prArr;

}

}

(3)界面层

定义ActivityFrame用于实现查看活动详情页面与引导,用户点击活动列表上的相关活动,如果不在可报名时间内则无法点入,否则进入查看活动详情页面。可显示活动的详细信息以及截至目前的报名情况简表,若用户即为此活动的发布者,还可以选择导出活动报名表的详表。生成窗口的代码:ActivityFrame frame = new ActivityFrame(new ActivityDao().getActivity(table.getValueAt(selectedRow, 0).toString()), pr.getAdmin_name());frame.setVisible(true);

 图5.27 界面组件图

核心代码:

package com.wd.registration.view;

import java.awt.Color;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.List;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextPane;

import javax.swing.SwingConstants;

import javax.swing.border.EmptyBorder;

import javax.swing.border.LineBorder;

import javax.swing.border.TitledBorder;

import javax.swing.table.DefaultTableModel;

import com.wd.registration.dao.EnrollDao;

import com.wd.registration.entity.Activity;

import com.wd.registration.entity.Enroll;

import com.wd.registration.entity.Person;

public class ActivityFrame extends JDialog implements ActionListener {

private JPanel contentPane;

private JTable table;

private DefaultTableModel dtm; // 表单

private JButton btnNewButton_1;

private JButton btnNewButton;

private String admin_name;

private Activity act;

private List<Person> temp;

/**

 * Create the frame.

 */

public ActivityFrame(Activity act, String admin_name) {

this.act = act;

this.admin_name = admin_name;

// 设置窗口默认关闭动作为执行window事件中定义的操作

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

setTitle(act.getActivity_name());

setBounds(100, 100, 640, 650);

setResizable(false);

setLocationRelativeTo(null);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JPanel activity_panel = new JPanel();

activity_panel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 2), "\u6D3B\u52A8\u8BE6\u60C5\u9762\u677F", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));

activity_panel.setBounds(15, 7, 595, 245);

contentPane.add(activity_panel);

activity_panel.setLayout(null);

JTextPane textPane = new JTextPane();

textPane.setFont(new Font("方正粗黑宋简体", Font.PLAIN, 18));

textPane.setText(act.getActivity_content());

textPane.setEditable(false);

textPane.setBounds(15, 25, 475, 205);

activity_panel.add(textPane);

btnNewButton_1 = new JButton("\u62A5\u540D");

btnNewButton_1.addActionListener(this);

btnNewButton_1.setFont(new Font("华文新魏", Font.BOLD, 20));

btnNewButton_1.setBounds(500, 25, 80, 205);

activity_panel.add(btnNewButton_1);

JScrollPane scrollPane = new JScrollPane();

scrollPane.setBounds(15, 280, 595, 280);

contentPane.add(scrollPane);

// 建立表格

String[] header = {"序号", "姓名", "学院", "专业", "班级"};

dtm = new DefaultTableModel(null, header) {

// 禁止编辑表格

    @Override

    public boolean isCellEditable(int row, int column) {

        return false;

    }

};

// 生成数据

temp = new EnrollDao().getInformation(act.getActivity_num());

int count = 0;

for(Person p : temp) {

dtm.addRow(new Object[] {++count, p.getAdmin_realname(), p.getAdmin_academy(), p.getAdmin_major(), p.getAdmin_class()});

}

table = new JTable(dtm);

scrollPane.setViewportView(table);

// 设置表格内容颜色

        table.setForeground(Color.BLACK);                   // 字体颜色

        table.setFont(new Font(null, Font.PLAIN, 13));      // 字体样式

        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色

        table.setSelectionBackground(Color.LIGHT_GRAY);     // 选中后字体背景

        table.setGridColor(Color.GRAY);                     // 网格颜色

        // 设置表头

        table.getTableHeader().setFont(new Font(null, Font.BOLD, 15));  // 设置表头名称字体样式

        table.getTableHeader().setForeground(Color.BLACK);                // 设置表头名称字体颜色

        table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽

        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高

        table.setRowHeight(30);

        // 设置列宽

        table.getColumnModel().getColumn(0).setPreferredWidth(10);

        table.getColumnModel().getColumn(1).setPreferredWidth(10);

        table.getColumnModel().getColumn(4).setPreferredWidth(10);

JLabel lblNewLabel = new JLabel("\u62A5\u540D\u60C5\u51B5");

lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);

lblNewLabel.setFont(new Font("华文新魏", Font.PLAIN, 20));

lblNewLabel.setBounds(260, 250, 105, 30);

contentPane.add(lblNewLabel);

btnNewButton = new JButton("\u5BFC\u51FA\u8BE6\u7EC6\u60C5\u51B5\u8868");

btnNewButton.addActionListener(this);

btnNewButton.setFont(new Font("华文新魏", Font.PLAIN, 15));

btnNewButton.setBounds(450, 565, 145, 30);

contentPane.add(btnNewButton);

if(!admin_name.equals(act.getAdmin_name())) {

btnNewButton.setEnabled(false);

}

// 模态框

this.setModal(true);

// 添加确认关闭代码

addWindowListener (new WindowAdapter() {

    @Override

    public void windowClosing(WindowEvent e) {

        int result = JOptionPane.showConfirmDialog(null, "确定关闭?", "",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {

        // 退出系统

         ActivityFrame.this.dispose();

        }

    }

});

}

public void actionPerformed(ActionEvent e) {

// 添加报名信息

if(e.getSource()==btnNewButton_1) {

if(new EnrollDao().insert(new Enroll(act.getActivity_num(), admin_name))) {

JOptionPane.showMessageDialog(this, "报名成功");

} else {

JOptionPane.showMessageDialog(this, "报名失败,可能已经报过名了", "错误", JOptionPane.ERROR_MESSAGE);

}

}

// 导出Excel

if(e.getSource()==btnNewButton) {

try {

MakeExcelFrame frame = new MakeExcelFrame(act.getActivity_name(), temp);

frame.setVisible(true);

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

}

5.8 导出Excel表格页面设计

5.8.1 导出Excel表格界面

用户在需要导出信息时,点击活动进入活动详情,在里面可以看到活动的具体信息,如果需要导出信息,点击下面的导出成excel表格。导出页面如图5.28所示。

 图5.28导出Excel界面设计

5.8.2 该模块涉及到的文件和类

通过详细的分析,该模块涉及到的文件和类在工程中的组织如图5.29所示。

 图5.29 模块文件的组织

(1)实体类

该类主要用于封装表格的信息:表格名称、表格路径、表格标题、内容,类图如图5.30所示。

Excel

-excel_name: String

-excel_path: String

-table_name:String

-table_titles:List

-table_content:List

提供了每个成员变量的getter和setter方法,还有全参构造方法、五个参数(excel_name、excel_path等)的构造方法,并重写了toString方法

图5.30 Excel类图

核心代码:

package com.wd.registration.entity;

import java.util.List;

public class Excel {

private String excel_name; // .xls

private String excel_path;

private String table_name;

private List<String> table_titles;

private List<Person> table_content;

public Excel() {}

public String getExcel_name() {

return excel_name;

}

public void setExcel_name(String excel_name) {

this.excel_name = excel_name;

}

public String getExcel_path() {

return excel_path;

}

public void setExcel_path(String excel_path) {

this.excel_path = excel_path;

}

public String getTable_name() {

return table_name;

}

public void setTable_name(String table_name) {

this.table_name = table_name;

}

public List<String> getTable_titles() {

return table_titles;

}

public void setTable_titles(List<String> table_titles) {

this.table_titles = table_titles;

}

public List<Person> getTable_content() {

return table_content;

}

public void setTable_content(List<Person> table_content) {

this.table_content = table_content;

}

public Excel(String excel_name, String excel_path, String table_name, List<String> table_titles,

List<Person> table_content) {

super();

this.excel_name = excel_name;

this.excel_path = excel_path;

this.table_name = table_name;

this.table_titles = table_titles;

this.table_content = table_content;

}

}

(2)文件操作层(Dao层)

Dao层用来定义操作数据库的ExcelDao,主要用来完成对生成excel表格生成的方法。核心代码如下:

package com.wd.registration.dao;

import java.io.File;

import com.wd.registration.entity.Excel;

import com.wd.registration.entity.Person;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

public class ExcelDao {

// 生成Excel

public void CreatExcel(Excel exc) throws Exception {

File file=new File(exc.getExcel_path() + exc.getExcel_name());

file.createNewFile();

WritableWorkbook workbook=Workbook.createWorkbook(file);

WritableSheet sheet=workbook.createSheet(exc.getTable_name(), 0);

Label label=null;

for(int i=0;i<exc.getTable_titles().size();i++){

label=new Label(i,0,exc.getTable_titles().get(i));

sheet.addCell(label);

}

int row = 1;

for(Person arow : exc.getTable_content()) {

int i = 0;

for(String item: exc.getTable_titles()) {

if(item.equals("学号")){

sheet.addCell(new Label(i,row,arow.getAdmin_name()));

} else if (item.equals("姓名")) {

sheet.addCell(new Label(i,row,arow.getAdmin_realname()));

} else if (item.equals("学院")) {

sheet.addCell(new Label(i,row,arow.getAdmin_academy()));

} else if (item.equals("专业")) {

sheet.addCell(new Label(i,row,arow.getAdmin_major()));

} else if (item.equals("班级")) {

sheet.addCell(new Label(i,row,arow.getAdmin_class()));

} else if (item.equals("电话")) {

sheet.addCell(new Label(i,row,arow.getAdmin_TEL()));

} else if (item.equals("QQ")) {

sheet.addCell(new Label(i,row,arow.getAdmin_QQ()));

} else if (item.equals("微信")) {

sheet.addCell(new Label(i,row,arow.getAdmin_WeChat()));

} else if (item.equals("身份证")) {

sheet.addCell(new Label(i,row,arow.getAdmin_IDnum()));

} else if (item.equals("政治面貌")) {

sheet.addCell(new Label(i,row,arow.getAdmin_politice()));

} else if (item.equals("家庭住址")) {

sheet.addCell(new Label(i,row,arow.getAdmin_address()));

} else if (item.equals("籍贯")) {

sheet.addCell(new Label(i,row,arow.getAdmin_hometown()));

} else if (item.equals("寝室号")) {

sheet.addCell(new Label(i,row,arow.getAdmin_dormitory()));

} else if (item.equals("其他1")) {

sheet.addCell(new Label(i,row,arow.getOther1()));

} else if (item.equals("其他2")) {

sheet.addCell(new Label(i,row,arow.getOther2()));

}

i++; // 自增

}

row += 1;

}

workbook.write();

workbook.close();

}

}

(3)界面层

Definir MakeExcelFrame para realizar a geração da interface e orientação do Excel.De acordo com a necessidade do organizador do evento, as informações dos inscritos podem ser coletadas e a tabela de estatísticas de inscrição pode ser gerada. Gere o código da janela: MakeExcelFrame frame = new MakeExcelFrame(act.getActivity_name(), temp);frame.setVisible(true);

 Figura 5.31 Exportar componentes da interface do Excel

Acho que você gosta

Origin blog.csdn.net/lf21qp/article/details/131593620
Recomendado
Clasificación