Compare commits

...

No commits in common. 'master' and 'main' have entirely different histories.
master ... main

38
.gitignore vendored

@ -1,38 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
.idea/.gitignore vendored

@ -1,8 +0,0 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CodeReadingNote">
<topics />
<state lastExportDir="" lastImportDir="" />
</component>
</project>

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="product@localhost" uuid="75250724-1f0c-48e7-b2ec-693f5b79a97a">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306/product</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

@ -1,71 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AliAccessStaticViaInstance" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliArrayNamingShouldHaveBracket" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliControlFlowStatementWithoutBraces" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliDeprecation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliEqualsAvoidNull" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliLongLiteralsEndingWithLowercaseL" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliMissingOverrideAnnotation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliWrapperTypeEquality" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAbstractClassShouldStartWithAbstractNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAbstractMethodOrInterfaceMethodMustUseJavadoc" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidApacheBeanUtilsCopy" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidCallStaticSimpleDateFormat" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidCommentBehindStatement" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidComplexCondition" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidConcurrentCompetitionRandom" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidDoubleOrFloatEqualCompare" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidManuallyCreateThread" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidMissUseOfMathRandom" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidNegationOperator" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidNewDateGetTime" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidPatternCompileInMethod" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidReturnInFinally" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidStartWithDollarAndUnderLineNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidUseTimer" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaBigDecimalAvoidDoubleConstructor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaBooleanPropertyShouldNotStartWithIs" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaClassCastExceptionWithSubListToArrayList" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaClassCastExceptionWithToArray" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaClassMustHaveAuthor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaClassNamingShouldBeCamel" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaCollectionInitShouldAssignCapacity" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaCommentsMustBeJavadocFormat" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaConcurrentExceptionWithModifyOriginSubList" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaConstantFieldShouldBeUpperCase" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaCountDownShouldInFinally" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaDontModifyInForeachCircle" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaEnumConstantsMustHaveComment" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaExceptionClassShouldEndWithException" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaIbatisMethodQueryForList" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaLockShouldWithTryFinally" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaLowerCamelCaseVariableNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaMethodReturnWrapperType" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaMethodTooLong" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaPackageNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaPojoMustOverrideToString" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaPojoMustUsePrimitiveField" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaPojoNoDefaultValue" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaRemoveCommentedCode" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaServiceOrDaoClassShouldEndWithImpl" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaSneakyThrowsWithoutExceptionType" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaStringConcat" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaSwitchExpression" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaSwitchStatement" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaTestClassShouldEndWithTestNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaThreadLocalShouldRemove" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaThreadPoolCreation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaThreadShouldSetName" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaTransactionMustHaveRollback" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUndefineMagicConstant" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUnsupportedExceptionWithModifyAsList" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUseQuietReferenceNotation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUseRightCaseForDateFormat" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,java.lang.Class,getResourceAsStream" />
</inspection_tool>
<inspection_tool class="MapOrSetKeyShouldOverrideHashCodeEquals" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<list size="2">
<item index="0" class="java.lang.String" itemvalue="Test" />
<item index="1" class="java.lang.String" itemvalue="lombok.Data" />
</list>
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21_PREVIEW" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/resources/db_product.sql" dialect="MySQL" />
</component>
</project>

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
<component name="VcsProjectSettings">
<option name="detectVcsMappingsAutomatically" value="false" />
</component>
</project>

Binary file not shown.

@ -0,0 +1,33 @@
GCC RUNTIME LIBRARY EXCEPTION
Version 3.1, 31 March 2009
General information: http://www.gnu.org/licenses/gcc-exception.html
Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception.
When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception.
0. Definitions.
A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library.
"GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF.
"GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC.
"Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation.
The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors.
A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process.
1. Grant of Additional Permission.
You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules.
2. No Weakening of GCC Copyleft.
The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC.

@ -0,0 +1,2 @@
# product_Demo

Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

@ -1,47 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xky</groupId>
<artifactId>Practical</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Practical</name>
<url>https://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>21</java.version>
</properties>
<dependencies>
<!-- mysql驱动坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.38</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,28 +0,0 @@
package com.xky;
import com.xky.pojo.User;
import com.xky.ui.module.login.Autoregister;
import com.xky.ui.module.login.Login;
import javax.swing.*;
import java.sql.SQLException;
public class Application
{
// 主方法,启动登录界面
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(Login::new); // 在事件调度线程中创建登录界面
//自动注册管理员账号
try {
Autoregister.adminRegister();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

@ -1,27 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customers {
private Integer customerId;//客户ID
private String customerCode;//客户编码
private String customerName;//客户名称
private String contactPerson;//联系人
private String phone;//联系电话
private String email;//电子邮箱
private String address;//联系地址
private String creditLimit;//信用额度
private Boolean isActive;//是否有效(1:是,0:否)
private LocalDateTime createdTime;//创建时间
private LocalDateTime updatedTime;//更新时间
}

@ -1,27 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Inventory {
private Integer inventoryId;//库存记录ID
private Integer productId ;//商品ID
private Integer warehouseId;//仓库ID
private Integer quantity;//当前库存数量
private Integer allocatedQuantity;//已分配数量
private String locationCode;//库位编码
private String batchNumber;//批次号
private LocalDateTime expiryDate;//过期日期
private LocalDateTime lastStockUpdate;//最后库存更新时间
private LocalDateTime createdTime;//创建时间
private LocalDateTime updatedTime;//更新时间
}

@ -1,22 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductCategories {
private Integer categoryId ;//分类ID
private String categoryName;//分类名称
private Integer parentId;//父分类ID
private String isActive;//是否启用(1:启用,0:禁用)
private LocalDateTime createdTime;//创建时间
private LocalDateTime updatedTime;//更新时间
}

@ -1,27 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Products {
private Integer productId;//商品ID
private String productCode;//商品编码
private String productName;//商品名称
private Integer categoryId ;//所属分类ID
private String unitOfMeasure;//计量单位
private Integer minStockLevel;//最低库存水平
private String isActive;//是否启用(1:启用,0:禁用)
private LocalDateTime createdTime;//创建时间
private LocalDateTime updatedTime;//更新时间
private Integer supplierId; // 供应商ID
}

@ -1,38 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SalesOrders {
private Integer orderId; // 订单ID
private String orderNumber; // 订单编号
private Integer customerId; // 客户ID
private LocalDateTime orderDate; // 下单时间
private LocalDate expectedShipDate; // 预计发货日期
private LocalDate actualShipDate; // 实际发货日期
private Integer warehouseId; // 发货仓库ID
private String orderStatus; // 订单状态
private String paymentStatus; // 支付状态
private String paymentMethod; // 支付方式
private BigDecimal subtotal; // 商品总额
private BigDecimal taxAmount; // 税额
private BigDecimal discountAmount; // 折扣金额
private BigDecimal shippingFee; // 运费
private BigDecimal totalAmount; // 订单总金额
private BigDecimal paidAmount; // 已付金额
private String notes; // 订单备注
private Integer createdBy; // 创建人ID
private LocalDateTime createdTime; // 创建时间
private LocalDateTime updatedTime; // 更新时间
}

@ -1,29 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SalesShipments {
private Integer shipmentId; // 发货单ID
private String shipmentNumber; // 发货单号
private Integer orderId; // 关联订单ID
private Integer warehouseId; // 发货仓库ID
private LocalDate shipmentDate; // 发货日期
private String carrier; // 承运商
private String trackingNumber; // 物流单号
private String shippingMethod; // 运输方式
private String status; // 状态
private String notes; // 备注
private LocalDateTime createdTime; // 创建时间
private LocalDateTime updatedTime; // 更新时间
}

@ -1,32 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Supplier {
private Integer supplierId; // 供应商ID
private String supplierCode;//供应商编码
private String supplierName; // 供应商名称
private String contactName; // 联系人姓名
private String contactPhone; // 联系人电话
private String contactEmail; // 联系人邮箱
private String address; // 地址
private Boolean isActive; // 是否激活
private LocalDateTime createdTime = LocalDateTime.now(); // 创建时间
private LocalDateTime updatedTime = LocalDateTime.now(); // 更新时间
@Override
public String toString() {
return supplierName;
}
}

@ -1,19 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private String username;
private String password;
private String email;
}

@ -1,23 +0,0 @@
package com.xky.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Warehouses {
private Integer warehouseId ;//仓库ID
private String warehouseCode;//仓库编码
private String warehouseName;//仓库名称
private String location ;//仓库位置
private Boolean isActive;//是否启用
private LocalDateTime createdTime;//创建时间
private LocalDateTime updatedTime;//更新时间
}

@ -1,490 +0,0 @@
package com.xky.ui.main;
import com.xky.ui.module.customersManagement.CustomersInfo;
import com.xky.ui.module.inventorManagement.InvenToryInfo;
import com.xky.ui.module.login.Login;
import com.xky.ui.module.productManagement.BasicMassageInfo;
import com.xky.ui.module.productManagement.ProductCategoryInfo;
import com.xky.ui.module.salesManagement.SalesInfo;
import com.xky.ui.module.salesManagement.SalesShipmentsInfo;
import com.xky.ui.module.supplierManagement.SupplierInfo;
import com.xky.ui.module.productManagement.select.ProductService;
import com.xky.ui.menu.MenuManager;
import lombok.Getter;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*/
@Getter
public class MainView extends JFrame {
private static JPanel leftPanel;
public static JPanel rightPanel;
private static JPanel contentPanel;
private static JLabel statusMessageLabel;
private static JLabel statusTimeLabel;
private static Timer statusTimeTimer;
public static Timer autoRefreshTimer;//定时器
private static JLabel lastRefreshTimeLabel;
private static String currentModuleName = "首页";
private static Runnable currentRefreshAction = null;
private ProductService productService;
public MainView() {
initializeFrame();
initializeServices();
initializeUI();
setVisible(true);
}
private void initializeFrame() {
setTitle("商品库存管理系统");
setSize(1440, 900);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
}
private void initializeServices() {
productService = new ProductService();
// 初始化自动刷新定时器 (每10秒刷新一次)
autoRefreshTimer = new Timer(10000, _ -> {
if (currentRefreshAction != null) {
currentRefreshAction.run();
// 检查lastRefreshTimeLabel是否已初始化
if (lastRefreshTimeLabel != null) {
updateRefreshTime();
}
updateStatusMessage(currentModuleName + "数据已自动刷新");
}
});
}
private void initializeUI() {
// 创建主内容面板
contentPanel = new JPanel(new BorderLayout());
// 初始化左侧面板
initializeLeftPanel();
// 初始化右侧面板
rightPanel = new JPanel(new BorderLayout());
rightPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); // 添加内边距
rightPanel.setBackground(new Color(245, 245, 245)); // 浅灰色背景
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setOpaque(false);
// 创建用户信息面板(右对齐)
JPanel userInfoPanel = new JPanel();
userInfoPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 0));
userInfoPanel.setOpaque(false);
userInfoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
// 创建用户信息背景面板
JPanel userBgPanel = new JPanel(new BorderLayout(5, 0));
userBgPanel.setBackground(new Color(48, 57, 82)); // 深蓝色背景,与左侧面板一致
userBgPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));
// 创建用户信息子面板
JPanel userInfoSubPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
userInfoSubPanel.setOpaque(false);
// 用户图标
JLabel userIconLabel = new JLabel();
userIconLabel.setFont(new Font("黑体", Font.PLAIN, 16));
userIconLabel.setForeground(Color.WHITE);
// 添加用户信息到子面板
userInfoSubPanel.add(userIconLabel);
// 添加子面板和按钮面板到用户背景面板
userBgPanel.add(userInfoSubPanel, BorderLayout.CENTER);
// 添加用户背景面板到用户信息面板
userInfoPanel.add(userBgPanel);
// 添加用户信息面板到顶部面板
topPanel.add(userInfoPanel, BorderLayout.EAST);
// 添加顶部面板到右侧面板
rightPanel.add(topPanel, BorderLayout.CENTER);
contentPanel.add(rightPanel, BorderLayout.CENTER);
// 添加内容面板到主窗口
add(contentPanel, BorderLayout.CENTER);
//添加顶部状态栏
topStatus();
// 添加底部状态栏
bottomStatus();
// 显示首页
BasicMassageInfo.showHomePage();
updateStatusMessage("欢迎使用商品库存管理系统");
}
// 初始化左侧面板
private void initializeLeftPanel() {
leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.setBackground(new Color(48, 57, 82)); // 深蓝色背景
leftPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // 移除内边距
// 使用一个包装面板来确保左侧面板填满高度
JPanel wrapperPanel = new JPanel(new BorderLayout());
wrapperPanel.setBackground(new Color(48, 57, 82));
wrapperPanel.add(leftPanel, BorderLayout.NORTH);
// 设置固定宽度但允许高度自适应
wrapperPanel.setPreferredSize(new Dimension(180, Integer.MAX_VALUE));
// 添加系统标题
JLabel titleLabel = new JLabel("库存管理系统");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 22)); // 增大字体
titleLabel.setForeground(Color.WHITE);
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT); // 居中对齐
titleLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 25, 0)); // 增加上下间距
leftPanel.add(titleLabel);
// 设置鼠标悬停效果
titleLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
titleLabel.setForeground(new Color(150, 200, 255));
// 添加鼠标事件监听器
titleLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 点击标题时执行的操作
dispose();
new MainView();
updateRefreshTime();
}
@Override
public void mouseEntered(MouseEvent e) {
// 鼠标悬停时改变颜色
titleLabel.setForeground(Color.YELLOW);
}
@Override
public void mouseExited(MouseEvent e) {
// 鼠标离开时恢复颜色
titleLabel.setForeground(new Color(150, 200, 255));
}
});
// 创建菜单管理器
new MenuManager(leftPanel);
// 首页按钮
JButton homeButton = createMenuButton("首页", new ImageIcon(""));
homeButton.addActionListener(e -> BasicMassageInfo.showHomePage());
leftPanel.add(homeButton);
// 分割线
JSeparator separator = new JSeparator();
separator.setMaximumSize(new Dimension(180, 1));
separator.setForeground(new Color(70, 80, 110));
leftPanel.add(separator);
// 添加菜单
addMenuItems();
// 添加一个弹性组件,使菜单项靠顶部显示
leftPanel.add(Box.createVerticalGlue());
contentPanel.add(wrapperPanel, BorderLayout.WEST);
}
/**
*
*/
private void bottomStatus() {
JPanel statusBar = new JPanel(new BorderLayout());
statusBar.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(200, 200, 200)),
BorderFactory.createEmptyBorder(5, 10, 5, 10)
));
statusBar.setBackground(new Color(240, 240, 240));
// 左侧面板 - 包含状态消息
JPanel leftStatusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
leftStatusPanel.setOpaque(false);
// 状态消息标签
statusMessageLabel = new JLabel("就绪");
statusMessageLabel.setForeground(new Color(100, 100, 100));
leftStatusPanel.add(statusMessageLabel);
// 最后刷新时间标签
lastRefreshTimeLabel = new JLabel("尚未刷新");
lastRefreshTimeLabel.setForeground(new Color(100, 100, 100));
leftStatusPanel.add(lastRefreshTimeLabel);
statusBar.add(leftStatusPanel, BorderLayout.WEST);
// 时间标签
statusTimeLabel = new JLabel();
statusTimeLabel.setForeground(new Color(100, 100, 100));
statusBar.add(statusTimeLabel, BorderLayout.EAST);
// 添加时间更新定时器
statusTimeTimer = new Timer(1000, e -> updateStatusBarTime());
statusTimeTimer.start();
updateStatusBarTime(); // 立即更新一次
add(statusBar, BorderLayout.SOUTH);
}
/**
*
*/
private void topStatus() {
JPanel topStatus = new JPanel(new BorderLayout());
topStatus.setPreferredSize(new Dimension(getWidth(), 35));
topStatus.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(200, 200, 200)),
BorderFactory.createEmptyBorder(5, 10, 5, 10)
));
topStatus.setBackground(new Color(240, 240, 240));
// 左侧系统状态信息
JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
leftPanel.setOpaque(false);
JLabel statusLabel = new JLabel("系统状态:已登录 | 登录角色admin |");
statusLabel.setFont(new Font("黑体", Font.PLAIN, 14));
statusLabel.setForeground(new Color(70, 70, 70));
leftPanel.add(statusLabel);
topStatus.add(leftPanel, BorderLayout.WEST);
// 右侧退出按钮
JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel.setOpaque(false);
JButton logoutButton = new JButton("退出系统");
logoutButton.setFont(new Font("黑体", Font.PLAIN, 14));
logoutButton.setForeground(new Color(70, 70, 70));
logoutButton.setOpaque(false);
logoutButton.setBorderPainted(false);
logoutButton.setContentAreaFilled(false);
logoutButton.setFocusPainted(false);
logoutButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
// 添加鼠标悬停效果
logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
logoutButton.setForeground(new Color(220, 0, 0));
}
public void mouseExited(java.awt.event.MouseEvent evt) {
logoutButton.setForeground(new Color(70, 70, 70));
}
});
rightPanel.add(logoutButton);
topStatus.add(rightPanel, BorderLayout.EAST);
add(topStatus, BorderLayout.NORTH);
// 点击事件
logoutButton.addActionListener(_ -> {
int i = JOptionPane.showConfirmDialog(MainView.this, "你确定要退出系统吗?", "退出提示", JOptionPane.OK_CANCEL_OPTION);
if (i == 0) {
dispose();
new Login();
}
});
}
/**
*
*/
private void updateStatusBarTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
statusTimeLabel.setText(sdf.format(new Date()));
}
/**
*
*/
public static void updateStatusMessage(String message) {
if (statusMessageLabel != null) {
statusMessageLabel.setText(message);
}
}
/**
*
*/
private static void updateRefreshTime() {
if (lastRefreshTimeLabel != null) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
lastRefreshTimeLabel.setText("最后刷新: " + sdf.format(new Date()));
}
}
/**
*
* @param moduleName
* @param refreshAction
*/
public static void registerRefreshAction(String moduleName, Runnable refreshAction) {
currentModuleName = moduleName;
currentRefreshAction = refreshAction;
// 更新刷新时间
if (lastRefreshTimeLabel != null) {
updateRefreshTime();
}
// 自动刷新始终启用
if (autoRefreshTimer != null) {
autoRefreshTimer.restart();
}
}
/**
*
*/
public static void unregisterRefreshAction() {
currentModuleName = "首页";
currentRefreshAction = null;
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
autoRefreshTimer.stop();
}
// 更新状态
if (lastRefreshTimeLabel != null) {
lastRefreshTimeLabel.setText("尚未刷新");
}
}
/**
*
* @param text
* @return
*/
public static JButton createMenuButton(String text, ImageIcon icon) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setForeground(Color.WHITE);
button.setMaximumSize(new Dimension(180, 45)); // 增加按钮高度
button.setPreferredSize(new Dimension(180, 45));
button.setAlignmentX(Component.CENTER_ALIGNMENT); // 居中对齐
button.setHorizontalTextPosition(SwingConstants.RIGHT);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
button.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 0)); // 增加左侧内边距
if (icon != null && icon.getIconWidth() > 0) {
button.setIcon(icon);
}
// 添加鼠标悬停效果
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
button.setBackground(new Color(60, 70, 100));
button.setOpaque(true);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
button.setOpaque(false);
}
});
return button;
}
private void addMenuItems() {
// 添加商品管理模块
MenuManager.addMenu("商品管理模块", new String[]{"商品基础信息", "商品分类"},
menuItem -> {
if ("商品基础信息".equals(menuItem)) {
BasicMassageInfo.showProductInfoPage();
updateStatusMessage("已加载商品基础信息");
} else if ("商品分类".equals(menuItem)) {
ProductCategoryInfo.showCategoryInfoPage();
updateStatusMessage("已加载商品分类信息");
}
}
);
// 添加库存管理模块
MenuManager.addMenu("库存管理模块", new String[]{"库存信息"},
menuItem -> {
if ("库存信息".equals(menuItem)) {
InvenToryInfo.showInventoryInfoPage();
updateStatusMessage("已加载库存信息");
}
}
);
// 恢复供应商管理模块
MenuManager.addMenu("供应商管理模块", new String[]{"供应商信息"},
menuItem -> {
if ("供应商信息".equals(menuItem)) {
SupplierInfo.showSupplierInfoPage();
updateStatusMessage("已加载供应商信息");
}
}
);
// 添加客户管理模块
MenuManager.addMenu("客户管理模块", new String[]{"客户信息"},
menuItem -> {
if ("客户信息".equals(menuItem)) {
CustomersInfo.showCustomersPage();
updateStatusMessage("已加载客户信息");
}
}
);
// 添加销售模块
MenuManager.addMenu("销售模块", new String[]{"销售订单信息", "销售发货信息"},
menuItem -> {
if ("销售订单信息".equals(menuItem)){
SalesInfo.showSalesInfoPage();
updateStatusMessage("已加载销售订单信息");
}else if ("销售发货信息".equals(menuItem)){
SalesShipmentsInfo.showSalesShipmentsPage();
updateStatusMessage("已加载销售发货信息");
}
}
);
// 添加仓库模块
MenuManager.addMenu("仓库模块", new String[]{"仓库信息"},
menuItem -> {
if ("仓库信息".equals(menuItem)) {
com.xky.ui.module.warehouseManagement.WarehouseInfo.showWarehouseInfoPage();
updateStatusMessage("已加载仓库信息");
}
}
);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MainView::new);
}
}

@ -1,250 +0,0 @@
package com.xky.ui.menu;
import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;
/**
*
*/
public class MenuManager {
private static JPanel leftPanel;
private static JPanel currentExpandedPanel;
public MenuManager(JPanel leftPanel) {
MenuManager.leftPanel = leftPanel;
}
/**
*
* @param mainMenuText
* @param subMenuTexts
* @param subMenuActions
*/
public static void addMenu(String mainMenuText, String[] subMenuTexts, Consumer<String> subMenuActions) {
// 主菜单按钮
JButton mainMenuButton = createMenuButton(mainMenuText);
// 子菜单面板
JPanel subMenuPanel = new JPanel();
subMenuPanel.setLayout(new BoxLayout(subMenuPanel, BoxLayout.Y_AXIS));
subMenuPanel.setBackground(new Color(55, 65, 95));
subMenuPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
subMenuPanel.setVisible(false);
subMenuPanel.setMaximumSize(new Dimension(180, 0));
subMenuPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
// 添加子菜单项
for (String subMenuText : subMenuTexts) {
JButton subButton = createSubMenuButton(subMenuText);
subMenuPanel.add(subButton);
// 子菜单点击事件
subButton.addActionListener(e -> {
String actionCommand = e.getActionCommand();
highlightSelectedButton(subButton);
subMenuActions.accept(actionCommand);
});
}
// 添加主菜单按钮和子菜单面板到左侧面板
leftPanel.add(mainMenuButton);
leftPanel.add(subMenuPanel);
// 添加分割线
JSeparator menuSeparator = new JSeparator();
menuSeparator.setMaximumSize(new Dimension(160, 1));
menuSeparator.setForeground(new Color(70, 80, 110));
menuSeparator.setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(menuSeparator);
// 主菜单点击事件
mainMenuButton.addActionListener(e -> {
if (currentExpandedPanel == subMenuPanel) {
collapseSubMenu(subMenuPanel);
currentExpandedPanel = null;
} else {
if (currentExpandedPanel != null) {
collapseSubMenu(currentExpandedPanel);
}
expandSubMenu(subMenuPanel);
currentExpandedPanel = subMenuPanel;
}
});
}
/**
*
*/
private static JButton createMenuButton(String text) {
// 创建一个按钮并设置其文本
JButton button = new JButton(text);
// 设置按钮的字体为微软雅黑粗体大小为16
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
// 设置按钮的前景色为白色
button.setForeground(Color.WHITE);
// 设置按钮的最大尺寸为180x45
button.setMaximumSize(new Dimension(180, 45));
// 设置按钮的首选尺寸为180x45
button.setPreferredSize(new Dimension(180, 45));
// 设置按钮在容器中的水平对齐方式为居中
button.setAlignmentX(Component.CENTER_ALIGNMENT);
// 设置按钮的文本水平位置为左侧
button.setHorizontalTextPosition(SwingConstants.LEFT);
// 设置按钮的文本水平对齐方式为左侧
button.setHorizontalAlignment(SwingConstants.LEFT);
// 设置按钮不绘制背景
button.setOpaque(false);
// 设置按钮的内容区域不填充
button.setContentAreaFilled(false);
// 设置按钮不绘制边框
button.setBorderPainted(false);
// 设置按钮不绘制焦点边框
button.setFocusPainted(false);
// 设置按钮的鼠标悬停时的光标为手型
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
// 设置按钮的边框为空边框上左下右的边距分别为8, 20, 8, 0
button.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 0));
// 添加一个右侧的箭头图标
button.setText(text + " ▼");
// 添加鼠标悬停效果
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
button.setBackground(new Color(60, 70, 100));
button.setOpaque(true);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
button.setOpaque(false);
}
});
return button;
}
/**
*
*/
private static JButton createSubMenuButton(String text) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
button.setForeground(new Color(220, 220, 220));
button.setMaximumSize(new Dimension(180, 35));
button.setPreferredSize(new Dimension(180, 35));
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.setHorizontalTextPosition(SwingConstants.LEFT);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setOpaque(false); // 使按钮背景透明
button.setContentAreaFilled(false); // 禁用内容区域自动填充
button.setBorderPainted(false); // 不绘制按钮边框
button.setFocusPainted(false); // 不显示焦点状态的高亮效果
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
button.setBorder(BorderFactory.createEmptyBorder(5, 30, 5, 0));
button.setActionCommand(text);
// 添加鼠标悬停效果
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
if (!button.isSelected()) {
button.setBackground(new Color(70, 80, 110));
button.setOpaque(true);
}
}
public void mouseExited(java.awt.event.MouseEvent evt) {
if (!button.isSelected()) {
button.setOpaque(false);
}
}
});
return button;
}
/**
*
* @param selectedButton
*/
private static void highlightSelectedButton(JButton selectedButton) {
// 遍历所有子菜单按钮,重置样式
// 遍历左侧面板中的所有组件
for (Component component : leftPanel.getComponents()) {
// 检查组件是否为 JPanel 类型
if (component instanceof JPanel) {
JPanel panel = (JPanel) component;
// 遍历 JPanel 中的所有子组件
for (Component subComp : panel.getComponents()) {
// 检查子组件是否为 JButton 类型
if (subComp instanceof JButton) {
JButton button = (JButton) subComp;
// 设置按钮背景为透明
button.setBackground(null);
// 使按钮不透明
button.setOpaque(false);
// 取消按钮选中状态
button.setSelected(false);
// 设置按钮前景色为浅灰色
button.setForeground(new Color(220, 220, 220));
}
}
}
}
// 设置选中按钮的样式
selectedButton.setBackground(new Color(41, 128, 185));
selectedButton.setOpaque(true);
// 设置选中的按钮为选中状态
selectedButton.setSelected(true);
selectedButton.setForeground(Color.WHITE);
}
/**
*
* @param subMenuPanel
*/
private static void expandSubMenu(JPanel subMenuPanel) {
subMenuPanel.setVisible(true);
int height = subMenuPanel.getComponentCount() * 35;
subMenuPanel.setMaximumSize(new Dimension(180, height));
int index = leftPanel.getComponentZOrder(subMenuPanel) - 1;
if (index >= 0 && leftPanel.getComponent(index) instanceof JButton) {
JButton mainButton = (JButton) leftPanel.getComponent(index);
String text = mainButton.getText().replace("▼", "▲");
mainButton.setText(text);
// 设置展开菜单的背景色
mainButton.setBackground(new Color(60, 70, 100));
mainButton.setOpaque(true);
}
leftPanel.revalidate();
leftPanel.repaint();
}
/**
*
* @param subMenuPanel
*/
private static void collapseSubMenu(JPanel subMenuPanel) {
subMenuPanel.setVisible(false);
subMenuPanel.setMaximumSize(new Dimension(180, 0));
int index = leftPanel.getComponentZOrder(subMenuPanel) - 1;
if (index >= 0 && leftPanel.getComponent(index) instanceof JButton) {
JButton mainButton = (JButton) leftPanel.getComponent(index);
String text = mainButton.getText().replace("▲", "▼");
mainButton.setText(text);
// 重置主菜单按钮的背景
mainButton.setOpaque(false);
}
leftPanel.revalidate();
leftPanel.repaint();
}
}

@ -1,154 +0,0 @@
package com.xky.ui.module.customersManagement;
import com.xky.pojo.Customers;
import com.xky.ui.main.MainView;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
*
*
*/
public class CustomersInfo {
private static JTable customersTable;
private static final String MODULE_NAME = "客户信息";
/**
*
*/
public static void showCustomersPage() {
try {
// 创建客户信息面板
JPanel customersInfoPanel = CustomersMassage.createCustomersPanel(CustomersInfo::refreshCustomersData);
// 获取表格组件
initializeTable(customersInfoPanel);
// 更新右侧面板
updateMainPanel(customersInfoPanel);
// 立即刷新一次
refreshCustomersData();
// 更新状态消息
MainView.updateStatusMessage(MODULE_NAME + "页面已加载");
} catch (Exception e) {
handleException(e, "加载" + MODULE_NAME + "页面失败");
}
}
/**
*
* @param panel
* @throws IllegalStateException
*/
private static void initializeTable(JPanel panel) throws IllegalStateException {
// 尝试通过索引获取JScrollPane
try {
if (panel.getComponentCount() >= 5) {
Component comp = panel.getComponent(4);
if (comp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) comp;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
customersTable = (JTable) viewComponent;
return;
}
}
}
// 如果上面的方法失败,尝试遍历所有组件查找表格
for (Component comp : panel.getComponents()) {
if (comp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) comp;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
customersTable = (JTable) viewComponent;
return;
}
}
}
throw new IllegalStateException("无法找到表格组件");
} catch (Exception e) {
throw new IllegalStateException("初始化表格失败: " + e.getMessage(), e);
}
}
/**
*
* @param panel
*/
private static void updateMainPanel(JPanel panel) {
MainView.rightPanel.removeAll();
MainView.rightPanel.add(panel, BorderLayout.CENTER);
MainView.rightPanel.revalidate();
MainView.rightPanel.repaint();
// 注册刷新操作
MainView.registerRefreshAction(MODULE_NAME, CustomersInfo::refreshCustomersData);
}
/**
*
*/
static void refreshCustomersData() {
// 显示加载指示器
MainView.updateStatusMessage("正在加载" + MODULE_NAME + "数据...");
new SwingWorker<List<Customers>, Void>() {
@Override
protected List<Customers> doInBackground() {
validateTable();
DefaultTableModel model = (DefaultTableModel) customersTable.getModel();
model.setRowCount(0);
// 获取所有客户数据
return SelectCustomers.selectAllCustomers();
}
@Override
protected void done() {
try {
List<Customers> customersList = get();
if (customersTable != null) {
CustomersMassage.updateTableData(customersTable, customersList);
MainView.rightPanel.repaint();
MainView.updateStatusMessage("已加载 " + customersList.size() + " 条" + MODULE_NAME + "数据");
}
} catch (InterruptedException | ExecutionException e) {
handleException(e, "刷新失败");
}
}
}.execute();
}
/**
*
* @throws IllegalStateException
*/
private static void validateTable() throws IllegalStateException {
if (customersTable == null) {
throw new IllegalStateException("表格未初始化");
}
}
/**
*
* @param e
* @param message
*/
private static void handleException(Exception e, String message) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
message + ": " + e.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
MainView.updateStatusMessage(MODULE_NAME + "数据加载失败");
}
}

@ -1,451 +0,0 @@
package com.xky.ui.module.customersManagement;
import com.xky.pojo.Customers;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import com.xky.ui.module.customersManagement.add.AddCustomers;
import com.xky.ui.module.customersManagement.delete.DeleteCustomer;
import com.xky.ui.module.customersManagement.update.UpdateCustomer;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import static com.xky.ui.main.MainView.*;
/**
* UI
*
*/
public class CustomersMassage {
private static JTable table;
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
// 定义字体常量
private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 24);
private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 16);
private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
/**
*
* @param refreshAction
* @return
*/
public static JPanel createCustomersPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("客户基本信息");
titleLabel.setFont(TITLE_FONT);
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createCustomersTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
new AddCustomers();
if (refreshAction != null) {
refreshAction.run();
}
});
deleteButton.addActionListener(e -> {
new DeleteCustomer();
if (refreshAction != null) {
refreshAction.run();
}
});
updateButton.addActionListener(e -> {
new UpdateCustomer();
if (refreshAction != null) {
refreshAction.run();
}
});
queryButton.addActionListener(e -> {
// 显示查询对话框
showSearchDialog();
});
refreshButton.addActionListener(e -> {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
if (refreshAction != null) {
refreshAction.run();
// 重新注册刷新操作
registerRefreshAction("客户信息", refreshAction);
updateStatusMessage("客户数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(BUTTON_FONT);
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setPreferredSize(new Dimension(100, 35));
return button;
}
/**
*
* @return
*/
public static JScrollPane createCustomersTable() {
String[] title = {"客户ID", "客户编码", "客户名称", "联系人", "联系电话", "电子邮箱", "联系地址", "信用额度", "是否有效","创建时间", "更新时间"};
DefaultTableModel model = new DefaultTableModel(title, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
table = new JTable(model);
table.setRowHeight(30);
table.setFont(TABLE_CELL_FONT);
table.getTableHeader().setFont(TABLE_HEADER_FONT);
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid(true);
table.setOpaque(false);
table.setGridColor(new Color(230, 230, 230));
// 设置表格排序
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
table.setRowSorter(sorter);
// 设置表格列宽
int[] columnWidths = {60, 80, 80, 100, 100, 120, 100, 80, 60, 150, 150};
for (int i = 0; i < columnWidths.length; i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
}
// 创建美化的滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param customersList
*/
public static void updateTableData(JTable table, List<Customers> customersList) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0); // 清空原有数据
if (customersList == null || customersList.isEmpty()) {
return;
}
for (Customers customers : customersList) {
// 格式化日期时间
String createdTime = customers.getCreatedTime() != null ? customers.getCreatedTime().format(FORMATTER) : "";
String updatedTime = customers.getUpdatedTime() != null ? customers.getUpdatedTime().format(FORMATTER) : "";
String isActiveStr = customers.getIsActive() != null && customers.getIsActive() ? "是" : "否";
Object[] rowData = {
customers.getCustomerId(),
customers.getCustomerCode(),
customers.getCustomerName(),
customers.getContactPerson(),
customers.getPhone(),
customers.getEmail(),
customers.getAddress(),
customers.getCreditLimit(),
isActiveStr,
createdTime,
updatedTime
};
model.addRow(rowData);
}
model.fireTableDataChanged(); // 触发表格刷新
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询客户", true);
searchDialog.setSize(830, 450);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
searchDialog.getContentPane().setBackground(SECONDARY_COLOR);
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
topPanel.setBackground(SECONDARY_COLOR);
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.setBackground(SECONDARY_COLOR);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按客户ID查询", true);
JRadioButton keywordRadio = new JRadioButton("关键字查询");
idRadio.setFont(BUTTON_FONT);
keywordRadio.setFont(BUTTON_FONT);
idRadio.setBackground(SECONDARY_COLOR);
keywordRadio.setBackground(SECONDARY_COLOR);
buttonGroup.add(idRadio);
buttonGroup.add(keywordRadio);
radioPanel.add(idRadio);
radioPanel.add(keywordRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
searchPanel.setBackground(SECONDARY_COLOR);
JLabel searchLabel = new JLabel("查询条件: ");
searchLabel.setFont(BUTTON_FONT);
searchLabel.setForeground(PRIMARY_COLOR);
JTextField searchField = new JTextField(20);
searchField.setFont(TABLE_CELL_FONT);
searchField.setPreferredSize(new Dimension(200, 30));
JButton searchButton = createStyledButton("搜索", BUTTON_COLOR);
JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
searchFieldPanel.setBackground(SECONDARY_COLOR);
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 客户编码/ 客户名称/ 联系人/ 联系电话/ 电子邮箱/ 联系地址/ 信用额度/ 是否有效");
tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"客户ID", "客户编码", "客户名称", "联系人", "联系电话", "电子邮箱", "联系地址", "信用额度", "是否有效","创建时间", "更新时间"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(TABLE_CELL_FONT);
resultTable.getTableHeader().setFont(TABLE_HEADER_FONT);
resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
resultTable.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
resultTable.getTableHeader().setOpaque(true);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
scrollPane.getViewport().setBackground(Color.WHITE);
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(e -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<Customers> resultList = new ArrayList<>();
try {
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
List<Customers> result = SelectCustomers.selectCustomersById(id);
if (result != null && !result.isEmpty()) {
resultList.addAll(result);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (keywordRadio.isSelected()) {
// 获取关键字搜索结果
List<Customers> customers = SelectCustomers.searchCustomersByKeyword(searchText);
if (customers != null && !customers.isEmpty()) {
resultList.addAll(customers);
}
}
// 更新表格数据
tableModel.setRowCount(0);
if (!resultList.isEmpty()) {
for (Customers customer : resultList) {
String createdTimeStr = customer.getCreatedTime() != null ?
customer.getCreatedTime().format(FORMATTER) : "";
String updatedTimeStr = customer.getUpdatedTime() != null ?
customer.getUpdatedTime().format(FORMATTER) : "";
String isActiveStr = customer.getIsActive() != null && customer.getIsActive() ? "是" : "否";
tableModel.addRow(new Object[]{
customer.getCustomerId(),
customer.getCustomerCode(),
customer.getCustomerName(),
customer.getContactPerson(),
customer.getPhone(),
customer.getEmail(),
customer.getAddress(),
customer.getCreditLimit(),
isActiveStr,
createdTimeStr,
updatedTimeStr
});
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int customerId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的客户数据
List<Customers> customersList = SelectCustomers.selectCustomersById(customerId);
if (customersList != null && !customersList.isEmpty()) {
// 清空主表格并只显示选中的客户
updateTableData(table, customersList);
// 更新状态消息
updateStatusMessage("已选择客户: " + customersList.get(0).getCustomerName());
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
}

@ -1,390 +0,0 @@
package com.xky.ui.module.customersManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.sql.*;
public class AddCustomers extends JFrame {
private JPanel jPanel1, jPanel2, jPanel3;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
public AddCustomers() {
setTitle("添加客户信息");
setSize(520, 750);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
private void init() {
setLayout(new BorderLayout());
// 顶部标题面板 - 添加渐变背景
jPanel2 = new JPanel(new GridBagLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建渐变色背景
GradientPaint gradient = new GradientPaint(
0, 0, new Color(48, 57, 82),
getWidth(), getHeight(), new Color(38, 47, 72)
);
g2d.setPaint(gradient);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
};
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
JLabel titleLabel = new JLabel("添加客户信息");
titleLabel.setFont(new Font("楷体", Font.BOLD, 30));
titleLabel.setForeground(Color.WHITE);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(20, 0, 20, 0);
jPanel2.add(titleLabel, gbc);
add(jPanel2, BorderLayout.NORTH);
// 主输入面板 - 添加圆角和阴影
jPanel1 = new JPanel(new GridBagLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 绘制圆角背景
int cornerRadius = 15;
g2d.setColor(getBackground());
g2d.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), cornerRadius, cornerRadius));
// 添加轻微阴影效果
g2d.setColor(new Color(0, 0, 0, 20));
for (int i = 0; i < 3; i++) {
g2d.drawRoundRect(i, i, getWidth() - 2*i - 1, getHeight() - 2*i - 1, cornerRadius, cornerRadius);
}
g2d.dispose();
}
};
JLabel[] labels = new JLabel[]{
new JLabel("客户编码 *"),
new JLabel("客户名称 *"),
new JLabel("联系人 *"),
new JLabel("联系电话 *"),
new JLabel("电子邮箱 *"),
new JLabel("联系地址 *"),
new JLabel("信用额度 *"),
new JLabel("是否有效 *"),
};
textFields = new JTextField[7]; // 减少一个,因为最后一个是下拉框
Font font = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i + 1;
gbc.insets = new Insets(10, 20, 10, 10);
labels[i].setFont(font);
jPanel1.add(labels[i], gbc);
if (i < 7) {
textFields[i] = new JTextField(20);
textFields[i].setFont(font);
textFields[i].setPreferredSize(new Dimension(200, 35));
// 添加圆角边框
textFields[i].setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(200, 200, 200)),
BorderFactory.createEmptyBorder(5, 10, 5, 10)
));
gbc.gridx = 1;
jPanel1.add(textFields[i], gbc);
} else {
// 为"是否有效"创建下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(font);
isActiveComboBox.setPreferredSize(new Dimension(200, 35));
gbc.gridx = 1;
jPanel1.add(isActiveComboBox, gbc);
}
}
// 添加字段说明标签
JLabel noteLabel = new JLabel("<html><body style='width: 350px'>" +
"<p style='color: #666666;'>注意:带 * 的字段为必填项</p>" +
"</body></html>");
noteLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
gbc.gridx = 0;
gbc.gridy = labels.length+1;
gbc.gridwidth = 2;
gbc.insets = new Insets(20, 20, 10, 10);
jPanel1.add(noteLabel, gbc);
// 添加边框和背景色
jPanel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
jPanel1.setBackground(new Color(245, 245, 245));
add(jPanel1, BorderLayout.CENTER);
// 底部按钮面板
jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 20));
JButton submitButton = createStyledButton("提交", new Color(41, 128, 185));
submitButton.setPreferredSize(new Dimension(120, 40));
JButton resetButton = createStyledButton("重置", new Color(180, 180, 180));
resetButton.setPreferredSize(new Dimension(120, 40));
jPanel3.add(submitButton);
jPanel3.add(resetButton);
jPanel3.setBackground(new Color(240, 240, 240));
add(jPanel3, BorderLayout.SOUTH);
// 提交按钮事件
submitButton.addActionListener(e -> {
try {
// 获取并验证输入
String customerCode = textFields[0].getText().trim();
String customerName = textFields[1].getText().trim();
String contactPerson = textFields[2].getText().trim();
String contactPhone = textFields[3].getText().trim();
String email = textFields[4].getText().trim();
String address = textFields[5].getText().trim();
Double creditLimit = parseDoubleField(textFields[6].getText().trim(), "信用额度");
Boolean isActive = isActiveComboBox.getSelectedItem().equals("是");
// 输入验证
if (!validateInputs(customerCode, customerName, contactPerson,
contactPhone, email, address, creditLimit)) {
return;
}
// 添加客户记录
if (addCustomer(customerCode, customerName, contactPerson,
contactPhone, email, address, creditLimit, isActive)) {
JOptionPane.showMessageDialog(this, "客户信息添加成功!",
"成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "客户信息添加失败!",
"错误", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
// 重置按钮事件
resetButton.addActionListener(_ -> {
for (JTextField field : textFields) {
field.setText("");
}
isActiveComboBox.setSelectedIndex(0);
});
}
private JButton createStyledButton(String text, Color color) {
JButton button = new JButton(text) {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建渐变背景
GradientPaint gradient = new GradientPaint(
0, 0, color,
0, getHeight(), color.darker()
);
g2d.setPaint(gradient);
// 绘制圆角矩形
g2d.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12));
g2d.dispose();
super.paintComponent(g);
}
};
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setForeground(Color.WHITE);
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
// 添加鼠标悬停效果
button.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
if (text.equals("提交")) {
button.setForeground(new Color(220, 255, 255));
} else {
button.setForeground(new Color(240, 240, 240));
}
}
public void mouseExited(MouseEvent evt) {
button.setForeground(Color.WHITE);
}
});
return button;
}
private Double parseDoubleField(String text, String fieldName) throws NumberFormatException {
if (text.isEmpty()) {
return 0.0; // 允许为空默认为0
}
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
throw new NumberFormatException(fieldName + "必须是有效的数字");
}
}
private boolean validateInputs(String customerCode,
String customerName, String contactPerson,
String contactPhone, String email,
String address, Double creditLimit) {
if (customerCode.isEmpty()) {
showValidationError("客户编码不能为空");
return false;
}
if (customerName.isEmpty()) {
showValidationError("客户名称不能为空");
return false;
}
if (contactPerson.isEmpty()) {
showValidationError("联系人不能为空");
return false;
}
if (contactPhone.isEmpty()) {
showValidationError("联系电话不能为空");
return false;
}
// 简单的电子邮箱格式验证
String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
if (email.matches(EMAIL_REGEX)) {
showValidationError("电子邮箱格式不正确");
return false;
}
// 检查客户编码是否已存在
if (isCustomerCodeExists(customerCode)) {
showValidationError("客户编码已存在,请使用其他编码");
return false;
}
return true;
}
private boolean isCustomerCodeExists(String customerCode) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
String sql = "SELECT COUNT(*) FROM customers WHERE customer_code = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, customerCode);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return false;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入验证错误", JOptionPane.WARNING_MESSAGE);
}
private boolean addCustomer(String customerCode,
String customerName, String contactPerson,
String contactPhone, String email,
String address, Double creditLimit, Boolean isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
connection.setAutoCommit(false);
String sql = "INSERT INTO customers(customer_code, customer_name, " +
"contact_person, phone, email, address, credit_limit, " +
"is_active, created_time, updated_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, customerCode);
preparedStatement.setString(2, customerName);
preparedStatement.setString(3, contactPerson);
preparedStatement.setString(4, contactPhone);
preparedStatement.setString(5, email);
preparedStatement.setString(6, address);
preparedStatement.setDouble(7, creditLimit);
preparedStatement.setBoolean(8, isActive);
int affectedRows = preparedStatement.executeUpdate();
connection.commit();
if (affectedRows > 0) {
System.out.println("受影响的行数为" + affectedRows + ",添加成功!");
return true;
} else {
System.out.println("受影响的行数为" + affectedRows + ",添加失败!");
return false;
}
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(),
"数据库错误", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
new AddCustomers();
});
}
}

@ -1,296 +0,0 @@
package com.xky.ui.module.customersManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*/
public class DeleteCustomer extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteCustomer() {
setTitle("删除客户信息");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init() {
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的客户ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有客户的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有客户");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个客户删除按钮事件
jButton.addActionListener(e -> {
String idText = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入你要删除的客户ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
Integer id = Integer.valueOf(idText);
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该客户信息吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
if (customerExists(id)) {
deleteCustomer(id);
JOptionPane.showMessageDialog(null, "该客户信息删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该客户ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有客户按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有客户信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有客户的操作
if (deleteAllCustomers()) {
JOptionPane.showMessageDialog(
null,
"所有客户信息已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有客户信息失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
* ID
* @param id ID
* @return
*/
private boolean customerExists(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM customers WHERE customer_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param id ID
* @return
*/
public boolean deleteCustomer(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM customers WHERE customer_id = ?");
preparedStatement.setInt(1, id);
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("影响行数为" + i + "删除成功!");
return true;
} else {
System.out.println("影响行数为" + i + "删除失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllCustomers() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM customers");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("删除了" + rowsAffected + "条客户记录");
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteCustomer::new);
}
}

@ -1,216 +0,0 @@
package com.xky.ui.module.customersManagement.select;
import com.xky.pojo.Customers;
import com.xky.utils.DBUtils;
import lombok.Getter;
import lombok.Setter;
import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Setter
@Getter
public class SelectCustomers {
/**
*
* @return
*/
public static List<Customers> selectAllCustomers() {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Customers> customersList = new ArrayList<>();
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM customers");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Customers customers = new Customers();
customers.setCustomerId(resultSet.getInt("customer_id"));
customers.setCustomerCode(resultSet.getString("customer_code"));
customers.setCustomerName(resultSet.getString("customer_name"));
customers.setContactPerson(resultSet.getString("contact_person"));
customers.setPhone(resultSet.getString("phone"));
customers.setEmail(resultSet.getString("email"));
customers.setAddress(resultSet.getString("address"));
customers.setCreditLimit(resultSet.getString("credit_limit"));
customers.setIsActive(resultSet.getBoolean("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
customers.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
customers.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
customersList.add(customers);
}
return customersList;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
* ID
* @param id ID
* @return
*/
public static Boolean checkCustomerExistsById(Integer id) {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM customers WHERE customer_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return false;
}
/**
* ID
* @param id ID
* @return
*/
public static List<Customers> selectCustomersById(Integer id) {
Connection connection;
PreparedStatement preparedStatement = null;//用于执行预编译的 SQL 语句。
ResultSet resultSet = null;
List<Customers> customersList = new ArrayList<>();
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM customers WHERE customer_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Customers customers = new Customers();
customers.setCustomerId(resultSet.getInt("customer_id"));
customers.setCustomerCode(resultSet.getString("customer_code"));
customers.setCustomerName(resultSet.getString("customer_name"));
customers.setContactPerson(resultSet.getString("contact_person"));
customers.setPhone(resultSet.getString("phone"));
customers.setEmail(resultSet.getString("email"));
customers.setAddress(resultSet.getString("address"));
customers.setCreditLimit(resultSet.getString("credit_limit"));
customers.setIsActive(resultSet.getBoolean("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
customers.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
customers.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
customersList.add(customers);
}
return customersList;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param keyword
* @return
*/
public static List<Customers> searchCustomersByKeyword(String keyword) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Customers> customersList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
// 使用LIKE进行模糊查询搜索所有相关字段
preparedStatement = connection.prepareStatement(
"SELECT * FROM customers WHERE customer_id = ? " +
"OR customer_code LIKE ? " +
"OR customer_name LIKE ? " +
"OR contact_person LIKE ? " +
"OR phone LIKE ? " +
"OR email LIKE ? " +
"OR address LIKE ? " +
"OR credit_limit LIKE ? " +
"OR CAST(is_active AS CHAR) LIKE ?"
);
String searchPattern = "%" + keyword + "%";
// Try to parse the keyword as an integer for customer_id
try {
int id = Integer.parseInt(keyword);
preparedStatement.setInt(1, id);
} catch (NumberFormatException e) {
// If not a valid integer, set it to -1 (which won't match any ID)
preparedStatement.setInt(1, -1);
}
preparedStatement.setString(2, searchPattern);
preparedStatement.setString(3, searchPattern);
preparedStatement.setString(4, searchPattern);
preparedStatement.setString(5, searchPattern);
preparedStatement.setString(6, searchPattern);
preparedStatement.setString(7, searchPattern);
preparedStatement.setString(8, searchPattern);
preparedStatement.setString(9, searchPattern);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Customers customers = new Customers();
customers.setCustomerId(resultSet.getInt("customer_id"));
customers.setCustomerCode(resultSet.getString("customer_code"));
customers.setCustomerName(resultSet.getString("customer_name"));
customers.setContactPerson(resultSet.getString("contact_person"));
customers.setPhone(resultSet.getString("phone"));
customers.setEmail(resultSet.getString("email"));
customers.setAddress(resultSet.getString("address"));
customers.setCreditLimit(resultSet.getString("credit_limit"));
customers.setIsActive(resultSet.getBoolean("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
customers.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
customers.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
customersList.add(customers);
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "搜索时发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return customersList;
}
}

@ -1,471 +0,0 @@
package com.xky.ui.module.customersManagement.update;
import com.xky.pojo.Customers;
import com.xky.utils.DBUtils;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
/**
*
*/
public class UpdateCustomer extends JFrame {
private JPanel mainPanel, formPanel, buttonPanel;
private JTextField idField, codeField, nameField, contactPersonField,
phoneField, emailField, addressField, creditLimitField;
private JCheckBox isActiveCheckBox;
private JButton searchButton, updateButton, cancelButton;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color CANCEL_BUTTON_COLOR = new Color(231, 76, 60);
// 邮箱验证正则表达式
private static final String EMAIL_REGEX =
"^(?![._-])(?!.*[._-]$)(?!.*\\.\\.)[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@(?![-])(?!.*-$)[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}(?:\\.[a-zA-Z]{2,})?$";
public UpdateCustomer() {
setTitle("修改客户信息");
setSize(550, 800);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
init();
setVisible(true);
}
private void init() {
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 顶部标题面板
JPanel headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("修改客户信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入客户ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.setPreferredSize(new Dimension(100,30));
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
// 中部搜索和表单面板
JPanel centerPanel = new JPanel(new BorderLayout(0, 15));
centerPanel.setOpaque(false);
// 搜索面板
JPanel searchCard = createRoundedPanel();
searchCard.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
JLabel idLabel = new JLabel("客户ID");
idLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
idLabel.setForeground(PRIMARY_COLOR);
searchCard.add(idLabel);
idField = new JTextField(15);
idField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
idField.setPreferredSize(new Dimension(200, 35));
searchCard.add(idField);
searchButton = new JButton("查询");
styleButton(searchButton, QUERY_BUTTON_COLOR);
searchButton.setPreferredSize(new Dimension(100, 35));
searchCard.add(searchButton);
centerPanel.add(searchCard, BorderLayout.NORTH);
// 表单面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
// 创建表单字段
createFormFields(formPanel);
formCard.add(formPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
centerPanel.add(formCard, BorderLayout.CENTER);
mainPanel.add(centerPanel, BorderLayout.CENTER);
// 底部按钮面板
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
updateButton = new JButton("更新");
styleButton(updateButton, BUTTON_COLOR);
cancelButton = new JButton("取消");
styleButton(cancelButton, CANCEL_BUTTON_COLOR);
buttonPanel.add(updateButton);
buttonPanel.add(cancelButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
// 禁用表单字段,直到用户搜索到客户
setFormFieldsEnabled(false);
// 添加事件监听器
addEventListeners();
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
/**
*
*/
private void createFormFields(JPanel panel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
JLabel[] labels = new JLabel[]{
new JLabel("客户编码 *"),
new JLabel("客户名称 *"),
new JLabel("联系人 *"),
new JLabel("联系电话 *"),
new JLabel("电子邮箱 *"),
new JLabel("联系地址 *"),
new JLabel("信用额度 *"),
new JLabel("是否有效")
};
// 创建文本字段
codeField = new JTextField(20);
nameField = new JTextField(20);
contactPersonField = new JTextField(20);
phoneField = new JTextField(20);
emailField = new JTextField(20);
addressField = new JTextField(20);
creditLimitField = new JTextField(20);
isActiveCheckBox = new JCheckBox();
isActiveCheckBox.setOpaque(false);
JTextField[] fields = {codeField, nameField, contactPersonField, phoneField, emailField, addressField, creditLimitField};
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.weightx = 0.3;
labels[i].setFont(labelFont);
labels[i].setForeground(PRIMARY_COLOR);
panel.add(labels[i], gbc);
gbc.gridx = 1;
gbc.weightx = 0.7;
if (i < 7) {
fields[i].setFont(fieldFont);
fields[i].setPreferredSize(new Dimension(250, 35));
panel.add(fields[i], gbc);
} else {
panel.add(isActiveCheckBox, gbc);
}
}
}
/**
*
*/
private void setFormFieldsEnabled(boolean enabled) {
codeField.setEnabled(enabled);
nameField.setEnabled(enabled);
contactPersonField.setEnabled(enabled);
phoneField.setEnabled(enabled);
emailField.setEnabled(enabled);
addressField.setEnabled(enabled);
creditLimitField.setEnabled(enabled);
isActiveCheckBox.setEnabled(enabled);
updateButton.setEnabled(enabled);
}
/**
*
*/
private void addEventListeners() {
// 查询按钮事件
searchButton.addActionListener(e -> {
try {
String idText = idField.getText().trim();
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入客户ID", "输入错误", JOptionPane.WARNING_MESSAGE);
return;
}
int customerId = Integer.parseInt(idText);
List<Customers> customersList = SelectCustomers.selectCustomersById(customerId);
if (customersList != null && !customersList.isEmpty()) {
Customers customer = customersList.get(0);
// 填充表单字段
codeField.setText(customer.getCustomerCode());
nameField.setText(customer.getCustomerName());
contactPersonField.setText(customer.getContactPerson());
phoneField.setText(customer.getPhone());
emailField.setText(customer.getEmail());
addressField.setText(customer.getAddress());
creditLimitField.setText(customer.getCreditLimit());
isActiveCheckBox.setSelected(customer.getIsActive());
// 启用表单字段
setFormFieldsEnabled(true);
} else {
JOptionPane.showMessageDialog(this, "未找到ID为 " + customerId + " 的客户记录",
"查找失败", JOptionPane.ERROR_MESSAGE);
// 清空并禁用表单字段
clearFormFields();
setFormFieldsEnabled(false);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
}
});
// 更新按钮事件
updateButton.addActionListener(e -> {
try {
int customerId = Integer.parseInt(idField.getText().trim());
String customerCode = codeField.getText().trim();
String customerName = nameField.getText().trim();
String contactPerson = contactPersonField.getText().trim();
String phone = phoneField.getText().trim();
String email = emailField.getText().trim();
String address = addressField.getText().trim();
String creditLimit = creditLimitField.getText().trim();
boolean isActive = isActiveCheckBox.isSelected();
// 验证输入
if (!validateInputs(customerCode, customerName, contactPerson, phone, email, address, creditLimit)) {
return;
}
// 更新客户信息
if (updateCustomer(customerId, customerCode, customerName, contactPerson, phone, email, address, creditLimit, isActive)) {
JOptionPane.showMessageDialog(this, "客户信息更新成功", "更新成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "客户信息更新失败", "更新失败", JOptionPane.ERROR_MESSAGE);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "客户ID格式错误", "输入错误", JOptionPane.WARNING_MESSAGE);
}
});
// 取消按钮事件
cancelButton.addActionListener(e -> {
dispose();
});
// 为ID文本框添加回车键事件
idField.addActionListener(e -> searchButton.doClick());
}
private void clearFormFields() {
codeField.setText("");
nameField.setText("");
contactPersonField.setText("");
phoneField.setText("");
emailField.setText("");
addressField.setText("");
creditLimitField.setText("");
isActiveCheckBox.setSelected(false);
}
private boolean validateInputs(String customerCode, String customerName, String contactPerson,
String phone, String email, String address, String creditLimit) {
// 1. 校验客户编码
if (customerCode.isEmpty()) {
showValidationError("客户编码不能为空");
return false;
}
// 2. 校验客户名称
if (customerName.isEmpty()) {
showValidationError("客户名称不能为空");
return false;
}
// 3. 校验联系人
if (contactPerson.isEmpty()) {
showValidationError("联系人不能为空");
return false;
}
// 4. 校验联系电话
if (phone.isEmpty()) {
showValidationError("联系电话不能为空");
return false;
}
// 5. 校验电子邮箱
if (email.isEmpty()) {
showValidationError("电子邮箱不能为空");
return false;
}
// 验证邮箱格式
if (email.matches(EMAIL_REGEX)) {
showValidationError("电子邮箱格式不正确");
return false;
}
// 6. 校验联系地址
if (address.isEmpty()) {
showValidationError("联系地址不能为空");
return false;
}
// 7. 校验信用额度
if (creditLimit.isEmpty()) {
showValidationError("信用额度不能为空");
return false;
}
try {
double limit = Double.parseDouble(creditLimit);
if (limit < 0) {
showValidationError("信用额度不能为负数");
return false;
}
} catch (NumberFormatException e) {
showValidationError("信用额度必须是数字");
return false;
}
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
private boolean updateCustomer(int customerId, String customerCode, String customerName,
String contactPerson, String phone, String email,
String address, String creditLimit, boolean isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
String sql = "UPDATE customers SET customer_code=?, customer_name=?, contact_person=?, " +
"phone=?, email=?, address=?, credit_limit=?, is_active=?, updated_time=NOW() " +
"WHERE customer_id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, customerCode);
preparedStatement.setString(2, customerName);
preparedStatement.setString(3, contactPerson);
preparedStatement.setString(4, phone);
preparedStatement.setString(5, email);
preparedStatement.setString(6, address);
preparedStatement.setString(7, creditLimit);
preparedStatement.setBoolean(8, isActive);
preparedStatement.setInt(9, customerId);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateCustomer::new);
}
}

@ -1,74 +0,0 @@
package com.xky.ui.module.inventorManagement;
import com.xky.pojo.Inventory;
import com.xky.ui.main.MainView;
import com.xky.ui.module.inventorManagement.select.SelectInvenTory;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class InvenToryInfo {
private static JTable inventoryTable;
/**
*
*/
public static void showInventoryInfoPage() {
// 创建库存信息面板
JPanel inventoryInfoPanel = InvenToryMassage.createInvenToryPanel(InvenToryInfo::refreshInventoryData);
// 获取表格组件
Component[] components = ((JScrollPane)inventoryInfoPanel.getComponent(1)).getViewport().getComponents();
if (components.length > 0 && components[0] instanceof JTable) {
inventoryTable = (JTable) components[0];
}
// 更新右侧面板
MainView.rightPanel.removeAll();
MainView.rightPanel.add(inventoryInfoPanel, BorderLayout.CENTER);
MainView.rightPanel.revalidate();
MainView.rightPanel.repaint();
// 注册刷新操作
MainView.registerRefreshAction("库存信息", InvenToryInfo::refreshInventoryData);
// 立即刷新一次
refreshInventoryData();
}
/**
*
*/
static void refreshInventoryData() {
new SwingWorker<List<Inventory>, Void>() {
@Override
protected List<Inventory> doInBackground() {
DefaultTableModel model = (DefaultTableModel) inventoryTable.getModel();
model.setRowCount(0);
// 获取所有库存数据
return SelectInvenTory.selectAllInventory();
}
@Override
protected void done() {
try {
List<Inventory> inventory = get();
if (inventoryTable != null) {
InvenToryMassage.updateTableData(inventoryTable, inventory);
MainView.rightPanel.repaint();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"刷新失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
}

@ -1,488 +0,0 @@
package com.xky.ui.module.inventorManagement;
import com.xky.pojo.Inventory;
import com.xky.ui.module.inventorManagement.add.AddInvenTory;
import com.xky.ui.module.inventorManagement.delete.DeleteInvenTory;
import com.xky.ui.module.inventorManagement.select.SelectInvenTory;
import com.xky.ui.module.inventorManagement.update.UpdateInvenTory;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import static com.xky.ui.main.MainView.*;
/**
*
*/
public class InvenToryMassage {
private static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
/**
*
* @param refreshAction
* @return
*/
public static JPanel createInvenToryPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("商品库存信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createInvenToryTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
new AddInvenTory();
});
deleteButton.addActionListener(e -> {
new DeleteInvenTory();
});
updateButton.addActionListener(e -> {
new UpdateInvenTory();
});
queryButton.addActionListener(e -> {
// 显示高级查询对话框
showSearchDialog();
});
refreshButton.addActionListener(e -> {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
if (refreshAction != null) {
refreshAction.run();
// 重新注册刷新操作
registerRefreshAction("库存信息", refreshAction);
updateStatusMessage("库存数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createInvenToryTable() {
String[] title = {"库存记录ID", "商品ID", "仓库ID", "当前库存数量", "已分配数量", "库位编码", "批次号", "过期日期", "创建时间", "更新时间"};
DefaultTableModel model = new DefaultTableModel(title, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(80); // 库存记录ID
table.getColumnModel().getColumn(1).setPreferredWidth(60); // 商品ID
table.getColumnModel().getColumn(2).setPreferredWidth(60); // 仓库ID
table.getColumnModel().getColumn(3).setPreferredWidth(100); // 当前库存数量
table.getColumnModel().getColumn(4).setPreferredWidth(100); // 已分配数量
table.getColumnModel().getColumn(5).setPreferredWidth(100); // 库位编码
table.getColumnModel().getColumn(6).setPreferredWidth(100); // 批次号
table.getColumnModel().getColumn(7).setPreferredWidth(120); // 过期日期
table.getColumnModel().getColumn(8).setPreferredWidth(150); // 创建时间
table.getColumnModel().getColumn(9).setPreferredWidth(150); // 更新时间
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param inventoryList null
*/
public static void updateTableData(JTable table, List<Inventory> inventoryList) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0); // 清空原有数据
if (inventoryList == null || inventoryList.isEmpty()) {
return;
}
// 创建日期格式化器
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Inventory inventory : inventoryList) {
// 格式化日期时间
String expiryDate = inventory.getExpiryDate() != null ? inventory.getExpiryDate().format(formatter) : "";
String createdTime = inventory.getCreatedTime() != null ? inventory.getCreatedTime().format(formatter) : "";
String updatedTime = inventory.getUpdatedTime() != null ? inventory.getUpdatedTime().format(formatter) : "";
Object[] rowData = {
inventory.getInventoryId(),
inventory.getProductId(),
inventory.getWarehouseId(),
inventory.getQuantity(),
inventory.getAllocatedQuantity(),
inventory.getLocationCode(),
inventory.getBatchNumber(),
expiryDate,
createdTime,
updatedTime
};
model.addRow(rowData);
}
model.fireTableDataChanged(); // 触发表格刷新
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询库存", true);
searchDialog.setSize(960, 500);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
topPanel.setBackground(SECONDARY_COLOR);
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.setBackground(SECONDARY_COLOR);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按库存ID查询", true);
JRadioButton productIdRadio = new JRadioButton("按商品ID查询");
JRadioButton warehouseIdRadio = new JRadioButton("按仓库ID查询");
JRadioButton keywordRadio = new JRadioButton("关键字查询");
idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
productIdRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
warehouseIdRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
keywordRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
idRadio.setBackground(SECONDARY_COLOR);
productIdRadio.setBackground(SECONDARY_COLOR);
warehouseIdRadio.setBackground(SECONDARY_COLOR);
keywordRadio.setBackground(SECONDARY_COLOR);
buttonGroup.add(idRadio);
buttonGroup.add(productIdRadio);
buttonGroup.add(warehouseIdRadio);
buttonGroup.add(keywordRadio);
radioPanel.add(idRadio);
radioPanel.add(productIdRadio);
radioPanel.add(warehouseIdRadio);
radioPanel.add(keywordRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
searchPanel.setBackground(SECONDARY_COLOR);
JLabel searchLabel = new JLabel("查询条件: ");
searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
searchLabel.setForeground(PRIMARY_COLOR);
JTextField searchField = new JTextField(20);
searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
searchField.setPreferredSize(new Dimension(200, 30));
JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);
JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
searchFieldPanel.setBackground(SECONDARY_COLOR);
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 库位编码/批次号");
tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"库存记录ID", "商品ID", "仓库ID", "当前库存数量", "已分配数量", "库位编码", "批次号", "过期日期", "创建时间", "更新时间"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
resultTable.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
resultTable.getTableHeader().setOpaque(true);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
resultTable.getColumnModel().getColumn(0).setPreferredWidth(80); // 库存记录ID
resultTable.getColumnModel().getColumn(1).setPreferredWidth(60); // 商品ID
resultTable.getColumnModel().getColumn(2).setPreferredWidth(60); // 仓库ID
resultTable.getColumnModel().getColumn(3).setPreferredWidth(100); // 当前库存数量
resultTable.getColumnModel().getColumn(4).setPreferredWidth(100); // 已分配数量
resultTable.getColumnModel().getColumn(5).setPreferredWidth(100); // 库位编码
resultTable.getColumnModel().getColumn(6).setPreferredWidth(100); // 批次号
resultTable.getColumnModel().getColumn(7).setPreferredWidth(120); // 过期日期
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
scrollPane.getViewport().setBackground(Color.WHITE);
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
buttonPanel.setBackground(SECONDARY_COLOR);
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(e -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<Inventory> resultList = new ArrayList<>();
try {
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
List<Inventory> result = SelectInvenTory.selectInventoryById(id);
if (result != null && !result.isEmpty()) {
resultList.addAll(result);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (productIdRadio.isSelected()) {
try {
int productId = Integer.parseInt(searchText);
List<Inventory> result = SelectInvenTory.searchInventoryByProductId(productId);
if (result != null && !result.isEmpty()) {
resultList.addAll(result);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "商品ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (warehouseIdRadio.isSelected()) {
try {
int warehouseId = Integer.parseInt(searchText);
List<Inventory> result = SelectInvenTory.searchInventoryByWarehouseId(warehouseId);
if (result != null && !result.isEmpty()) {
resultList.addAll(result);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "仓库ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (keywordRadio.isSelected()) {
List<Inventory> result = SelectInvenTory.searchInventoryByKeyword(searchText);
if (result != null && !result.isEmpty()) {
resultList.addAll(result);
}
}
// 更新表格数据
tableModel.setRowCount(0);
if (!resultList.isEmpty()) {
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Inventory inventory : resultList) {
String expiryDate = inventory.getExpiryDate() != null ? inventory.getExpiryDate().format(formatter) : "";
String createdTime = inventory.getCreatedTime() != null ? inventory.getCreatedTime().format(formatter) : "";
String updatedTime = inventory.getUpdatedTime() != null ? inventory.getUpdatedTime().format(formatter) : "";
Object[] rowData = {
inventory.getInventoryId(),
inventory.getProductId(),
inventory.getWarehouseId(),
inventory.getQuantity(),
inventory.getAllocatedQuantity(),
inventory.getLocationCode(),
inventory.getBatchNumber(),
expiryDate,
createdTime,
updatedTime
};
tableModel.addRow(rowData);
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int inventoryId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的库存数据
List<Inventory> selectedInventory = SelectInvenTory.selectInventoryById(inventoryId);
if (selectedInventory != null && !selectedInventory.isEmpty()) {
// 清空主表格并只显示选中的库存
DefaultTableModel mainModel = (DefaultTableModel) table.getModel();
mainModel.setRowCount(0);
updateTableData(table, selectedInventory);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
autoRefreshTimer.stop();
}
// 更新状态消息
updateStatusMessage("已选择库存记录: ID=" + inventoryId);
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
public static void main(String[] args) {
new InvenToryMassage();
}
}

@ -1,418 +0,0 @@
package com.xky.ui.module.inventorManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Date;
public class AddInvenTory extends JFrame {
private JPanel contentPanel, formPanel, buttonPanel;
private JTextField[] textFields;
private JFormattedTextField expiryDateField;
private static final Color BACKGROUND_COLOR = new Color(245, 248, 250);
private static final Color ACCENT_COLOR = new Color(70, 130, 180);
private static final Color BUTTON_COLOR = new Color(70, 130, 180);
private static final Color TEXT_COLOR = new Color(50, 50, 80);
private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 24);
private static final Font LABEL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
private static final Font INPUT_FONT = new Font("微软雅黑", Font.PLAIN, 14);
private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
private static final int INPUT_HEIGHT = 30;
public AddInvenTory() {
setTitle("添加商品库存信息");
setSize(550, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
initUI();
setVisible(true);
}
private void initUI() {
// 设置整体布局
setLayout(new BorderLayout());
contentPanel = new JPanel(new BorderLayout(0, 20));
contentPanel.setBackground(BACKGROUND_COLOR);
contentPanel.setBorder(new EmptyBorder(20, 30, 20, 30));
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setBackground(BACKGROUND_COLOR);
JLabel titleLabel = new JLabel("添加商品库存信息");
titleLabel.setFont(TITLE_FONT);
titleLabel.setForeground(ACCENT_COLOR);
titlePanel.add(titleLabel);
// 表单面板
formPanel = new JPanel();
formPanel.setLayout(new GridBagLayout());
formPanel.setBackground(Color.WHITE);
formPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
BorderFactory.createEmptyBorder(20, 25, 20, 25)
));
// 设置圆角面板
formPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
g2.dispose();
}
};
formPanel.setOpaque(false);
formPanel.setLayout(new GridBagLayout());
formPanel.setBackground(Color.WHITE);
formPanel.setBorder(BorderFactory.createEmptyBorder(20, 25, 20, 25));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(8, 5, 8, 5);
gbc.weightx = 1.0;
// 创建表单字段
String[] labelTexts = {
"商品ID",
"仓库ID",
"当前库存数量:",
"已分配数量:",
"库位编码:",
"批次号:",
"过期日期:"
};
textFields = new JTextField[6]; // 现在有6个文本字段
for (int i = 0; i < labelTexts.length; i++) {
JLabel label = new JLabel(labelTexts[i]);
label.setFont(LABEL_FONT);
label.setForeground(TEXT_COLOR);
gbc.gridx = 0;
gbc.gridy = i;
gbc.gridwidth = 1;
formPanel.add(label, gbc);
if (i == 6) { // 过期日期
expiryDateField = new JFormattedTextField(new SimpleDateFormat("yyyy-MM-dd"));
expiryDateField.setValue(new Date());
expiryDateField.setFont(INPUT_FONT);
expiryDateField.setPreferredSize(new Dimension(250, INPUT_HEIGHT));
expiryDateField.setToolTipText("格式: yyyy-MM-dd");
// 添加日历选择按钮
JPanel datePanel = new JPanel(new BorderLayout());
datePanel.add(expiryDateField, BorderLayout.CENTER);
JButton calendarButton = new JButton("📅");
calendarButton.setPreferredSize(new Dimension(INPUT_HEIGHT, INPUT_HEIGHT));
calendarButton.addActionListener(e -> showDatePicker());
datePanel.add(calendarButton, BorderLayout.EAST);
gbc.gridx = 1;
formPanel.add(datePanel, gbc);
} else {
textFields[i] = new JTextField();
textFields[i].setFont(INPUT_FONT);
textFields[i].setPreferredSize(new Dimension(250, INPUT_HEIGHT));
// 添加焦点监听器和提示
setupTextField(textFields[i], getPlaceholder(i), getTooltip(i));
gbc.gridx = 1;
formPanel.add(textFields[i], gbc);
}
}
// 按钮面板
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setBackground(BACKGROUND_COLOR);
JButton submitButton = createStyledButton("提交", BUTTON_COLOR);
JButton resetButton = createStyledButton("重置", new Color(120, 120, 120));
buttonPanel.add(submitButton);
buttonPanel.add(resetButton);
// 组装面板
contentPanel.add(titlePanel, BorderLayout.NORTH);
contentPanel.add(formPanel, BorderLayout.CENTER);
contentPanel.add(buttonPanel, BorderLayout.SOUTH);
add(contentPanel);
// 按钮事件
submitButton.addActionListener(e -> handleSubmit());
resetButton.addActionListener(e -> handleReset());
}
private void setupTextField(JTextField textField, String placeholder, String tooltip) {
textField.setForeground(Color.GRAY);
textField.setText(placeholder);
textField.setToolTipText(tooltip);
textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if (textField.getText().equals(placeholder)) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
}
@Override
public void focusLost(FocusEvent e) {
if (textField.getText().isEmpty()) {
textField.setForeground(Color.GRAY);
textField.setText(placeholder);
}
}
});
}
private String getPlaceholder(int fieldIndex) {
switch (fieldIndex) {
case 0: return "请输入商品ID";
case 1: return "请输入仓库ID";
case 2: return "请输入库存数量";
case 3: return "请输入已分配数量";
case 4: return "请输入库位编码";
case 5: return "请输入批次号";
default: return "";
}
}
private String getTooltip(int fieldIndex) {
switch (fieldIndex) {
case 0: return "商品ID必须是正整数";
case 1: return "仓库ID必须是正整数";
case 2: return "库存数量必须为非负整数";
case 3: return "已分配数量必须为非负整数,且不能超过库存数量";
case 4: return "库位编码不能为空";
case 5: return "批次号不能为空";
default: return "";
}
}
private JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text) {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
g2.dispose();
super.paintComponent(g);
}
};
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFont(BUTTON_FONT);
button.setPreferredSize(new Dimension(120, 36));
return button;
}
private void showDatePicker() {
// 简单实现,实际项目中可以使用第三方日期选择器
JOptionPane.showMessageDialog(this, "请在文本框中直接输入日期格式为yyyy-MM-dd",
"日期选择", JOptionPane.INFORMATION_MESSAGE);
}
private void handleSubmit() {
try {
// 获取并验证输入
String productIdText = textFields[0].getText().trim();
String warehouseIdText = textFields[1].getText().trim();
String quantityText = textFields[2].getText().trim();
String allocatedText = textFields[3].getText().trim();
String locationCode = textFields[4].getText().trim();
String batchNumber = textFields[5].getText().trim();
String expiryDateStr = expiryDateField.getText().trim();
// 检查占位符
if (productIdText.equals(getPlaceholder(0))) productIdText = "";
if (warehouseIdText.equals(getPlaceholder(1))) warehouseIdText = "";
if (quantityText.equals(getPlaceholder(2))) quantityText = "";
if (allocatedText.equals(getPlaceholder(3))) allocatedText = "";
if (locationCode.equals(getPlaceholder(4))) locationCode = "";
if (batchNumber.equals(getPlaceholder(5))) batchNumber = "";
Integer productId = parseIntegerField(productIdText, "商品ID");
Integer warehouseId = parseIntegerField(warehouseIdText, "仓库ID");
Integer quantity = parseIntegerField(quantityText, "当前库存数量");
Integer allocatedQuantity = parseIntegerField(allocatedText, "已分配数量");
// 输入验证
if (!validateInputs(productId, warehouseId, quantity,
allocatedQuantity, locationCode, batchNumber, expiryDateStr)) {
return;
}
// 添加记录
if (addProduct(productId, warehouseId, quantity,
allocatedQuantity, locationCode, batchNumber, expiryDateStr)) {
JOptionPane.showMessageDialog(this, "商品库存信息添加成功!",
"成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "商品库存信息添加失败!",
"错误", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
private void handleReset() {
for (int i = 0; i < textFields.length; i++) {
textFields[i].setForeground(Color.GRAY);
textFields[i].setText(getPlaceholder(i));
}
expiryDateField.setValue(new Date());
}
private Integer parseIntegerField(String text, String fieldName) throws NumberFormatException {
if (text.isEmpty()) {
throw new NumberFormatException(fieldName + "不能为空");
}
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new NumberFormatException(fieldName + "必须是有效的整数");
}
}
private boolean validateInputs(Integer productId, Integer warehouseId,
Integer quantity, Integer allocatedQuantity,
String locationCode, String batchNumber, String expiryDateStr) {
if (productId == null) {
showValidationError("请选择有效的商品");
return false;
}
if (warehouseId == null) {
showValidationError("请选择有效的仓库");
return false;
}
if (quantity == null || quantity < 0) {
showValidationError("库存数量不能为负数");
return false;
}
if (allocatedQuantity == null || allocatedQuantity < 0) {
showValidationError("已分配数量不能为负数");
return false;
}
if (allocatedQuantity > quantity) {
showValidationError("已分配数量不能大于总库存数量");
return false;
}
if (locationCode.isEmpty()) {
showValidationError("库位编码不能为空");
return false;
}
if (batchNumber.isEmpty()) {
showValidationError("批次号不能为空");
return false;
}
// 日期验证
try {
LocalDate expiryDate = LocalDate.parse(expiryDateStr);
if (expiryDate.isBefore(LocalDate.now())) {
showValidationError("过期日期不能早于当前日期");
return false;
}
} catch (DateTimeParseException e) {
showValidationError("过期日期格式不正确请使用yyyy-MM-dd格式");
return false;
}
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入验证错误", JOptionPane.WARNING_MESSAGE);
}
private boolean addProduct(Integer productId, Integer warehouseId,
Integer quantity, Integer allocatedQuantity,
String locationCode, String batchNumber, String expiryDateStr) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
connection.setAutoCommit(false);
String sql = "INSERT INTO inventory(product_id, warehouse_id, quantity, " +
"allocated_quantity, location_code, batch_number, expiry_date, " +
"last_stock_update, created_time, updated_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), NOW())";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, productId);
preparedStatement.setInt(2, warehouseId);
preparedStatement.setInt(3, quantity);
preparedStatement.setInt(4, allocatedQuantity);
preparedStatement.setString(5, locationCode);
preparedStatement.setString(6, batchNumber);
preparedStatement.setDate(7, java.sql.Date.valueOf(LocalDate.parse(expiryDateStr)));
int affectedRows = preparedStatement.executeUpdate();
connection.commit();
return affectedRows > 0;
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(),
"数据库错误", JOptionPane.ERROR_MESSAGE);
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
new AddInvenTory();
});
}
}

@ -1,305 +0,0 @@
package com.xky.ui.module.inventorManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*/
public class DeleteInvenTory extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteInvenTory() {
setTitle("删除库存订单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
/**
* ID
* @param orderId ID
*/
public DeleteInvenTory(int orderId) {
setTitle("删除库存订单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
// 自动填充订单ID
JTextField idField = (JTextField) ((JPanel)((JPanel)getContentPane().getComponent(0)).getComponent(1)).getComponent(0);
idField.setText(String.valueOf(orderId));
setVisible(true);
}
void init() {
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的商品ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有销售订单的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有库存订单");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个销售订单删除按钮事件
jButton.addActionListener(e -> {
String idText = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入你要删除的商品ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
Integer id = Integer.valueOf(idText);
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该库存订单吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
if (orderExists(id)) {
deleteSalesOrder(id);
JOptionPane.showMessageDialog(null, "该库存订单删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该商品ID,删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有销售订单按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有库存订单信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有销售订单的操作
if (deleteAllSalesOrders()) {
JOptionPane.showMessageDialog(
null,
"所有库存订单已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有库存订单失败",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
* ID
* @param id ID
* @return
*/
private boolean orderExists(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM inventory WHERE product_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param id ID
* @return
*/
public boolean deleteSalesOrder(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM inventory WHERE product_id = ?");
preparedStatement.setInt(1, id);
int rows = preparedStatement.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllSalesOrders() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM inventory");
return true; // 即使没有记录被删除也算成功
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteInvenTory::new);
}
}

@ -1,241 +0,0 @@
package com.xky.ui.module.inventorManagement.select;
import com.xky.pojo.Inventory;
import com.xky.utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
*/
public class SelectInvenTory {
/**
*
* @return
*/
public static List<Inventory> selectAllInventory() {
String sql = "SELECT * FROM inventory";
return executeInventoryQuery(sql, null);
}
/**
* ID
* @param id ID
* @return truefalse
*/
public static boolean isInventoryExistById(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT 1 FROM inventory WHERE inventory_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
return resultSet.next(); // 只需要检查是否存在记录
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
* ID
* @param id ID
* @return
*/
public static List<Inventory> selectInventoryById(Integer id) {
String sql = "SELECT * FROM inventory WHERE inventory_id = ?";
return executeInventoryQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, id);
});
}
/**
*
* @param keyword
* @return
*/
public static List<Inventory> searchInventoryByKeyword(String keyword) {
String sql = "SELECT * FROM inventory WHERE location_code LIKE ? OR batch_number LIKE ?";
return executeInventoryQuery(sql, preparedStatement -> {
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
preparedStatement.setString(2, searchPattern);
});
}
/**
* ID
* @param productId ID
* @return
*/
public static List<Inventory> searchInventoryByProductId(Integer productId) {
String sql = "SELECT * FROM inventory WHERE product_id = ?";
return executeInventoryQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, productId);
});
}
/**
* ID
* @param warehouseId ID
* @return
*/
public static List<Inventory> searchInventoryByWarehouseId(Integer warehouseId) {
String sql = "SELECT * FROM inventory WHERE warehouse_id = ?";
return executeInventoryQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, warehouseId);
});
}
/**
* ID
* @param supplierId ID
* @return
*/
public static List<Inventory> selectInventoryBySupplier(Integer supplierId) {
String sql =
"SELECT i.*, p.product_name, w.warehouse_name " +
"FROM inventory i " +
"JOIN products p ON i.product_id = p.product_id " +
"JOIN warehouses w ON i.warehouse_id = w.warehouse_id " +
"WHERE i.supplier_id = ? " +
"ORDER BY i.inventory_id";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Inventory> inventoryList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, supplierId);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Inventory inventory = new Inventory();
inventory.setInventoryId(resultSet.getInt("inventory_id"));
inventory.setProductId(resultSet.getInt("product_id"));
inventory.setWarehouseId(resultSet.getInt("warehouse_id"));
inventory.setQuantity(resultSet.getInt("quantity"));
// 获取创建时间和更新时间
setTimestampFields(resultSet, inventory);
inventoryList.add(inventory);
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return inventoryList;
}
/**
*
* @param sql SQL
* @param preparer SQL
* @return
*/
private static List<Inventory> executeInventoryQuery(String sql, PreparedStatementPreparer preparer) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Inventory> inventoryList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
// 如果有参数需要设置
if (preparer != null) {
preparer.prepare(preparedStatement);
}
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Inventory inventory = createInventoryFromResultSet(resultSet);
inventoryList.add(inventory);
}
} catch (SQLException e) {
e.printStackTrace();
// 记录错误但不中断程序流程
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return inventoryList;
}
/**
* ResultSetInventory
* @param resultSet
* @return Inventory
* @throws SQLException 访
*/
private static Inventory createInventoryFromResultSet(ResultSet resultSet) throws SQLException {
Inventory inventory = new Inventory();
inventory.setInventoryId(resultSet.getInt("inventory_id"));
inventory.setProductId(resultSet.getInt("product_id"));
inventory.setWarehouseId(resultSet.getInt("warehouse_id"));
inventory.setQuantity(resultSet.getInt("quantity"));
inventory.setAllocatedQuantity(resultSet.getInt("allocated_quantity"));
inventory.setLocationCode(resultSet.getString("location_code"));
inventory.setBatchNumber(resultSet.getString("batch_number"));
// 设置时间戳字段
setTimestampFields(resultSet, inventory);
return inventory;
}
/**
* Inventory
* @param resultSet
* @param inventory
* @throws SQLException 访
*/
private static void setTimestampFields(ResultSet resultSet, Inventory inventory) throws SQLException {
// 设置过期日期
Timestamp expiryDate = resultSet.getTimestamp("expiry_date");
if (expiryDate != null) {
inventory.setExpiryDate(expiryDate.toLocalDateTime());
}
// 设置创建时间
Timestamp createdTime = resultSet.getTimestamp("created_time");
if (createdTime != null) {
inventory.setCreatedTime(createdTime.toLocalDateTime());
}
// 设置更新时间
Timestamp updatedTime = resultSet.getTimestamp("updated_time");
if (updatedTime != null) {
inventory.setUpdatedTime(updatedTime.toLocalDateTime());
}
}
/**
* PreparedStatement
*/
@FunctionalInterface
private interface PreparedStatementPreparer {
void prepare(PreparedStatement preparedStatement) throws SQLException;
}
}

@ -1,533 +0,0 @@
package com.xky.ui.module.inventorManagement.update;
import com.xky.pojo.Inventory;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class UpdateInvenTory extends JFrame {
private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
private JTextField inventoryIdField, productIdField, warehouseIdField, quantityField,
allocatedQuantityField, locationCodeField, batchNumberField,
expiryDateField, productNameField, warehouseNameField, supplierIdField;
private JButton updateButton, queryButton;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
// 日期格式化
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public UpdateInvenTory() {
initializeFrame();
initComponents();
setVisible(true);
}
private void initializeFrame() {
setTitle("库存信息修改");
setSize(600, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
private void initComponents() {
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 1. 头部面板
createHeaderPanel();
// 2. 表单面板
createFormPanel();
// 3. 按钮面板
createButtonPanel();
// 添加事件监听
setupEventListeners();
add(mainPanel);
}
private void createHeaderPanel() {
headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("库存信息修改");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入库存ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
}
private void createFormPanel() {
// 创建带圆角和阴影的面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
// 创建输入字段
inventoryIdField = createStyledTextField(fieldFont);
productIdField = createStyledTextField(fieldFont);
warehouseIdField = createStyledTextField(fieldFont);
quantityField = createStyledTextField(fieldFont);
allocatedQuantityField = createStyledTextField(fieldFont);
locationCodeField = createStyledTextField(fieldFont);
batchNumberField = createStyledTextField(fieldFont);
expiryDateField = createStyledTextField(fieldFont);
productNameField = createStyledTextField(fieldFont);
warehouseNameField = createStyledTextField(fieldFont);
supplierIdField = createStyledTextField(fieldFont);
// 添加字段到面板
int row = 0;
addFormField(row++, "库存ID *", inventoryIdField, labelFont, true);
// 添加分组标签 - 库存信息
JLabel inventoryGroupLabel = new JLabel("库存信息");
inventoryGroupLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
inventoryGroupLabel.setForeground(PRIMARY_COLOR);
gbc.gridx = 0;
gbc.gridy = row++;
gbc.gridwidth = 2;
formPanel.add(inventoryGroupLabel, gbc);
gbc.gridwidth = 1;
addFormField(row++, "仓库ID *", warehouseIdField, labelFont, true);
addFormField(row++, "当前库存数量 *", quantityField, labelFont, true);
addFormField(row++, "已分配数量", allocatedQuantityField, labelFont, false);
// 添加分组标签 - 批次信息
JLabel batchGroupLabel = new JLabel("批次信息");
batchGroupLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
batchGroupLabel.setForeground(PRIMARY_COLOR);
gbc.gridx = 0;
gbc.gridy = row++;
gbc.gridwidth = 2;
formPanel.add(batchGroupLabel, gbc);
gbc.gridwidth = 1;
addFormField(row++, "库位编码 *", locationCodeField, labelFont, true);
addFormField(row++, "批次号 *", batchNumberField, labelFont, true);
addFormField(row++, "过期日期 (yyyy-MM-dd) *", expiryDateField, labelFont, true);
JScrollPane scrollPane = new JScrollPane(formPanel);
scrollPane.setBorder(null);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
formCard.add(scrollPane, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
}
private JTextField createStyledTextField(Font font) {
JTextField field = new JTextField();
field.setFont(font);
field.setPreferredSize(new Dimension(250, 35));
field.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(200, 215, 230)),
BorderFactory.createEmptyBorder(3, 5, 3, 5)
));
return field;
}
private void addFormField(int row, String labelText, JComponent field, Font labelFont, boolean required) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = row;
gbc.weightx = 0.3;
gbc.anchor = GridBagConstraints.WEST;
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
labelPanel.setOpaque(false);
JLabel label = new JLabel(labelText);
label.setFont(labelFont);
label.setForeground(PRIMARY_COLOR);
labelPanel.add(label);
formPanel.add(labelPanel, gbc);
gbc.gridx = 1;
gbc.weightx = 0.7;
formPanel.add(field, gbc);
}
private void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
queryButton = new JButton("查询");
styleButton(queryButton, QUERY_BUTTON_COLOR);
updateButton = new JButton("修改");
styleButton(updateButton, BUTTON_COLOR);
// 初始状态下修改按钮不可用
updateButton.setEnabled(false);
buttonPanel.add(queryButton);
buttonPanel.add(updateButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
private void setupEventListeners() {
// 查询按钮事件
queryButton.addActionListener(e -> {
String inventoryIdStr = inventoryIdField.getText().trim();
if (inventoryIdStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入库存ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
int inventoryId = Integer.parseInt(inventoryIdStr);
Inventory inventory = findInventoryById(inventoryId);
if (inventory != null) {
// 填充表单数据
populateForm(inventory);
// 启用修改按钮
updateButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(this, "未找到该库存记录", "提示", JOptionPane.WARNING_MESSAGE);
updateButton.setEnabled(false);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
// 修改按钮事件
updateButton.addActionListener(e -> {
try {
// 首先进行输入校验
if (!validateInputs()) {
return; // 如果校验不通过,直接返回
}
Inventory inventory = getInventoryFromForm();
if (updateInventory(inventory)) {
JOptionPane.showMessageDialog(this, "库存信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "库存信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
private void populateForm(Inventory inventory) {
inventoryIdField.setText(inventory.getInventoryId().toString());
productIdField.setText(inventory.getProductId().toString());
warehouseIdField.setText(inventory.getWarehouseId().toString());
quantityField.setText(inventory.getQuantity().toString());
if (inventory.getAllocatedQuantity() != null) {
allocatedQuantityField.setText(inventory.getAllocatedQuantity().toString());
} else {
allocatedQuantityField.setText("");
}
locationCodeField.setText(inventory.getLocationCode());
batchNumberField.setText(inventory.getBatchNumber());
if (inventory.getExpiryDate() != null) {
expiryDateField.setText(inventory.getExpiryDate().toLocalDate().format(DATE_FORMATTER));
} else {
expiryDateField.setText("");
}
}
private Inventory getInventoryFromForm() {
Inventory inventory = new Inventory();
inventory.setInventoryId(Integer.valueOf(inventoryIdField.getText().trim()));
inventory.setProductId(Integer.valueOf(productIdField.getText().trim()));
inventory.setWarehouseId(Integer.valueOf(warehouseIdField.getText().trim()));
inventory.setQuantity(Integer.valueOf(quantityField.getText().trim()));
String allocatedQty = allocatedQuantityField.getText().trim();
if (!allocatedQty.isEmpty()) {
inventory.setAllocatedQuantity(Integer.valueOf(allocatedQty));
}
inventory.setLocationCode(locationCodeField.getText().trim());
inventory.setBatchNumber(batchNumberField.getText().trim());
String expiryDateStr = expiryDateField.getText().trim();
if (!expiryDateStr.isEmpty()) {
LocalDate expiryDate = LocalDate.parse(expiryDateStr, DATE_FORMATTER);
inventory.setExpiryDate(LocalDateTime.of(expiryDate, LocalDateTime.now().toLocalTime()));
}
return inventory;
}
private boolean validateInputs() {
// 1. 校验库存ID
if (!validateRequiredField(inventoryIdField, "库存ID")) return false;
// 2. 校验产品ID
if (!validateRequiredField(productIdField, "产品ID")) return false;
// 3. 校验仓库ID
if (!validateRequiredField(warehouseIdField, "仓库ID")) return false;
// 4. 校验库存数量
if (!validateRequiredField(quantityField, "库存数量")) return false;
// 5. 校验已分配数量(如果有值)
if (!allocatedQuantityField.getText().trim().isEmpty() &&
!validateNumericField(allocatedQuantityField, "已分配数量")) return false;
// 6. 校验库位编码
if (!validateRequiredField(locationCodeField, "库位编码")) return false;
// 7. 校验批次号
if (!validateRequiredField(batchNumberField, "批次号")) return false;
// 8. 校验过期日期
if (!validateRequiredField(expiryDateField, "过期日期")) return false;
try {
LocalDate.parse(expiryDateField.getText().trim(), DATE_FORMATTER);
} catch (DateTimeParseException e) {
showValidationError("过期日期格式不正确请使用yyyy-MM-dd格式");
return false;
}
// 所有校验通过
return true;
}
private boolean validateRequiredField(JTextField field, String fieldName) {
if (field.getText().trim().isEmpty()) {
showValidationError(fieldName + "不能为空");
field.requestFocus();
return false;
}
return true;
}
private boolean validateNumericField(JTextField field, String fieldName) {
try {
Integer.parseInt(field.getText().trim());
return true;
} catch (NumberFormatException e) {
showValidationError(fieldName + "必须是数字");
field.requestFocus();
return false;
}
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
private Inventory findInventoryById(int inventoryId) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM inventory WHERE inventory_id = ?");
preparedStatement.setInt(1, inventoryId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Inventory inventory = new Inventory();
inventory.setInventoryId(resultSet.getInt("inventory_id"));
inventory.setProductId(resultSet.getInt("product_id"));
inventory.setWarehouseId(resultSet.getInt("warehouse_id"));
inventory.setQuantity(resultSet.getInt("quantity"));
inventory.setAllocatedQuantity(resultSet.getInt("allocated_quantity"));
if (resultSet.wasNull()) {
inventory.setAllocatedQuantity(null);
}
inventory.setLocationCode(resultSet.getString("location_code"));
inventory.setBatchNumber(resultSet.getString("batch_number"));
Timestamp expiryDate = resultSet.getTimestamp("expiry_date");
if (expiryDate != null) {
inventory.setExpiryDate(expiryDate.toLocalDateTime());
}
Timestamp lastStockUpdate = resultSet.getTimestamp("last_stock_update");
if (lastStockUpdate != null) {
inventory.setLastStockUpdate(lastStockUpdate.toLocalDateTime());
}
Timestamp createdTime = resultSet.getTimestamp("created_time");
if (createdTime != null) {
inventory.setCreatedTime(createdTime.toLocalDateTime());
}
Timestamp updatedTime = resultSet.getTimestamp("updated_time");
if (updatedTime != null) {
inventory.setUpdatedTime(updatedTime.toLocalDateTime());
}
return inventory;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
private boolean updateInventory(Inventory inventory) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"UPDATE inventory SET product_id = ?, warehouse_id = ?, quantity = ?, " +
"allocated_quantity = ?, location_code = ?, batch_number = ?, " +
"expiry_date = ?, last_stock_update = NOW(), updated_time = NOW() WHERE inventory_id = ?");
preparedStatement.setInt(1, inventory.getProductId());
preparedStatement.setInt(2, inventory.getWarehouseId());
preparedStatement.setInt(3, inventory.getQuantity());
if (inventory.getAllocatedQuantity() != null) {
preparedStatement.setInt(4, inventory.getAllocatedQuantity());
} else {
preparedStatement.setNull(4, Types.INTEGER);
}
preparedStatement.setString(5, inventory.getLocationCode());
preparedStatement.setString(6, inventory.getBatchNumber());
if (inventory.getExpiryDate() != null) {
preparedStatement.setTimestamp(7, Timestamp.valueOf(inventory.getExpiryDate()));
} else {
preparedStatement.setNull(7, Types.TIMESTAMP);
}
preparedStatement.setInt(8,inventory.getInventoryId());
return preparedStatement.executeUpdate() > 0;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateInvenTory::new);
}
}

@ -1,64 +0,0 @@
package com.xky.ui.module.login;
import com.xky.utils.DBUtils;
import com.xky.utils.MD5Utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import static java.sql.Types.VARCHAR;
public class Autoregister {
public static void adminRegister() throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; // 用于接收查询结果
String username = "admin";
String password = "admin123";
try {
connection = DBUtils.getConnection();
// 1. 先查询数据库中是否已存在 admin 账号
String checkSql = "SELECT COUNT(*) FROM login WHERE username = ?";
preparedStatement = connection.prepareStatement(checkSql);
preparedStatement.setString(1, username); // 设置查询参数为 admin
resultSet = preparedStatement.executeQuery();
// 判断是否存在:如果 COUNT(*) > 0说明已存在
boolean exists = false;
if (resultSet.next()) {
int count = resultSet.getInt(1); // 获取第一列COUNT(*))的值
exists = count > 0;
}
// 2. 根据查询结果决定是否注册
if (exists) {
System.out.println("管理员账号已存在,无需重复注册");
return; // 直接返回,跳过后续插入逻辑
}
// 3. 不存在则执行注册(原有加密和插入逻辑)
String mdpassword = MD5Utils.md5Encrypt(password);
String insertSql = "INSERT INTO login(username, password, email) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(insertSql);
preparedStatement.setString(1, username);
preparedStatement.setString(2, mdpassword);
preparedStatement.setNull(3, VARCHAR);
long rows = preparedStatement.executeLargeUpdate();
if (rows > 0) {
System.out.println("管理员账号已自动注册");
} else {
System.out.println("管理员账号自动注册失败请手动前往数据库中的login表中注册");
}
} finally {
// 关闭所有资源(包含 ResultSet
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
}

@ -1,248 +0,0 @@
package com.xky.ui.module.login;
import com.xky.pojo.User;
import com.xky.ui.main.MainView;
import com.xky.ui.module.register.Register;
import com.xky.utils.DBUtils;
import com.xky.utils.MD5Utils;
import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* 6
* 1
* 2
* 3
* 4
* 5mysql
*
* 6
*/
// 登录界面类,继承自 JFrame
public class Login extends JFrame {
private JTextField usernameField; // 用户名输入框
private JPasswordField passwordField; // 密码输入框
// 构造函数,初始化登录界面
public Login() {
setTitle("登录界面"); // 设置窗口标题
setSize(450, 450); // 设置窗口大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭操作
setLocationRelativeTo(null); // 窗口居中显示
init(); // 初始化界面组件
setVisible(true); // 显示窗口
}
// 初始化界面组件
public void init() {
// 主面板
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(new Color(153, 244, 145));
setContentPane(mainPanel);
// 标题(顶部)
JLabel titleLabel = new JLabel("用户登录", SwingConstants.CENTER); // 创建标题标签
titleLabel.setFont(new Font("华文行楷", Font.PLAIN, 40)); // 设置字体
titleLabel.setOpaque(false); // 设置标签为透明
mainPanel.add(titleLabel, BorderLayout.NORTH); // 将标签添加到主面板的北部
// 中央表单面板
JPanel formPanel = createFormPanel(); // 创建表单面板
mainPanel.add(formPanel, BorderLayout.CENTER); // 将表单面板添加到主面板的中央
// 底部按钮面板
JPanel buttonPanel = createButtonPanel(); // 创建按钮面板
mainPanel.add(buttonPanel, BorderLayout.SOUTH); // 将按钮面板添加到主面板的南部
}
// 创建表单面板
private JPanel createFormPanel() {
JPanel formPanel = new JPanel(new GridBagLayout()); // 创建表单面板,使用 GridBagLayout 布局
formPanel.setOpaque(false); // 设置面板为透明
GridBagConstraints gbc = new GridBagConstraints(); // 创建布局约束
gbc.insets = new Insets(7, 0, 7, 0); // 设置组件之间的间距
Font font = new Font("微软雅黑", Font.PLAIN, 20);
// 用户名标签
JLabel usernameLabel = new JLabel("用户名:");
usernameLabel.setFont(font);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10,50,10,10);
gbc.weightx = 0.0;
gbc.fill = GridBagConstraints.NONE;
formPanel.add(usernameLabel, gbc);
// 用户名输入框
usernameField = new JTextField(20);
usernameField.setPreferredSize(new Dimension(250,35));
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0; // 让输入框占用所有可用的水平空间
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
formPanel.add(usernameField, gbc);
// 密码标签
JLabel passwordLabel = new JLabel("密码:");
passwordLabel.setFont(font);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.0;
gbc.gridwidth = 1;
gbc.insets = new Insets(10,50,10,10);
gbc.fill = GridBagConstraints.NONE;
formPanel.add(passwordLabel, gbc);
// 密码输入框
passwordField = new JPasswordField(20);
passwordField.setPreferredSize(new Dimension(250,35));
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
formPanel.add(passwordField, gbc);
//角色提示
JLabel jLabel = new JLabel("你当前登录的角色是管理员");
jLabel.setFont(new Font("华文行楷",Font.PLAIN,15));
jLabel.setForeground(Color.BLACK);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(5,30,10,10);
formPanel.add(jLabel,gbc);
JLabel jLabel1 = new JLabel("管理员默认账户admin 密码admin123");
jLabel.setFont(new Font("华文行楷",Font.PLAIN,15));
jLabel.setForeground(Color.BLACK);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(5,30,10,10);
formPanel.add(jLabel1,gbc);
return formPanel; // 返回表单面板
}
// 创建按钮面板
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel(new GridBagLayout()); // 创建按钮面板,使用 GridBagLayout 布局
buttonPanel.setOpaque(false); // 设置面板为透明
GridBagConstraints gbc = new GridBagConstraints(); // 创建布局约束
gbc.insets = new Insets(20, 10, 20, 10); // 设置组件之间的间距
gbc.anchor = GridBagConstraints.CENTER; // 设置组件对齐方式
// 登录按钮
JButton loginButton = new JButton("登录"); // 创建登录按钮
loginButton.setPreferredSize(new Dimension(80,35));
loginButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
loginButton.setBackground(Color.cyan);
loginButton.setBorderPainted(false);
gbc.insets = new Insets(10,10,30,10);
loginButton.addActionListener(e1 -> {
try {
handleLogin(); // 处理登录事件
} catch (SQLException e) {
throw new RuntimeException(e); // 抛出运行时异常
}
});
// 密码框回车触发登录
passwordField.addActionListener(_ -> loginButton.doClick()); // 密码框回车时触发登录按钮点击事件
gbc.gridx = 0; // 设置网格 x 坐标
gbc.gridy = 0; // 设置网格 y 坐标
buttonPanel.add(loginButton, gbc); // 将登录按钮添加到按钮面板
// 注册按钮
JButton registerButton = new JButton("注册"); // 创建注册按钮
registerButton.setPreferredSize(new Dimension(80,35));
registerButton.setBackground(Color.orange);
registerButton.setBorderPainted(false);
gbc.insets = new Insets(10,50,30,10);
registerButton.addActionListener(e -> {
dispose();
new Register();
});
gbc.gridx = 1; // 设置网格 x 坐标
buttonPanel.add(registerButton, gbc); // 将注册按钮添加到按钮面板
return buttonPanel; // 返回按钮面板
}
// 处理登录事件
private void handleLogin() throws SQLException {
String username = usernameField.getText().trim(); // 获取用户名并去除空格
String password = new String(passwordField.getPassword()).trim(); // 获取密码并去除空格
if (username.isEmpty() || password.isEmpty()) {
showError("用户名和密码不能为空"); // 如果用户名或密码为空,显示错误提示
} else {
User user = authenticate(username, password);
if (user != null) {
JOptionPane.showMessageDialog(this, "登录成功!", "成功", JOptionPane.INFORMATION_MESSAGE); // 登录成功提示
this.dispose(); // 关闭登录窗口
new MainView();
} else {
showError("用户名或密码错误"); // 用户名或密码错误提示
}
}
}
private User authenticate(String username, String password) throws SQLException {
// 校验输入参数非空
if (username == null || password == null) {
return null;
}
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
String mdpassword = MD5Utils.md5Encrypt(password);
// 只查询需要的字段
preparedStatement = connection.prepareStatement(
"select username, password, email from login where username=? and password=?"
);
preparedStatement.setString(1, username);
preparedStatement.setString(2, mdpassword);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
User user = new User();
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password")); // 注意:这里返回的是加密后的密码
user.setEmail(resultSet.getString("email"));
return user;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
// 显示错误提示
private void showError(String message) {
JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE); // 显示错误提示框
passwordField.setText(""); // 清空密码框
passwordField.requestFocus(); // 将焦点设置到密码框
}
// 主方法,启动登录界面
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 设置外观为系统外观
} catch (Exception e) {
e.printStackTrace(); // 打印异常堆栈
}
SwingUtilities.invokeLater(Login::new); // 在事件调度线程中创建登录界面
}
}

@ -1,677 +0,0 @@
package com.xky.ui.module.productManagement;
import com.xky.pojo.*;
import com.xky.ui.module.customersManagement.CustomersInfo;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import com.xky.ui.module.inventorManagement.add.AddInvenTory;
import com.xky.ui.module.inventorManagement.InvenToryInfo;
import com.xky.ui.module.inventorManagement.select.SelectInvenTory;
import com.xky.ui.module.productManagement.add.AddProduct;
import com.xky.ui.module.productManagement.delete.DeleteProduct;
import com.xky.ui.module.productManagement.select.ProductService;
import com.xky.ui.module.productManagement.select.SelectCateGory;
import com.xky.ui.module.productManagement.select.SelectProduct;
import com.xky.ui.module.productManagement.update.UpdateProduct;
import com.xky.ui.module.salesManagement.SalesInfo;
import com.xky.ui.module.salesManagement.SalesShipmentsInfo;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.module.supplierManagement.SupplierInfo;
import com.xky.ui.module.supplierManagement.select.SelectSupplier;
import com.xky.ui.module.warehouseManagement.WarehouseInfo;
import com.xky.ui.module.warehouseManagement.select.WarehouseService;
import lombok.Getter;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
public class BasicMassage {
static JTable table;
@Getter
private static String description;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);//用于标题、主要按钮等突出显示元素
private static final Color SECONDARY_COLOR = new Color(255, 255, 255);//用于背景色或次要面板
private static final Color BUTTON_COLOR = new Color(100, 149, 237);//用于普通按钮的默认状态
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);//用于面板间的分隔线
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);//用于搜索/查询类操作按钮
/**
*
* @return
*/
public static JPanel createHomePanel() {
JPanel panel = new JPanel(new BorderLayout(10, 10));//在每个区域之间添加水平和垂直方向上的间距都是10个像素。
//这行代码的目的是为 panel 设置一个边框。setBorder 方法用于指定一个边框对象,这个对象将围绕着面板进行绘制。
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.setBackground(new Color(245, 245, 245));
// 创建顶部欢迎面板
JPanel welcomePanel = new JPanel(new BorderLayout());
welcomePanel.setBackground(new Color(48, 57, 82));
welcomePanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
JLabel titleLabel = new JLabel("商品库存管理系统");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
titleLabel.setForeground(Color.WHITE);
welcomePanel.add(titleLabel, BorderLayout.NORTH);
JLabel subtitleLabel = new JLabel("高效管理您的商品和库存");
subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
subtitleLabel.setForeground(new Color(200, 200, 200));
subtitleLabel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
welcomePanel.add(subtitleLabel, BorderLayout.CENTER);
panel.add(welcomePanel, BorderLayout.NORTH);
// 创建中央信息面板
JPanel infoPanel = new JPanel(new GridLayout(3, 2, 25, 25));//3, 2, 25, 25分别代表行垂直间距水平间距
infoPanel.setBorder(BorderFactory.createEmptyBorder(35, 35, 35, 35));
infoPanel.setBackground(new Color(245, 245, 245));
// 添加统计卡片
// 向信息面板添加多个仪表盘卡片,展示商品、分类、仓库、库存、供应商、客户、销售订单和销售发货的统计信息
infoPanel.add(createDashboardCard("商品总数", getProductCount(), "商品基础信息",
new Color(41, 128, 185), new ImageIcon("lib/1.jpg")));
infoPanel.add(createDashboardCard("分类总数", getCategoryCount(), "商品分类",
new Color(39, 174, 96), new ImageIcon("lib/2.jpg")));
infoPanel.add(createDashboardCard("仓库总数", getWarehouseCount(), "仓库信息",
new Color(142, 68, 173), new ImageIcon("lib/3.jpg")));
infoPanel.add(createDashboardCard("库存情况", getInventoryCount(), "库存记录",
new Color(0, 211, 84), new ImageIcon("lib/4.jpg")));
infoPanel.add(createDashboardCard("供应商总数", getSupplierCount(), "供应商信息",
new Color(100, 199, 188), new ImageIcon("lib/5.jpg")));
infoPanel.add(createDashboardCard("客户情况",getCustomerCount(),"客户信息",
new Color(11, 245, 220),new ImageIcon("lib/6.jpg")));
infoPanel.add(createDashboardCard("销售订单",getSalesOrderCount(),"销售订单信息",
new Color(154, 20, 232),new ImageIcon("lib/7.jpg")));
infoPanel.add(createDashboardCard("销售发货",getSalesShipmentCount(),"销售发货信息",
new Color(196, 120, 50),new ImageIcon("lib/8.jpg")));
panel.add(infoPanel, BorderLayout.CENTER);
// 添加底部快捷功能面板
JPanel quickPanel = new JPanel(new BorderLayout());
quickPanel.setBackground(new Color(240, 240, 240));
// 设置快速面板的边框由一个复合边框组成该复合边框包含一个顶部有1像素宽灰色边框和一个内部有20像素上下及35像素左右的空白边框
quickPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(220, 220, 220)),
BorderFactory.createEmptyBorder(20, 35, 20, 35)
));
JLabel quickTitle = new JLabel("快捷功能");
quickTitle.setFont(new Font("微软雅黑", Font.BOLD, 18));
quickTitle.setForeground(new Color(70, 70, 70));
// 设置快速标题的边框底部留有15像素的空白边距
quickTitle.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0));
quickPanel.add(quickTitle, BorderLayout.NORTH);
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
buttonsPanel.setOpaque(false);
// 添加快捷按钮
JButton addProductBtn = createQuickButton("添加商品", new Color(41, 128, 185));
addProductBtn.addActionListener(e -> handleAddButtonClick());
buttonsPanel.add(addProductBtn);
JButton queryProductBtn = createQuickButton("查询商品", new Color(39, 174, 96));
queryProductBtn.addActionListener(e -> new SelectProduct());
buttonsPanel.add(queryProductBtn);
JButton addInventoryBtn = createQuickButton("添加库存", new Color(142, 68, 173));
addInventoryBtn.addActionListener(e -> new AddInvenTory());
buttonsPanel.add(addInventoryBtn);
JButton manageWarehouseBtn = createQuickButton("管理仓库", new Color(211, 84, 0));
manageWarehouseBtn.addActionListener(e -> WarehouseInfo.showWarehouseInfoPage());
buttonsPanel.add(manageWarehouseBtn);
JButton customerBtn = createQuickButton("客户管理", new Color(98, 32, 238));
customerBtn.addActionListener(e -> CustomersInfo.showCustomersPage());
buttonsPanel.add(customerBtn);
JButton supplierBtn = createQuickButton("供应商管理", new Color(226, 200, 72));
supplierBtn.addActionListener(e -> SupplierInfo.showSupplierInfoPage());
buttonsPanel.add(supplierBtn);
quickPanel.add(buttonsPanel, BorderLayout.CENTER);
panel.add(quickPanel, BorderLayout.SOUTH);
return panel;
}
/**
*
*/
private static JButton createQuickButton(String text, Color color) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 14));
button.setForeground(Color.WHITE);
button.setBackground(color);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
button.setPreferredSize(new Dimension(150, 40));
// 添加鼠标悬停效果
Color darkerColor = color.darker();
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
button.setBackground(darkerColor);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
button.setBackground(color);
}
});
return button;
}
/**
*
*/
private static JPanel createDashboardCard(String title, String value, String description, Color color, ImageIcon icon) {
// 设置基本信息类的描述信息
BasicMassage.description = description;
// 创建一个新的JPanel使用BorderLayout布局管理器并设置水平和垂直间距
JPanel card = new JPanel(new BorderLayout(10, 0));
// 设置JPanel的背景颜色为白色
card.setBackground(Color.WHITE);
// 设置JPanel的边框内侧为一个1像素宽的浅灰色实线边框外侧为一个15像素的空边框以增加内边距
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(15, 15, 15, 15)
));
// 左侧图标区域
JPanel leftStrip = new JPanel(new BorderLayout());
leftStrip.setPreferredSize(new Dimension(80, 0));
leftStrip.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
if (icon != null && icon.getIconWidth() > 0) {
try {
// 创建一个自定义的JLabel用于绘制缩放后的图标
JLabel iconLabel = new JLabel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 获取图片并缩放到面板大小
Image img = icon.getImage();
// 创建一个Graphics2D对象并设置其渲染提示以提高图像质量和平滑度
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 在当前组件上绘制图像,图像的左上角位于(0,0),宽度和高度调整为组件的宽度和高度
g2d.drawImage(img, 0, 0, getWidth(), getHeight(), this);
g2d.dispose();
}
};
iconLabel.setMinimumSize(new Dimension(80, 100));
iconLabel.setPreferredSize(new Dimension(80, 100));
leftStrip.add(iconLabel, BorderLayout.CENTER);
} catch (Exception e) {
System.err.println("图标加载失败: " + e.getMessage());
}
} else {
leftStrip.setBackground(color);
}
card.add(leftStrip, BorderLayout.WEST);
// 右侧内容
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.setOpaque(false);
contentPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 5));
JLabel titleLabel = new JLabel(title);
titleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
titleLabel.setForeground(new Color(100, 100, 100));
titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPanel.add(titleLabel);
contentPanel.add(Box.createVerticalStrut(10));
JLabel valueLabel = new JLabel(value);
valueLabel.setFont(new Font("微软雅黑", Font.BOLD, 36));
valueLabel.setForeground(color);
valueLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPanel.add(valueLabel);
contentPanel.add(Box.createVerticalGlue());
JPanel linkPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
linkPanel.setOpaque(false);
linkPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPanel.add(linkPanel);
card.add(contentPanel, BorderLayout.CENTER);
// 为整个卡片添加点击事件
card.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 鼠标点击时导航到详情页
navigateToDetailPage(description);
}
@Override
public void mouseEntered(MouseEvent e) {
// 鼠标进入时设置卡片边框
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(color, 1),
BorderFactory.createEmptyBorder(15, 15, 15, 15)
));
}
@Override
public void mouseExited(MouseEvent e) {
// 当鼠标退出组件时,设置卡片的边框为一个由实线边框和空白边框组成的复合边框
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(15, 15, 15, 15)
));
}
});
return card;
}
/**
*
* @param description
*/
private static void navigateToDetailPage(String description) {
updateStatusMessage("正在打开: " + description);
switch (description) {
case "商品基础信息":
BasicMassageInfo.showProductInfoPage();
break;
case "商品分类":
ProductCategoryInfo.showCategoryInfoPage();
break;
case "仓库信息":
WarehouseInfo.showWarehouseInfoPage();
break;
case "库存记录":
InvenToryInfo.showInventoryInfoPage();
break;
case "供应商信息":
SupplierInfo.showSupplierInfoPage();
break;
case "客户信息":
CustomersInfo.showCustomersPage();
break;
case "销售订单信息":
SalesInfo.showSalesInfoPage();
break;
case "销售发货信息":
SalesShipmentsInfo.showSalesShipmentsPage();
break;
default:
updateStatusMessage("未找到对应的页面: " + description);
break;
}
}
/**
*
* @return
*/
private static String getProductCount() {
List<Products> products = ProductService.selectAllProducts();
return String.valueOf(products.size());
}
/**
*
* @return
*/
private static String getCategoryCount() {
List<ProductCategories> categories = SelectCateGory.selectAllCateGory();
return String.valueOf(categories.size());
}
/**
*
* @return
*/
private static String getWarehouseCount() {
try {
List<com.xky.pojo.Warehouses> warehouses = WarehouseService.selectAllWarehouses();
return String.valueOf(warehouses.size());
} catch (Exception e) {
return "0";
}
}
/**
*
* @return
*/
private static String getInventoryCount() {
try {
List<com.xky.pojo.Inventory> inventories = SelectInvenTory.selectAllInventory();
return String.valueOf(inventories.size());
} catch (Exception e) {
return "0";
}
}
/**
*
* @return
*/
private static String getSupplierCount() {
List<Supplier> supplierList = SelectSupplier.selectAll();
return String.valueOf(supplierList.size());
}
/**
*
* @return
*/
private static String getCustomerCount() {
List<Customers> customersList = SelectCustomers.selectAllCustomers();
return String.valueOf(customersList.size());
}
/**
*
* @return
*/
private static String getSalesOrderCount() {
List<SalesOrders> salesOrders = SelectSalesOrder.selectAll();
return String.valueOf(salesOrders.size());
}
/**
*
* @return
*/
private static String getSalesShipmentCount() {
List<SalesShipments> salesShipments = SelectSalesShipment.selectAll();
return String.valueOf(salesShipments.size());
}
/**
*
* @param refreshAction
* @return
*/
//Runnable refreshAction:可运行的刷新操作
public static JPanel createProductInfoPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("商品基本信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 1));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createProductTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(_ -> {
new AddProduct();
if (refreshAction != null) {
refreshAction.run();
}
});
deleteButton.addActionListener(_ -> {
new DeleteProduct();
if (refreshAction != null) {
refreshAction.run();
}
});
updateButton.addActionListener(_ -> {
new UpdateProduct();
if (refreshAction != null) {
refreshAction.run();
}
});
queryButton.addActionListener(_ -> {
SelectProduct selectProduct = new SelectProduct();
selectProduct.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
// 使用getId()静态方法获取ID
Integer id = SelectProduct.getId();
if (id != null){
List<Products> products = ProductService.selectProductById(id);
if (!products.isEmpty()) {
// 清空表格并只显示查询到的商品
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
updateTableData(table, products);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
System.out.println("停止自动刷新");
autoRefreshTimer.stop();
}
}
}
}
});
});
refreshButton.addActionListener(e -> {
System.out.println("你点击了刷新按钮");
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
if (refreshAction != null) {
refreshAction.run();
updateStatusMessage("商品数据已刷新");
}
// 重新启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
System.out.println("重新启动自动刷新");
autoRefreshTimer.start();
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createProductTable() {
String[] title = {"商品ID", "编码", "名称", "所属分类ID", "计量单位", "最小库存量", "是否上架", "创建时间", "更新时间"};
DefaultTableModel model = new DefaultTableModel(title, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(60); // 商品ID
table.getColumnModel().getColumn(1).setPreferredWidth(80); // 编码
table.getColumnModel().getColumn(2).setPreferredWidth(120); // 名称
table.getColumnModel().getColumn(3).setPreferredWidth(80); // 所属分类ID
table.getColumnModel().getColumn(4).setPreferredWidth(80); // 计量单位
table.getColumnModel().getColumn(5).setPreferredWidth(80); // 最小库存量
table.getColumnModel().getColumn(6).setPreferredWidth(80); // 是否上架
table.getColumnModel().getColumn(7).setPreferredWidth(150); // 创建时间
table.getColumnModel().getColumn(8).setPreferredWidth(150); // 更新时间
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param productsList
*/
public static void updateTableData(JTable table, List<Products> productsList) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
// 创建日期格式化器
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Products product : productsList) {
// 格式化日期时间
String createdTime = product.getCreatedTime() != null ? product.getCreatedTime().format(formatter) : "";
String updatedTime = product.getUpdatedTime() != null ? product.getUpdatedTime().format(formatter) : "";
Object[] rowData = {
product.getProductId(),
product.getProductCode(),
product.getProductName(),
product.getCategoryId(),
product.getUnitOfMeasure(),
product.getMinStockLevel(),
product.getIsActive(),
createdTime,
updatedTime
};
model.addRow(rowData);
}
}
// 添加按钮事件处理
private static void handleAddButtonClick() {
// 获取主窗口
for (Frame frame : JFrame.getFrames()) {
if (frame instanceof JFrame && frame.isVisible() && frame.getTitle().contains("商品库存管理系统")) {
break;
}
}
// 打开添加商品对话框
new AddProduct().setVisible(true);
}
}

@ -1,108 +0,0 @@
package com.xky.ui.module.productManagement;
import com.xky.pojo.Products;
import com.xky.ui.module.productManagement.select.ProductService;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.xky.ui.main.MainView.*;
public class BasicMassageInfo {
private static JTable productTable;
private static JPanel homePanel;
/**
*
*/
public static void showProductInfoPage() {
// 创建商品信息面板
// 创建一个包含产品信息的面板,并设置刷新产品数据的回调方法
JPanel productInfoPanel = BasicMassage.createProductInfoPanel(BasicMassageInfo::refreshProductData);
// 从productInfoPanel中获取CENTER位置的组件并检查该组件是否为JScrollPane的实例
Component centerComponent = productInfoPanel.getComponent(1); // 获取CENTER位置的组件
if (centerComponent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) centerComponent;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
productTable = (JTable) viewComponent;
}
}
// 更新右侧面板
rightPanel.removeAll();//移除所有现有组件
rightPanel.add(productInfoPanel, BorderLayout.CENTER);//添加产品信息面板
rightPanel.revalidate();//重新绘制界面
rightPanel.repaint();
// 注册刷新操作
registerRefreshAction("商品信息", BasicMassageInfo::refreshProductData);
// 立即刷新一次
refreshProductData();
}
/**
*
*/
static void refreshProductData() {
new SwingWorker<List<Products>, Void>() {
@Override
//SwingWorker这是一个允许在后台线程中执行任务并在任务完成后将结果安全地发布到事件调度线程的类。
// 这对于需要在 GUI 中显示长时间运行的任务的结果的情况非常有用。
protected List<Products> doInBackground() {
DefaultTableModel model = (DefaultTableModel) productTable.getModel();
model.setRowCount(0);
// 获取所有商品数据
return ProductService.selectAllProducts();
}
@Override
protected void done() {
try {
List<Products> products = get();
if (productTable != null) {
BasicMassage.updateTableData(productTable, products);
rightPanel.repaint();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"刷新失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
/**
*
*/
public static void showHomePage() {
// 取消注册刷新操作
unregisterRefreshAction();
// 如果首页面板不存在,创建一个
if (homePanel == null) {
homePanel = BasicMassage.createHomePanel();
}
// 更新右侧面板
rightPanel.removeAll();
rightPanel.add(homePanel, BorderLayout.CENTER);
rightPanel.revalidate();
rightPanel.repaint();
}
}

@ -1,73 +0,0 @@
package com.xky.ui.module.productManagement;
import com.xky.pojo.ProductCategories;
import com.xky.ui.module.productManagement.select.SelectCateGory;
import lombok.Data;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.xky.ui.main.MainView.*;
@Data
public class ProductCategoryInfo {
private static JTable categoryTable;
private static JPanel homePanel;
/**
*
*/
public static void showCategoryInfoPage() {
// 创建商品分类信息面板
JPanel categoryInfoPanel = ProductCategoryMassage.createCategoryPanel(com.xky.ui.module.productManagement.ProductCategoryInfo::refreshCategoryData);
// 获取表格组件
Component[] components = ((JScrollPane)categoryInfoPanel.getComponent(1)).getViewport().getComponents();
if (components.length > 0 && components[0] instanceof JTable) {
categoryTable = (JTable) components[0];
}
// 更新右侧面板
rightPanel.removeAll();
rightPanel.add(categoryInfoPanel, BorderLayout.CENTER);
rightPanel.revalidate();
rightPanel.repaint();
// 注册刷新操作
registerRefreshAction("商品分类", ProductCategoryInfo::refreshCategoryData);
// 立即刷新一次
refreshCategoryData();
}
/**
*
*/
static void refreshCategoryData() {
new SwingWorker<List<ProductCategories>, Void>() {
@Override
protected List<ProductCategories> doInBackground() {
DefaultTableModel model = (DefaultTableModel) categoryTable.getModel();
model.setRowCount(0);
return SelectCateGory.selectAllCateGory();
}
@Override
protected void done() {
try {
List<ProductCategories> categoryList = get();
if (categoryTable != null) {
ProductCategoryMassage.updateTableData(categoryTable, categoryList);
rightPanel.repaint();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"刷新失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
}

@ -1,413 +0,0 @@
package com.xky.ui.module.productManagement;
import com.xky.pojo.ProductCategories;
import com.xky.ui.module.productManagement.select.SelectCateGory;
import com.xky.ui.module.productManagement.add.AddCategory;
import com.xky.ui.module.productManagement.delete.DeleteCategory;
import com.xky.ui.module.productManagement.update.UpdateCategory;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
/**
*
*/
public class ProductCategoryMassage {
private static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(250, 250, 250);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
/**
*
* @param refreshAction
* @return
*/
public static JPanel createCategoryPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("商品分类信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createCategoryTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
new AddCategory();
});
deleteButton.addActionListener(e -> {
new DeleteCategory();
});
updateButton.addActionListener(e -> {
new UpdateCategory();
});
queryButton.addActionListener(e -> {
// 创建查询对话框
showSearchDialog();
});
refreshButton.addActionListener(e -> {
System.out.println("你点击了刷新按钮");
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
if (refreshAction != null) {
refreshAction.run();
updateStatusMessage("分类数据已刷新");
}
// 重新启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
System.out.println("重新启动自动刷新");
autoRefreshTimer.start();
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createCategoryTable() {
String[] title = {"分类ID", "分类名称", "父分类ID", "是否启用", "创建时间", "更新时间"};
DefaultTableModel model = new DefaultTableModel(title, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(80); // 分类ID
table.getColumnModel().getColumn(1).setPreferredWidth(150); // 分类名称
table.getColumnModel().getColumn(2).setPreferredWidth(80); // 父分类ID
table.getColumnModel().getColumn(3).setPreferredWidth(80); // 是否启用
table.getColumnModel().getColumn(4).setPreferredWidth(150); // 创建时间
table.getColumnModel().getColumn(5).setPreferredWidth(150); // 更新时间
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param productCategoriesList null
*/
public static void updateTableData(JTable table, List<ProductCategories> productCategoriesList) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0); // 清空原有数据
if (productCategoriesList == null || productCategoriesList.isEmpty()) {
return;
}
// 创建日期格式化器
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (ProductCategories category : productCategoriesList) {
// 格式化日期时间
String createdTime = category.getCreatedTime() != null ? category.getCreatedTime().format(formatter) : "";
String updatedTime = category.getUpdatedTime() != null ? category.getUpdatedTime().format(formatter) : "";
Object[] rowData = {
category.getCategoryId(),
category.getCategoryName(),
category.getParentId(),
category.getIsActive() != null && category.getIsActive().equals("1") ? "已启用" : "已禁用",
createdTime,
updatedTime
};
model.addRow(rowData);
}
model.fireTableDataChanged(); // 触发表格刷新
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询商品分类", true);
searchDialog.setSize(600, 450);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
topPanel.setBackground(SECONDARY_COLOR);
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.setBackground(SECONDARY_COLOR);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按ID查询", true);
JRadioButton nameRadio = new JRadioButton("按名称模糊查询");
idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
nameRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
idRadio.setBackground(SECONDARY_COLOR);
nameRadio.setBackground(SECONDARY_COLOR);
buttonGroup.add(idRadio);
buttonGroup.add(nameRadio);
radioPanel.add(idRadio);
radioPanel.add(nameRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
searchPanel.setBackground(SECONDARY_COLOR);
JLabel searchLabel = new JLabel("查询条件: ");
searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
searchLabel.setForeground(PRIMARY_COLOR);
JTextField searchField = new JTextField(20);
searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
searchField.setPreferredSize(new Dimension(200, 30));
JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);
JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
searchFieldPanel.setBackground(SECONDARY_COLOR);
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 模糊查询支持部分分类名称");
tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"分类ID", "分类名称", "父分类ID", "是否启用", "创建时间", "更新时间"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
resultTable.setFont(new Font("微软雅黑", Font.BOLD, 15));
resultTable.setBackground(PRIMARY_COLOR);
resultTable.setForeground(Color.BLACK);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
scrollPane.getViewport().setBackground(Color.WHITE);
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(e -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<ProductCategories> results;
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
results = SelectCateGory.selectCateGoryById(id);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else {
results = SelectCateGory.searchCategoriesByKeyword(searchText);
}
// 更新表格数据
tableModel.setRowCount(0);
if (results != null && !results.isEmpty()) {
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (ProductCategories category : results) {
String createdTime = category.getCreatedTime() != null ? category.getCreatedTime().format(formatter) : "";
String updatedTime = category.getUpdatedTime() != null ? category.getUpdatedTime().format(formatter) : "";
Object[] rowData = {
category.getCategoryId(),
category.getCategoryName(),
category.getParentId(),
category.getIsActive() != null && category.getIsActive().equals("1") ? "已启用" : "已禁用",
createdTime,
updatedTime
};
tableModel.addRow(rowData);
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int categoryId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的分类数据
List<ProductCategories> selectedCategory = SelectCateGory.selectCateGoryById(categoryId);
if (selectedCategory != null && !selectedCategory.isEmpty()) {
// 清空主表格并只显示选中的分类
DefaultTableModel mainModel = (DefaultTableModel) table.getModel();
mainModel.setRowCount(0);
updateTableData(table, selectedCategory);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
System.out.println("停止自动刷新");
autoRefreshTimer.stop();
}
// 更新状态消息
updateStatusMessage("已选择分类: " + selectedCategory.get(0).getCategoryName());
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
}

@ -1,307 +0,0 @@
package com.xky.ui.module.productManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class AddCategory extends JFrame {
private JPanel jPanel1, jPanel2, jPanel3;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
public AddCategory() {
setTitle("添加商品分类");
setSize(500, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init() {
setLayout(new BorderLayout()); // 设置主布局
// 创建主面板并设置背景渐变
JPanel mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 标题面板
jPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jPanel2.setOpaque(false);
JLabel jLabel = new JLabel("添加商品分类信息");
jLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
jLabel.setForeground(PRIMARY_COLOR);
jPanel2.add(jLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setOpaque(false);
titlePanel.add(jPanel2, BorderLayout.CENTER);
titlePanel.add(separator, BorderLayout.SOUTH);
titlePanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(titlePanel, BorderLayout.NORTH);
// 表单面板
jPanel1 = new JPanel(new GridBagLayout());
jPanel1.setOpaque(false);
JLabel[] labels = new JLabel[]{
new JLabel("分类ID *"),
new JLabel("分类名称 *"),
new JLabel("父分类ID *"),
new JLabel("是否启用 *")
};
// 创建文本框数组
textFields = new JTextField[3];
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
gbc.insets = new Insets(10, 10, 10, 10);
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
// 创建圆角边框的文本框样式
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.anchor = GridBagConstraints.WEST;
labels[i].setFont(labelFont);
labels[i].setForeground(PRIMARY_COLOR);
jPanel1.add(labels[i], gbc);
gbc.gridx = 1;
gbc.weightx = 1.0;
if (i < 3) {
// 前三个是文本框分类ID、分类名称、父分类ID
textFields[i] = new JTextField(20);
textFields[i].setFont(inputFont);
textFields[i].setPreferredSize(new Dimension(250, 35));
jPanel1.add(textFields[i], gbc);
} else {
// 是否启用下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(inputFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
jPanel1.add(isActiveComboBox, gbc);
}
}
// 添加表单面板到卡片容器
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formCard.add(jPanel1, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
// 按钮面板
jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
jPanel3.setOpaque(false);
JButton submitButton = new JButton("提交");
submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
submitButton.setPreferredSize(new Dimension(120, 40));
submitButton.setBackground(BUTTON_COLOR);
submitButton.setForeground(Color.WHITE);
submitButton.setFocusPainted(false);
submitButton.setBorderPainted(false);
JButton resetButton = new JButton("重置");
resetButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
resetButton.setPreferredSize(new Dimension(120, 40));
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.setForeground(Color.WHITE);
resetButton.setFocusPainted(false);
resetButton.setBorderPainted(false);
jPanel3.add(submitButton);
jPanel3.add(resetButton);
mainPanel.add(jPanel3, BorderLayout.SOUTH);
add(mainPanel);
// 重置按钮事件
resetButton.addActionListener(_ -> {
for (JTextField field : textFields) {
field.setText("");
}
isActiveComboBox.setSelectedIndex(0);
});
// 提交按钮事件
submitButton.addActionListener(e -> {
try {
// 获取输入值
String categoryIdStr = textFields[0].getText().trim();
String categoryName = textFields[1].getText().trim();
String parentIdStr = textFields[2].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
// 进行输入校验
if (categoryIdStr.isEmpty() || categoryName.isEmpty() || parentIdStr.isEmpty()) {
showValidationError("所有字段都为必填项,请完成表单");
return;
}
try {
Integer categoryId = Integer.valueOf(categoryIdStr);
Integer parentId = Integer.valueOf(parentIdStr);
// 进行输入校验
if (!validateInputs(categoryId, categoryName, parentId, isActive)) {
return; // 如果校验不通过,直接返回
}
if (addCategory(categoryId, categoryName, parentId, isActive)) {
JOptionPane.showMessageDialog(AddCategory.this, "商品分类添加成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(AddCategory.this, "商品分类添加失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
} catch (NumberFormatException ex) {
showValidationError("分类ID和父分类ID必须是数字");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(AddCategory.this, "发生错误:" + ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
}
});
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
/**
*
* @return truefalse
*/
private boolean validateInputs(Integer categoryId, String categoryName, Integer parentId, String isActive) {
// 1. 校验分类ID
if (categoryId <= 0) {
showValidationError("分类ID必须大于0");
return false;
}
// 2. 校验分类名称
if (categoryName.isEmpty()) {
showValidationError("商品分类名称不能为空");
return false;
}
// 3. 校验父分类ID
if (parentId < 0) {
showValidationError("父分类ID不能小于0");
return false;
}
// 所有校验通过
return true;
}
/**
*
* @param message
*/
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
public boolean addCategory(Integer categoryId, String categoryName, Integer parentId, String isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"INSERT INTO product_categories(category_id, category_name, parent_id, is_active, updated_time, created_time) VALUES (?, ?, ?, ?, NOW(), NOW())",
Statement.RETURN_GENERATED_KEYS
);
preparedStatement.setInt(1, categoryId);
preparedStatement.setString(2, categoryName);
preparedStatement.setInt(3, parentId);
preparedStatement.setString(4, isActive);
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("影响行数为" + i + "添加成功!");
return true;
} else {
System.out.println("影响行数为" + i + "添加失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
try {
// 尝试使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(AddCategory::new);
}
}

@ -1,367 +0,0 @@
package com.xky.ui.module.productManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class AddProduct extends JFrame {
private JPanel jPanel1, jPanel2, jPanel3;
private JTextField[] textFields;
private JComboBox<String> unitComboBox;
private JComboBox<String> isActiveComboBox;
// 预定义的有效计量单位列表
private static final Set<String> VALID_UNITS = new HashSet<>(Arrays.asList(
"个", "箱", "袋", "瓶", "千克", "克", "吨", "升", "毫升", "米", "厘米", "套",
"件", "双", "台", "包", "盒", "桶", "卷", "张", "只", "块", "片", "支"
));
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
public AddProduct() {
setTitle("添加商品");
setSize(500, 650);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init() {
setLayout(new BorderLayout()); // 设置主布局
// 创建主面板并设置背景渐变
JPanel mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 标题面板
jPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jPanel2.setOpaque(false);
JLabel jLabel = new JLabel("添加商品信息");
jLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
jLabel.setForeground(PRIMARY_COLOR);
jPanel2.add(jLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setOpaque(false);
titlePanel.add(jPanel2, BorderLayout.CENTER);
titlePanel.add(separator, BorderLayout.SOUTH);
titlePanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(titlePanel, BorderLayout.NORTH);
// 表单面板
jPanel1 = new JPanel(new GridBagLayout());
jPanel1.setOpaque(false);
JLabel[] labels = new JLabel[]{
new JLabel("商品编码 *"),
new JLabel("商品名称 *"),
new JLabel("所属分类ID *"),
new JLabel("计量单位 *"),
new JLabel("库存量 *"),
new JLabel("是否上架 *")
};
// 创建正确大小的文本框数组
textFields = new JTextField[4];
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
gbc.insets = new Insets(10, 10, 10, 10);
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
// 创建圆角边框的文本框样式
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.anchor = GridBagConstraints.WEST;
labels[i].setFont(labelFont);
labels[i].setForeground(PRIMARY_COLOR);
jPanel1.add(labels[i], gbc);
gbc.gridx = 1;
gbc.weightx = 1.0;
if (i < 3) {
// 前三个是文本框商品编码、商品名称、分类ID
textFields[i] = new JTextField(20);
textFields[i].setFont(inputFont);
textFields[i].setPreferredSize(new Dimension(250, 35));
jPanel1.add(textFields[i], gbc);
} else if (i == 3) {
// 计量单位下拉框
unitComboBox = new JComboBox<>(VALID_UNITS.toArray(new String[0]));
unitComboBox.setFont(inputFont);
unitComboBox.setPreferredSize(new Dimension(250, 35));
unitComboBox.setBackground(Color.WHITE);
jPanel1.add(unitComboBox, gbc);
} else if (i == 4) {
// 库存量文本框
textFields[3] = new JTextField(20);
textFields[3].setFont(inputFont);
textFields[3].setPreferredSize(new Dimension(250, 35));
jPanel1.add(textFields[3], gbc);
} else {
// 是否上架下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(inputFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
jPanel1.add(isActiveComboBox, gbc);
}
}
// 添加表单面板到卡片容器
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formCard.add(jPanel1, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
// 按钮面板
jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
jPanel3.setOpaque(false);
JButton submitButton = new JButton("提交");
submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
submitButton.setPreferredSize(new Dimension(120, 40));
submitButton.setBackground(BUTTON_COLOR);
submitButton.setForeground(Color.WHITE);
submitButton.setFocusPainted(false);
submitButton.setBorderPainted(false);
JButton resetButton = new JButton("重置");
resetButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
resetButton.setPreferredSize(new Dimension(120, 40));
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.setForeground(Color.WHITE);
resetButton.setFocusPainted(false);
resetButton.setBorderPainted(false);
jPanel3.add(submitButton);
jPanel3.add(resetButton);
mainPanel.add(jPanel3, BorderLayout.SOUTH);
add(mainPanel);
// 重置按钮事件
resetButton.addActionListener(_ -> {
for (JTextField field : textFields) {
field.setText("");
}
unitComboBox.setSelectedIndex(0);
isActiveComboBox.setSelectedIndex(0);
});
// 提交按钮事件
submitButton.addActionListener(e -> {
try {
// 获取输入值
String productCode = textFields[0].getText().trim();
String productName = textFields[1].getText().trim();
String categoryIdStr = textFields[2].getText().trim();
String unitOfMeasure = (String) unitComboBox.getSelectedItem();
String minStockLevelStr = textFields[3].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
// 进行输入校验
if (!validateInputs(productCode, productName, categoryIdStr,
unitOfMeasure, minStockLevelStr, isActive)) {
return; // 如果校验不通过,直接返回
}
// 校验通过后,转换数据类型
Integer categoryId = Integer.valueOf(categoryIdStr);
Integer minStockLevel = Integer.valueOf(minStockLevelStr);
if (addProduct(productCode, productName, categoryId, unitOfMeasure, minStockLevel, isActive)) {
JOptionPane.showMessageDialog(AddProduct.this, "商品信息添加成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(AddProduct.this, "商品信息添加失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(AddProduct.this, "发生错误:" + ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
}
});
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
/**
*
* @return truefalse
*/
private boolean validateInputs(String productCode, String productName, String categoryIdStr,
String unitOfMeasure, String minStockLevelStr, String isActive) {
// 1. 校验商品编码
if (productCode.isEmpty()) {
showValidationError("商品编码不能为空");
return false;
}
// 2. 校验商品名称
if (productName.isEmpty()) {
showValidationError("商品名称不能为空");
return false;
}
// 3. 校验分类ID
if (categoryIdStr.isEmpty()) {
showValidationError("分类ID不能为空");
return false;
}
try {
Integer.parseInt(categoryIdStr);
} catch (NumberFormatException e) {
showValidationError("分类ID必须是数字");
return false;
}
// 4. 校验计量单位
if (unitOfMeasure == null || unitOfMeasure.isEmpty()) {
showValidationError("计量单位不能为空");
return false;
}
// 5. 校验最低库存
if (minStockLevelStr.isEmpty()) {
showValidationError("库存量不能为空");
return false;
}
try {
int minStock = Integer.parseInt(minStockLevelStr);
if (minStock < 0) {
showValidationError("库存量不能小于0");
return false;
}
} catch (NumberFormatException e) {
showValidationError("库存量必须是数字");
return false;
}
// 所有校验通过
return true;
}
/**
*
* @param message
*/
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
/**
*
* @param productCode
* @param productName
* @param categoryId
* @param unitOfMeasure
* @param minStockLevel
* @param isActive
* @return
*/
public boolean addProduct(String productCode, String productName, Integer categoryId, String unitOfMeasure, Integer minStockLevel, String isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("insert into products(product_code, product_name, category_id, unit_of_measure, min_stock_level, is_active, created_time, updated_time) values (?,?,?,?,?,?,now(),now())", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, productCode);
preparedStatement.setString(2, productName);
preparedStatement.setInt(3, categoryId);
preparedStatement.setString(4, unitOfMeasure);
preparedStatement.setInt(5, minStockLevel);
preparedStatement.setString(6, isActive);
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("影响行数为" + i + "添加成功!");
return true;
} else {
System.out.println("影响行数为" + i + "添加失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
try {
// 尝试使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(AddProduct::new);
}
}

@ -1,263 +0,0 @@
package com.xky.ui.module.productManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static com.xky.ui.module.productManagement.select.SelectCateGory.selectAllCateGoryById;
public class DeleteCategory extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteCategory(){
setTitle("删除界面");
setSize(320,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的商品的分类ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有商品的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有分类商品");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个商品删除按钮事件
jButton.addActionListener(e -> {
Integer id = Integer.valueOf(jTextField.getText().trim());
System.out.println("你点击了确定按钮!");
if (id == 0){
JOptionPane.showMessageDialog(null, "请输入你要删除的商品的ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该商品信息吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION){
if (selectAllCateGoryById(id)){
deleteCategory(id);
JOptionPane.showMessageDialog(null, "该商品信息删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该商品ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有商品按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有商品信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有商品的操作
if (deleteAllProducts()) {
JOptionPane.showMessageDialog(
null,
"所有商品信息已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有商品信息失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
*
* @param id ID
* @return
*/
public boolean deleteCategory(Integer id){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM product_categories WHERE category_id = ?");
preparedStatement.setInt(1,id);
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("影响行数为" + i + "删除成功!");
return true;
} else {
System.out.println("影响行数为" + i + "删除失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllProducts() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM products");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("删除了" + rowsAffected + "条商品记录");
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteCategory::new);
}
}

@ -1,280 +0,0 @@
package com.xky.ui.module.productManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DeleteProduct extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteProduct(){
setTitle("删除界面");
setSize(280,200); // 增加高度以容纳新按钮
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的商品的ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(250, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有商品的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有商品");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个商品删除按钮事件
jButton.addActionListener(e -> {
String id = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (id.isEmpty()){
JOptionPane.showMessageDialog(DeleteProduct.this, "请输入你要删除的商品的ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
int i = JOptionPane.showConfirmDialog(DeleteProduct.this, "你确定要删除该商品信息吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION){
if (selectById(id)){
deleteProduct(id);
JOptionPane.showMessageDialog(DeleteProduct.this, "该商品信息删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(DeleteProduct.this, "找不到该商品ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有商品按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
DeleteProduct.this,
"警告:此操作将删除所有商品信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
DeleteProduct.this,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有商品的操作
if (deleteAllProducts()) {
JOptionPane.showMessageDialog(
DeleteProduct.this,
"所有商品信息已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
DeleteProduct.this,
"删除所有商品信息失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
DeleteProduct.this,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
*
* @param productId ID
* @return
*/
public boolean deleteProduct(String productId){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM products WHERE product_id = ?");
preparedStatement.setString(1, productId);
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("影响行数为" + i + "删除成功!");
return true;
} else {
System.out.println("影响行数为" + i + "删除失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllProducts() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM products");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("删除了" + rowsAffected + "条商品记录");
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public Boolean selectById(String productId){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM products WHERE product_id = ?");
preparedStatement.setString(1, productId);
resultSet = preparedStatement.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteProduct::new);
}
}

@ -1,161 +0,0 @@
package com.xky.ui.module.productManagement.select;
import com.xky.pojo.Products;
import com.xky.utils.DBUtils;
import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class ProductService {
/**
*
* @return
*/
public static List<Products> selectAllProducts() {
List<Products> productsList = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM products");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Products product = new Products();
product.setProductId(resultSet.getInt("product_id"));
product.setProductCode(resultSet.getString("product_code"));
product.setProductName(resultSet.getString("product_name"));
product.setCategoryId(resultSet.getInt("category_id"));
product.setUnitOfMeasure(resultSet.getString("unit_of_measure"));
product.setMinStockLevel(resultSet.getInt("min_stock_level"));
product.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
product.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
product.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
productsList.add(product);
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return productsList;
}
/**
* ID
* @param id ID
* @return
*/
public static List<Products> selectProductById(Integer id) {
List<Products> productsList = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM products WHERE product_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Products product = new Products();
product.setProductId(resultSet.getInt("product_id"));
product.setProductCode(resultSet.getString("product_code"));
product.setProductName(resultSet.getString("product_name"));
product.setCategoryId(resultSet.getInt("category_id"));
product.setUnitOfMeasure(resultSet.getString("unit_of_measure"));
product.setMinStockLevel(resultSet.getInt("min_stock_level"));
product.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
product.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
product.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
productsList.add(product);
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return productsList;
}
/**
*
* @param keyword
* @return
*/
public static List<Products> searchProductsByKeyword(String keyword) {
List<Products> productsList = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
// 使用LIKE进行模糊查询支持商品名称和商品编码
preparedStatement = connection.prepareStatement(
"SELECT * FROM products WHERE product_name LIKE ? OR product_code LIKE ?"
);
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
preparedStatement.setString(2, searchPattern);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Products product = new Products();
product.setProductId(resultSet.getInt("product_id"));
product.setProductCode(resultSet.getString("product_code"));
product.setProductName(resultSet.getString("product_name"));
product.setCategoryId(resultSet.getInt("category_id"));
product.setUnitOfMeasure(resultSet.getString("unit_of_measure"));
product.setMinStockLevel(resultSet.getInt("min_stock_level"));
product.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
product.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
product.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
productsList.add(product);
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return productsList;
}
}

@ -1,157 +0,0 @@
package com.xky.ui.module.productManagement.select;
import com.xky.pojo.ProductCategories;
import com.xky.utils.DBUtils;
import lombok.Getter;
import lombok.Setter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Setter
@Getter
public class SelectCateGory {
public static List<ProductCategories> selectAllCateGory(){
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<ProductCategories> productCategoriesList = new ArrayList<>();
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("select * from product_categories");
resultSet = preparedStatement.executeQuery();
// 直接使用while循环处理结果集
while (resultSet.next()){
ProductCategories productCategories = new ProductCategories();
productCategories.setCategoryId(resultSet.getInt("category_id"));
productCategories.setCategoryName(resultSet.getString("category_name"));
productCategories.setParentId(resultSet.getInt("parent_id"));
productCategories.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
productCategories.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
productCategories.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
productCategoriesList.add(productCategories);
}
return productCategoriesList;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection,preparedStatement,resultSet);
}
}
public static Boolean selectAllCateGoryById(Integer id){
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("select * from product_categories where category_id = ?");
preparedStatement.setInt(1,id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
return true;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
public static List<ProductCategories> selectCateGoryById(Integer id){
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<ProductCategories> productCategoriesList = new ArrayList<>();
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("select * from product_categories where category_id = ?");
preparedStatement.setInt(1,id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
ProductCategories productCategories = new ProductCategories();
productCategories.setCategoryId(resultSet.getInt("category_id"));
productCategories.setCategoryName(resultSet.getString("category_name"));
productCategories.setParentId(resultSet.getInt("parent_id"));
productCategories.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
productCategories.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
productCategories.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
productCategoriesList.add(productCategories);
}
return productCategoriesList;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection,preparedStatement,resultSet);
}
}
/**
*
* @param keyword
* @return
*/
public static List<ProductCategories> searchCategoriesByKeyword(String keyword) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<ProductCategories> categoriesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
// 使用LIKE进行模糊查询
preparedStatement = connection.prepareStatement(
"SELECT * FROM product_categories WHERE category_name LIKE ?"
);
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
ProductCategories category = new ProductCategories();
category.setCategoryId(resultSet.getInt("category_id"));
category.setCategoryName(resultSet.getString("category_name"));
category.setParentId(resultSet.getInt("parent_id"));
category.setIsActive(resultSet.getString("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
category.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
category.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
categoriesList.add(category);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return categoriesList;
}
}

@ -1,312 +0,0 @@
package com.xky.ui.module.productManagement.select;
import com.xky.pojo.Products;
import lombok.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
@Setter
public class SelectProduct extends JFrame {
@Getter
private static Integer Id;
private final ProductService productService;
private JTextField searchField;
private JRadioButton idSearchRadio;
private JRadioButton nameSearchRadio;
private JTable resultTable;
private DefaultTableModel tableModel;
private JScrollPane scrollPane;
private boolean showingResults = false;
public SelectProduct(){
setTitle("查询商品");
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
productService = new ProductService();
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
// 创建搜索面板
JPanel searchPanel = createSearchPanel();
mainPanel.add(searchPanel, BorderLayout.NORTH);
// 创建结果表格
createResultTable();
mainPanel.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = createButtonPanel();
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel, BorderLayout.CENTER);
}
private JPanel createSearchPanel() {
JPanel panel = new JPanel(new BorderLayout(5, 5));
panel.setBorder(new EmptyBorder(0, 0, 10, 0));
// 创建搜索类型选择面板
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
idSearchRadio = new JRadioButton("按ID查询");
idSearchRadio.setSelected(true);
nameSearchRadio = new JRadioButton("按名称/编码查询");
ButtonGroup group = new ButtonGroup();
group.add(idSearchRadio);
group.add(nameSearchRadio);
radioPanel.add(idSearchRadio);
radioPanel.add(nameSearchRadio);
panel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索框面板
JPanel searchBoxPanel = new JPanel(new BorderLayout(5, 0));
JLabel searchLabel = new JLabel("查询条件:");
searchLabel.setFont(new Font("黑体", Font.BOLD, 14));
searchBoxPanel.add(searchLabel, BorderLayout.WEST);
searchField = new JTextField();
searchField.setFont(new Font("宋体", Font.PLAIN, 14));
searchBoxPanel.add(searchField, BorderLayout.CENTER);
JButton searchButton = new JButton("搜索");
searchButton.setBackground(Color.PINK);
searchButton.addActionListener(e -> performSearch());
searchBoxPanel.add(searchButton, BorderLayout.EAST);
panel.add(searchBoxPanel, BorderLayout.CENTER);
// 添加提示标签
JLabel tipLabel = new JLabel("提示: 模糊查询支持部分商品名称或编码");
tipLabel.setFont(new Font("宋体", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
panel.add(tipLabel, BorderLayout.SOUTH);
// 添加搜索框输入监听器,按回车时执行搜索
searchField.addActionListener(e -> performSearch());
// 添加搜索模式切换时的监听器
ActionListener radioListener = e -> {
if (idSearchRadio.isSelected()) {
tipLabel.setText("提示: 请输入商品ID");
searchField.getDocument().removeDocumentListener(documentListener);
} else {
tipLabel.setText("提示: 模糊查询支持部分商品名称或编码");
searchField.getDocument().addDocumentListener(documentListener);
}
};
idSearchRadio.addActionListener(radioListener);
nameSearchRadio.addActionListener(radioListener);
return panel;
}
private void createResultTable() {
// 创建表格模型
String[] columnNames = {"商品ID", "商品编码", "商品名称", "分类ID", "计量单位", "最小库存", "是否激活"};
tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
resultTable = new JTable(tableModel);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setRowHeight(25);
resultTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14));
// 设置列宽
resultTable.getColumnModel().getColumn(0).setPreferredWidth(100); // 商品ID
resultTable.getColumnModel().getColumn(1).setPreferredWidth(100); // 商品编码
resultTable.getColumnModel().getColumn(2).setPreferredWidth(100); // 商品名称
resultTable.getColumnModel().getColumn(3).setPreferredWidth(100); // 分类ID
resultTable.getColumnModel().getColumn(4).setPreferredWidth(100); // 计量单位
resultTable.getColumnModel().getColumn(5).setPreferredWidth(100); // 最小库存
resultTable.getColumnModel().getColumn(6).setPreferredWidth(100); // 是否激活
// 添加表格点击事件
resultTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) { // 双击
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
Id = (Integer) tableModel.getValueAt(selectedRow, 0);
JOptionPane.showMessageDialog(SelectProduct.this,
"已选择ID为 " + Id + " 的商品: " + tableModel.getValueAt(selectedRow, 2),
"已选择", JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
}
});
scrollPane = new JScrollPane(resultTable);
scrollPane.setPreferredSize(new Dimension(580, 250));
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton selectButton = new JButton("选择");
selectButton.setFont(new Font("黑体", Font.BOLD, 14));
selectButton.setBackground(Color.PINK);
selectButton.setPreferredSize(new Dimension(100, 30));
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
Id = (Integer) tableModel.getValueAt(selectedRow, 0);
JOptionPane.showMessageDialog(SelectProduct.this,
"已选择ID为 " + Id + " 的商品: " + tableModel.getValueAt(selectedRow, 2),
"已选择", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(SelectProduct.this,
"请先选择一个商品",
"提示", JOptionPane.WARNING_MESSAGE);
}
});
JButton cancelButton = new JButton("取消");
cancelButton.setFont(new Font("黑体", Font.BOLD, 14));
cancelButton.setBackground(Color.PINK);
cancelButton.setPreferredSize(new Dimension(100, 30));
cancelButton.addActionListener(e -> {
Id = null;
dispose();
});
panel.add(selectButton);
panel.add(Box.createHorizontalStrut(20));
panel.add(cancelButton);
return panel;
}
// 文档监听器,用于实时搜索
private DocumentListener documentListener = new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (nameSearchRadio.isSelected() && showingResults) {
performSearch();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (nameSearchRadio.isSelected() && showingResults) {
performSearch();
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (nameSearchRadio.isSelected() && showingResults) {
performSearch();
}
}
};
// 执行搜索
private void performSearch() {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
if (idSearchRadio.isSelected()) {
JOptionPane.showMessageDialog(this, "请输入商品ID", "提示", JOptionPane.WARNING_MESSAGE);
} else {
// 如果是模糊查询且输入为空,显示所有商品
displayAllProducts();
}
return;
}
if (idSearchRadio.isSelected()) {
// ID查询
try {
Integer id = Integer.valueOf(searchText);
if (id <= 0) {
JOptionPane.showMessageDialog(this, "商品ID必须为正整数", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
List<Products> productList = ProductService.selectProductById(id);
updateTableWithResults(productList);
if (productList.isEmpty()) {
JOptionPane.showMessageDialog(this, "未查找到ID为 " + id + " 的商品", "查找结果", JOptionPane.INFORMATION_MESSAGE);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
}
} else {
// 模糊查询
List<Products> productList = ProductService.searchProductsByKeyword(searchText);
updateTableWithResults(productList);
if (productList.isEmpty() && !showingResults) {
JOptionPane.showMessageDialog(this, "未找到匹配的商品", "查找结果", JOptionPane.INFORMATION_MESSAGE);
}
}
showingResults = true;
}
// 显示所有商品
private void displayAllProducts() {
List<Products> productList = ProductService.selectAllProducts();
updateTableWithResults(productList);
}
// 更新表格数据
private void updateTableWithResults(List<Products> productList) {
// 清空表格
tableModel.setRowCount(0);
// 添加结果到表格
for (Products product : productList) {
Object[] rowData = {
product.getProductId(),
product.getProductCode(),
product.getProductName(),
product.getCategoryId(),
product.getUnitOfMeasure(),
product.getMinStockLevel(),
product.getIsActive()
};
tableModel.addRow(rowData);
}
// 刷新表格
tableModel.fireTableDataChanged();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SelectProduct::new);
}
}

@ -1,371 +0,0 @@
package com.xky.ui.module.productManagement.update;
import com.xky.pojo.ProductCategories;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class UpdateCategory extends JFrame {
private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
private JButton updateButton, queryButton;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
public UpdateCategory() {
initializeFrame();
initComponents();
setVisible(true);
}
private void initializeFrame() {
setTitle("商品分类信息修改");
setSize(550, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
private void initComponents() {
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 1. 头部面板
createHeaderPanel();
// 2. 表单面板
createFormPanel();
// 3. 按钮面板
createButtonPanel();
// 添加事件监听
setupEventListeners();
add(mainPanel);
}
private void createHeaderPanel() {
headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("商品分类信息修改");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入分类ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
}
private void createFormPanel() {
// 创建带圆角和阴影的面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
String[] labels = {"分类ID *", "分类名称 *", "父分类ID *", "是否启用 *"};
textFields = new JTextField[3];
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
// 添加标签
gbc.gridx = 0;
gbc.gridy = i;
gbc.weightx = 0.3;
JLabel label = new JLabel(labels[i]);
label.setFont(labelFont);
label.setForeground(PRIMARY_COLOR);
formPanel.add(label, gbc);
// 添加输入控件
gbc.gridx = 1;
gbc.weightx = 0.7;
if (i != 3) { // 不是是否启用
textFields[i] = new JTextField(20);
textFields[i].setFont(fieldFont);
textFields[i].setPreferredSize(new Dimension(250, 35));
formPanel.add(textFields[i], gbc);
} else { // 是否启用使用下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(fieldFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
formPanel.add(isActiveComboBox, gbc);
}
}
formCard.add(formPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
}
private void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
queryButton = new JButton("查询");
styleButton(queryButton, QUERY_BUTTON_COLOR);
updateButton = new JButton("修改");
styleButton(updateButton, BUTTON_COLOR);
// 初始状态下修改按钮不可用
updateButton.setEnabled(false);
buttonPanel.add(queryButton);
buttonPanel.add(updateButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
private void setupEventListeners() {
// 查询按钮事件
queryButton.addActionListener(e -> {
String categoryIdStr = textFields[0].getText().trim();
if (categoryIdStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入分类ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
int categoryId = Integer.parseInt(categoryIdStr);
ProductCategories category = findCategoryById(categoryId);
if (category != null) {
// 填充表单数据
textFields[0].setText(String.valueOf(category.getCategoryId()));
textFields[1].setText(category.getCategoryName());
textFields[2].setText(String.valueOf(category.getParentId()));
// 设置是否启用下拉框
isActiveComboBox.setSelectedIndex("1".equals(category.getIsActive()) ? 0 : 1);
// 启用修改按钮
updateButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(this, "未找到该分类", "提示", JOptionPane.WARNING_MESSAGE);
updateButton.setEnabled(false);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
// 修改按钮事件
updateButton.addActionListener(e -> {
try {
// 首先进行输入校验
if (!validateInputs()) {
return; // 如果校验不通过,直接返回
}
Integer categoryId = Integer.valueOf(textFields[0].getText().trim());
String categoryName = textFields[1].getText().trim();
Integer parentId = Integer.valueOf(textFields[2].getText().trim());
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
if (updateCategory(categoryId, categoryName, parentId, isActive)) {
JOptionPane.showMessageDialog(this, "分类信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "分类信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
private boolean validateInputs() {
// 1. 校验分类ID
if (textFields[0].getText().trim().isEmpty()) {
showValidationError("分类ID不能为空");
return false;
}
try {
Integer.parseInt(textFields[0].getText().trim());
} catch (NumberFormatException e) {
showValidationError("分类ID必须是数字");
return false;
}
// 2. 校验分类名称
if (textFields[1].getText().trim().isEmpty()) {
showValidationError("分类名称不能为空");
return false;
}
// 3. 校验父分类ID
if (textFields[2].getText().trim().isEmpty()) {
showValidationError("父分类ID不能为空");
return false;
}
try {
Integer.parseInt(textFields[2].getText().trim());
} catch (NumberFormatException e) {
showValidationError("父分类ID必须是数字");
return false;
}
// 所有校验通过
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
private ProductCategories findCategoryById(int categoryId) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM product_categories WHERE category_id = ?");
preparedStatement.setInt(1, categoryId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
ProductCategories category = new ProductCategories();
category.setCategoryId(resultSet.getInt("category_id"));
category.setCategoryName(resultSet.getString("category_name"));
category.setParentId(resultSet.getInt("parent_id"));
category.setIsActive(resultSet.getString("is_active"));
return category;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
private boolean updateCategory(Integer categoryId, String categoryName, Integer parentId, String isActive) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"UPDATE product_categories SET category_name = ?, parent_id = ?, is_active = ?, updated_time = NOW() WHERE category_id = ?");
preparedStatement.setString(1, categoryName);
preparedStatement.setInt(2, parentId);
preparedStatement.setString(3, isActive);
preparedStatement.setInt(4, categoryId);
return preparedStatement.executeUpdate() > 0;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
private void clearForm() {
for (JTextField field : textFields) {
field.setText("");
}
isActiveComboBox.setSelectedIndex(0);
updateButton.setEnabled(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateCategory::new);
}
}

@ -1,450 +0,0 @@
package com.xky.ui.module.productManagement.update;
import com.xky.pojo.Products;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class UpdateProduct extends JFrame {
private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
private JTextField[] textFields;
private JComboBox<String> unitComboBox;
private JComboBox<String> isActiveComboBox;
private JButton updateButton, queryButton;
// 预定义的有效计量单位列表
private static final Set<String> VALID_UNITS = new HashSet<>(Arrays.asList(
"个", "箱", "袋", "瓶", "千克", "克", "吨", "升", "毫升", "米", "厘米", "套",
"件", "双", "台", "包", "盒", "桶", "卷", "张", "只", "块", "片", "支"
));
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
public UpdateProduct() {
initializeFrame();
initComponents();
setVisible(true);
}
private void initializeFrame() {
setTitle("商品信息修改");
setSize(550, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
private void initComponents() {
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 1. 头部面板
createHeaderPanel();
// 2. 表单面板
createFormPanel();
// 3. 按钮面板
createButtonPanel();
// 添加事件监听
setupEventListeners();
add(mainPanel);
}
private void createHeaderPanel() {
headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("商品信息修改");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入商品ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
}
private void createFormPanel() {
// 创建带圆角和阴影的面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
String[] labels = {"商品ID *", "商品编码 *", "商品名称 *", "分类ID *", "计量单位 *", "最低库存 *", "是否上架 *"};
textFields = new JTextField[6];
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
// 添加标签
gbc.gridx = 0;
gbc.gridy = i;
gbc.weightx = 0.3;
JLabel label = new JLabel(labels[i]);
label.setFont(labelFont);
label.setForeground(PRIMARY_COLOR);
formPanel.add(label, gbc);
// 添加输入控件
gbc.gridx = 1;
gbc.weightx = 0.7;
if (i != 4 && i != 6) { // 不是计量单位和是否上架
textFields[i > 4 ? i - 1 : i] = new JTextField(20);
textFields[i > 4 ? i - 1 : i].setFont(fieldFont);
textFields[i > 4 ? i - 1 : i].setPreferredSize(new Dimension(250, 35));
formPanel.add(textFields[i > 4 ? i - 1 : i], gbc);
} else if (i == 4) { // 计量单位使用下拉框
unitComboBox = new JComboBox<>(VALID_UNITS.toArray(new String[0]));
unitComboBox.setFont(fieldFont);
unitComboBox.setPreferredSize(new Dimension(250, 35));
unitComboBox.setBackground(Color.WHITE);
formPanel.add(unitComboBox, gbc);
} else {
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(fieldFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
formPanel.add(isActiveComboBox, gbc);
}
}
formCard.add(formPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
}
private void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
queryButton = new JButton("查询");
styleButton(queryButton, QUERY_BUTTON_COLOR);
updateButton = new JButton("修改");
styleButton(updateButton, BUTTON_COLOR);
// 初始状态下修改按钮不可用
updateButton.setEnabled(false);
buttonPanel.add(queryButton);
buttonPanel.add(updateButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
private void setupEventListeners() {
// 查询按钮事件
queryButton.addActionListener(e -> {
String productIdStr = textFields[0].getText().trim();
if (productIdStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入商品ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
int productId = Integer.parseInt(productIdStr);
Products product = findProductById(productId);
if (product != null) {
// 填充表单数据
textFields[0].setText(String.valueOf(product.getProductId()));
textFields[1].setText(product.getProductCode());
textFields[2].setText(product.getProductName());
textFields[3].setText(String.valueOf(product.getCategoryId()));
// 设置计量单位下拉框
for (int i = 0; i < unitComboBox.getItemCount(); i++) {
if (unitComboBox.getItemAt(i).equals(product.getUnitOfMeasure())) {
unitComboBox.setSelectedIndex(i);
break;
}
}
textFields[4].setText(String.valueOf(product.getMinStockLevel()));
// 设置是否上架下拉框
isActiveComboBox.setSelectedIndex("1".equals(product.getIsActive()) ? 0 : 1);
// 启用修改按钮
updateButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(this, "未找到该商品", "提示", JOptionPane.WARNING_MESSAGE);
updateButton.setEnabled(false);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
// 修改按钮事件
updateButton.addActionListener(e -> {
try {
// 首先进行输入校验
if (!validateInputs()) {
return; // 如果校验不通过,直接返回
}
Integer productId = Integer.valueOf(textFields[0].getText().trim());
String productCode = textFields[1].getText().trim();
String productName = textFields[2].getText().trim();
int categoryId = Integer.parseInt(textFields[3].getText().trim());
String unitOfMeasure = (String) unitComboBox.getSelectedItem();
int minStockLevel = Integer.parseInt(textFields[4].getText().trim());
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
if (updateProduct(productId, productCode, productName, categoryId, unitOfMeasure, minStockLevel, isActive)) {
JOptionPane.showMessageDialog(this, "商品信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "商品信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
/**
*
* @return truefalse
*/
private boolean validateInputs() {
// 1. 校验商品ID
if (textFields[0].getText().trim().isEmpty()) {
showValidationError("商品ID不能为空");
return false;
}
try {
Integer.parseInt(textFields[0].getText().trim());
} catch (NumberFormatException e) {
showValidationError("商品ID必须是数字");
return false;
}
// 2. 校验商品编码
if (textFields[1].getText().trim().isEmpty()) {
showValidationError("商品编码不能为空");
return false;
}
// 3. 校验商品名称
if (textFields[2].getText().trim().isEmpty()) {
showValidationError("商品名称不能为空");
return false;
}
// 4. 校验分类ID
if (textFields[3].getText().trim().isEmpty()) {
showValidationError("分类ID不能为空");
return false;
}
try {
Integer.parseInt(textFields[3].getText().trim());
} catch (NumberFormatException e) {
showValidationError("分类ID必须是数字");
return false;
}
// 5. 校验最低库存
if (textFields[4].getText().trim().isEmpty()) {
showValidationError("最低库存不能为空");
return false;
}
try {
int minStock = Integer.parseInt(textFields[4].getText().trim());
if (minStock < 0) {
showValidationError("最低库存不能小于0");
return false;
}
} catch (NumberFormatException e) {
showValidationError("最低库存必须是数字");
return false;
}
// 所有校验通过
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
private Products findProductById(int productId) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM products WHERE product_id = ?");
preparedStatement.setInt(1, productId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Products product = new Products();
product.setProductId(resultSet.getInt("product_id"));
product.setProductCode(resultSet.getString("product_code"));
product.setProductName(resultSet.getString("product_name"));
product.setCategoryId(resultSet.getInt("category_id"));
product.setUnitOfMeasure(resultSet.getString("unit_of_measure"));
product.setMinStockLevel(resultSet.getInt("min_stock_level"));
product.setIsActive(resultSet.getString("is_active"));
return product;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param productId
* @param productCode
* @param productName
* @param categoryId
* @param unitOfMeasure
* @param minStockLevel
* @param isActive
* @return
* @throws SQLException
*/
private boolean updateProduct(Integer productId, String productCode, String productName, int categoryId,
String unitOfMeasure, int minStockLevel, String isActive) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"UPDATE products SET product_code = ?, product_name = ?, category_id = ?, " +
"unit_of_measure = ?, min_stock_level = ?, is_active = ?, updated_time = NOW() " +
"WHERE product_id = ?");
preparedStatement.setString(1, productCode);
preparedStatement.setString(2, productName);
preparedStatement.setInt(3, categoryId);
preparedStatement.setString(4, unitOfMeasure);
preparedStatement.setInt(5, minStockLevel);
preparedStatement.setString(6, isActive);
preparedStatement.setInt(7, productId);
return preparedStatement.executeUpdate() > 0;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
private void clearForm() {
for (JTextField field : textFields) {
field.setText("");
}
unitComboBox.setSelectedIndex(0);
isActiveComboBox.setSelectedIndex(0);
updateButton.setEnabled(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateProduct::new);
}
}

@ -1,229 +0,0 @@
package com.xky.ui.module.register;
import com.xky.ui.module.login.Login;
import com.xky.utils.DBUtils;
import com.xky.utils.MD5Utils;
import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Register extends JFrame {
public Register() {
setTitle("注册界面");
setSize(450, 450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
setVisible(true);
}
void initComponents() {
setLayout(new BorderLayout());
JLabel label1 = new JLabel("用户注册",SwingConstants.CENTER);
label1.setBounds(100, 20, 200, 30);
label1.setFont(new java.awt.Font("华文行楷", Font.PLAIN, 30));
add(label1, BorderLayout.NORTH);
//表单面板
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.setBackground(new Color(147, 206, 141));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5,5,5,5);
jPanel.setOpaque(false); // 设置主面板为透明
Font font = new Font("微软雅黑", Font.PLAIN, 20);
JLabel label2 = new JLabel("用户名:");
label2.setFont(font);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.insets = new Insets(10,50,10,10);
gbc.fill = GridBagConstraints.NONE;
jPanel.add(label2,gbc);
JTextField usernameField = new JTextField(20);
usernameField.setPreferredSize(new Dimension(400,35));
gbc.gridx = 1;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.gridwidth = 2;
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
jPanel.add(usernameField,gbc);
JLabel jLabel1 = new JLabel("密码:");
jLabel1.setFont(font);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(10,70,10,10);
gbc.fill = GridBagConstraints.NONE;
jPanel.add(jLabel1,gbc);
JPasswordField passwordField = new JPasswordField(20);
passwordField.setPreferredSize(new Dimension(400,35));
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.gridwidth = 2; // 输入框占据一个网格单元
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
jPanel.add(passwordField,gbc);
JLabel jLabel2 = new JLabel("确认密码:");
jLabel2.setFont(font);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(10,30,10,10);
gbc.fill = GridBagConstraints.NONE;
jPanel.add(jLabel2,gbc);
JPasswordField password1Field = new JPasswordField(20);
password1Field.setPreferredSize(new Dimension(400,35));
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.gridwidth = 2; // 输入框占据一个网格单元
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
jPanel.add(password1Field,gbc);
JLabel jLabel3 = new JLabel("邮箱:");
jLabel3.setFont(font);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(10,70,10,10);
gbc.fill = GridBagConstraints.NONE;
jPanel.add(jLabel3,gbc);
JTextField emailField = new JTextField(20);
emailField.setPreferredSize(new Dimension(400,35));
gbc.gridx = 1;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.gridwidth = 2; // 输入框占据一个网格单元
gbc.insets = new Insets(10,0,10,50);
gbc.fill = GridBagConstraints.HORIZONTAL;
jPanel.add(emailField,gbc);
//角色提示
JLabel jLabel = new JLabel("你当前注册的角色是管理员");
jLabel.setFont(new Font("华文行楷",Font.PLAIN,15));
jLabel.setForeground(Color.LIGHT_GRAY);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.insets = new Insets(5,30,10,10);
jPanel.add(jLabel,gbc);
//按钮
JButton jButton = new JButton("注册");
jButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
jButton.setForeground(Color.WHITE);
jButton.setBackground(new Color(255, 182, 193)); // 柔和的粉色
jButton.setPreferredSize(new Dimension(100, 35));
jButton.setFocusPainted(false);
jButton.setBorderPainted(false); // 禁用默认边框
jButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
gbc.gridx = 0;
gbc.gridy = 5;
gbc.insets = new Insets(40,120,10,10);
gbc.fill = GridBagConstraints.NONE;
String EMAIL = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
jButton.addActionListener(e->{
String username = usernameField.getText().trim();
String password = new String(passwordField.getPassword()).trim();
String password1 = new String(password1Field.getPassword()).trim();
String email = emailField.getText().trim();
if (username.isEmpty() || password.isEmpty() || password1.isEmpty() || email.isEmpty()){
JOptionPane.showMessageDialog(Register.this,"注册信息不能为空,请输入:","注册提示",JOptionPane.WARNING_MESSAGE);
}else if (!password.equals(password1)){
JOptionPane.showMessageDialog(Register.this,"你填写的密码不一致,请重新输入,","错误提示",JOptionPane.WARNING_MESSAGE);
passwordField.setText("");
password1Field.setText("");
}else if (!email.matches(EMAIL)){
JOptionPane.showMessageDialog(Register.this,"邮箱格式不对,请重新输入","错误提示",JOptionPane.ERROR_MESSAGE);
emailField.setText("");
}else if (addUser(username,password,email)){
JOptionPane.showMessageDialog(Register.this,"恭喜你,注册成功!","成功提示",JOptionPane.INFORMATION_MESSAGE);
dispose();
new Login();
}else {
JOptionPane.showMessageDialog(Register.this,"注册失败?","失败提示",JOptionPane.ERROR_MESSAGE);
}
});
jPanel.add(jButton,gbc);
//按钮
JButton jButton1 = new JButton("返回");
jButton1.setFont(new Font("微软雅黑", Font.BOLD, 14));
jButton1.setForeground(Color.WHITE);
jButton1.setBackground(new Color(135, 206, 250)); // 淡蓝色
jButton1.setPreferredSize(new Dimension(100, 35));
jButton1.setFocusPainted(false);
jButton1.setBorderPainted(false); // 禁用默认边框
jButton1.setCursor(new Cursor(Cursor.HAND_CURSOR));
gbc.gridx = 1;
gbc.gridy = 5;
gbc.insets = new Insets(40,120,10,10);
gbc.fill = GridBagConstraints.NONE;
jButton1.addActionListener(e->{
dispose();
new Login();
});
jPanel.add(jButton1,gbc);
add(jPanel, BorderLayout.CENTER);
}
//添加用户信息
public boolean addUser(String username, String password, String email){
Connection connection;
PreparedStatement preparedStatement = null;
connection = DBUtils.getConnection();
String mdpassword = MD5Utils.md5Encrypt(password);
try {
preparedStatement = connection.prepareStatement("insert into login(username, password, email) values (?,?,?)");
preparedStatement.setString(1,username);
preparedStatement.setString(2,mdpassword);
preparedStatement.setString(3,email);
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("受影响的行数为"+i+",添加成功!");
}else {
System.out.println("受影响的行数为"+i+",添加失败!");
}
return true;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtils.closeAll(connection,preparedStatement,null);
}
}
public static void main(String[] args) throws UnsupportedLookAndFeelException, ClassNotFoundException, InstantiationException, IllegalAccessException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(Register::new);
}
}

@ -1,142 +0,0 @@
package com.xky.ui.module.salesManagement;
import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.ui.main.MainView;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
*
*
*/
public class SalesInfo {
private static JTable salesTable;
private static final String MODULE_NAME = "销售订单信息";
/**
*
*/
public static void showSalesInfoPage() {
try {
// 创建销售订单信息面板
JPanel salesInfoPanel = SalesMassage.createSalesInfoPanel(SalesInfo::refreshSalesData);
// 获取表格组件
Component centerComponent = null;
if (salesInfoPanel.getLayout() instanceof BorderLayout) {
// 遍历所有组件查找位于CENTER位置的组件
for (Component comp : salesInfoPanel.getComponents()) {
Object constraints = ((BorderLayout)salesInfoPanel.getLayout())
.getConstraints(comp);
if (BorderLayout.CENTER.equals(constraints)) {
centerComponent = comp;
break;
}
}
// 如果找不到尝试直接查找JScrollPane
if (centerComponent == null) {
for (Component comp : salesInfoPanel.getComponents()) {
if (comp instanceof JScrollPane) {
centerComponent = comp;
break;
}
}
}
}
if (centerComponent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) centerComponent;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
salesTable = (JTable) viewComponent;
} else {
throw new IllegalStateException("无法找到表格组件: 视图组件不是表格");
}
} else {
throw new IllegalStateException("无法找到表格组件: 中心组件不是滚动面板");
}
// 更新右侧面板
MainView.rightPanel.removeAll();
MainView.rightPanel.add(salesInfoPanel, BorderLayout.CENTER);
MainView.rightPanel.revalidate();
MainView.rightPanel.repaint();
// 注册刷新操作
MainView.registerRefreshAction(MODULE_NAME, SalesInfo::refreshSalesData);
// 立即刷新一次
refreshSalesData();
// 更新状态消息
MainView.updateStatusMessage(MODULE_NAME + "页面已加载");
} catch (Exception e) {
handleException(e, "加载" + MODULE_NAME + "页面失败");
}
}
/**
*
*/
static void refreshSalesData() {
// 显示加载指示器
MainView.updateStatusMessage("正在加载" + MODULE_NAME + "数据...");
new SwingWorker<List<SalesOrders>, Void>() {
@Override
protected List<SalesOrders> doInBackground() {
validateTable();
DefaultTableModel model = (DefaultTableModel) salesTable.getModel();
model.setRowCount(0);
// 获取所有销售订单数据
return SelectSalesOrder.selectAll();
}
@Override
protected void done() {
try {
List<SalesOrders> salesList = get();
if (salesTable != null) {
SalesMassage.updateTableData(salesTable, salesList);
MainView.rightPanel.repaint();
MainView.updateStatusMessage("已加载 " + salesList.size() + " 条" + MODULE_NAME + "数据");
}
} catch (InterruptedException | ExecutionException e) {
handleException(e, "刷新失败");
}
}
}.execute();
}
/**
*
* @throws IllegalStateException
*/
private static void validateTable() throws IllegalStateException {
if (salesTable == null) {
throw new IllegalStateException("表格未初始化");
}
}
/**
*
* @param e
* @param message
*/
private static void handleException(Exception e, String message) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
message + ": " + e.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
MainView.updateStatusMessage(MODULE_NAME + "数据加载失败");
}
}

@ -1,578 +0,0 @@
package com.xky.ui.module.salesManagement;
import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.ui.module.salesManagement.add.AddSalesOrder;
import com.xky.ui.module.salesManagement.delete.DeleteSalesOrder;
import com.xky.ui.module.salesManagement.update.UpdateSalesOrder;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
/**
*
*/
public class SalesMassage {
// 表格组件
private static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color ADD_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color UPDATE_BUTTON_COLOR = new Color(52, 152, 219);
private static final Color DELETE_BUTTON_COLOR = new Color(231, 76, 60);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color REFRESH_BUTTON_COLOR = new Color(142, 68, 173);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color HIGHLIGHT_ROW_COLOR = new Color(235, 245, 251);
private static final Color ALTERNATE_ROW_COLOR = new Color(248, 251, 255);
// 定义字体常量
private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 26);
private static final Font SUBTITLE_FONT = new Font("微软雅黑", Font.PLAIN, 14);
private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
// 订单状态颜色映射
private static final Map<String, Color> STATUS_COLORS = new HashMap<>();
static {
STATUS_COLORS.put("待处理", new Color(230, 126, 34));
STATUS_COLORS.put("已确认", new Color(41, 128, 185));
STATUS_COLORS.put("已发货", new Color(46, 204, 113));
STATUS_COLORS.put("已完成", new Color(39, 174, 96));
STATUS_COLORS.put("已取消", new Color(231, 76, 60));
}
// 支付状态颜色映射
private static final Map<String, Color> PAYMENT_COLORS = new HashMap<>();
static {
PAYMENT_COLORS.put("未支付", new Color(192, 57, 43));
PAYMENT_COLORS.put("部分支付", new Color(243, 156, 18));
PAYMENT_COLORS.put("已支付", new Color(39, 174, 96));
PAYMENT_COLORS.put("已退款", new Color(142, 68, 173));
}
// 状态代码到显示文本的映射
private static final Map<String, String> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put("pending", "待处理");
STATUS_MAP.put("confirmed", "已确认");
STATUS_MAP.put("shipped", "已发货");
STATUS_MAP.put("completed", "已完成");
STATUS_MAP.put("cancelled", "已取消");
}
private static final Map<String, String> PAYMENT_STATUS_MAP = new HashMap<>();
static {
PAYMENT_STATUS_MAP.put("unpaid", "未支付");
PAYMENT_STATUS_MAP.put("partial", "部分支付");
PAYMENT_STATUS_MAP.put("paid", "已支付");
PAYMENT_STATUS_MAP.put("refunded", "已退款");
}
// 日期时间格式化器
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
*
* @param refreshAction
* @return
*/
public static JPanel createSalesInfoPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("销售订单基本信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createSalesTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
new AddSalesOrder();
if (refreshAction != null) {
refreshAction.run();
}
});
deleteButton.addActionListener(e -> {
if (table.getSelectedRow() != -1) {
int selectedRow = table.getSelectedRow();
int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
new DeleteSalesOrder(orderId);
} else {
new DeleteSalesOrder();
}
if (refreshAction != null) {
refreshAction.run();
}
});
updateButton.addActionListener(e -> {
if (table.getSelectedRow() != -1) {
int selectedRow = table.getSelectedRow();
int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
new UpdateSalesOrder(orderId);
} else {
new UpdateSalesOrder();
}
if (refreshAction != null) {
refreshAction.run();
}
});
queryButton.addActionListener(e -> showSearchDialog());
refreshButton.addActionListener(e -> {
SelectSalesOrder.resetSearchStatus();
if (refreshAction != null) {
refreshAction.run();
updateStatusMessage("销售订单数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createSalesTable() {
// 表格列名
String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "预计发货日期", "实际发货日期",
"仓库ID", "商品总额", "税额",
"折扣金额", "订单总金额", "已付金额", "备注", "创建时间", "更新时间"};
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
// 创建表格
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(70);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(70);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(120);
table.getColumnModel().getColumn(5).setPreferredWidth(120);
table.getColumnModel().getColumn(6).setPreferredWidth(70);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(70);
table.getColumnModel().getColumn(9).setPreferredWidth(100);
table.getColumnModel().getColumn(10).setPreferredWidth(130);
table.getColumnModel().getColumn(11).setPreferredWidth(100);
table.getColumnModel().getColumn(12).setPreferredWidth(60);
table.getColumnModel().getColumn(13).setPreferredWidth(120);
table.getColumnModel().getColumn(14).setPreferredWidth(120);
// 设置单元格渲染器
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
// 对所有列应用居中渲染器,除了备注列
for (int i = 0; i < columnNames.length; i++) {
if (i != 14) { // 备注列除外
table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
}
// 添加双击打开编辑功能
table.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() == 2) {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
int orderId = (int) table.getModel().getValueAt(selectedRow, 0);
new UpdateSalesOrder(orderId);
}
}
}
});
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param orderList
*/
public static void updateTableData(JTable table, List<SalesOrders> orderList) {
if (table == null || orderList == null) {
return;
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
// 清空表格中现有的数据
model.setRowCount(0);
for (SalesOrders order : orderList) {
String orderDateStr = order.getOrderDate() != null ?
order.getOrderDate().format(DATETIME_FORMATTER) : "";
String expectedShipDateStr = order.getExpectedShipDate() != null ?
order.getExpectedShipDate().format(DATE_FORMATTER) : "";
String actualShipDateStr = order.getActualShipDate() != null ?
order.getActualShipDate().format(DATE_FORMATTER) : "";
String createdTimeStr = order.getCreatedTime() != null ?
order.getCreatedTime().format(DATETIME_FORMATTER) : "";
String updatedTimeStr = order.getUpdatedTime() != null ?
order.getUpdatedTime().format(DATETIME_FORMATTER) : "";
model.addRow(new Object[]{
order.getOrderId(),
order.getOrderNumber(),
order.getCustomerId(),
orderDateStr,
expectedShipDateStr,
actualShipDateStr,
order.getWarehouseId(),
order.getSubtotal(),
order.getTaxAmount(),
order.getDiscountAmount(),
order.getTotalAmount(),
order.getPaidAmount(),
order.getNotes(),
createdTimeStr,
updatedTimeStr
});
}
// 触发表格数据刷新
model.fireTableDataChanged();
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询销售订单", true);
searchDialog.setSize(900, 550);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
topPanel.setBackground(SECONDARY_COLOR);
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.setOpaque(false);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按订单ID查询", true);
JRadioButton numberRadio = new JRadioButton("按订单编号查询");
JRadioButton customerRadio = new JRadioButton("按客户ID查询");
JRadioButton keywordRadio = new JRadioButton("关键字查询");
idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
numberRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
customerRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
keywordRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
idRadio.setOpaque(false);
numberRadio.setOpaque(false);
customerRadio.setOpaque(false);
keywordRadio.setOpaque(false);
buttonGroup.add(idRadio);
buttonGroup.add(numberRadio);
buttonGroup.add(customerRadio);
buttonGroup.add(keywordRadio);
radioPanel.add(idRadio);
radioPanel.add(numberRadio);
radioPanel.add(customerRadio);
radioPanel.add(keywordRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
searchPanel.setOpaque(false);
JLabel searchLabel = new JLabel("查询条件: ");
searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
JTextField searchField = new JTextField(20);
searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
searchField.setPreferredSize(new Dimension(200, 30));
JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);
JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
searchFieldPanel.setOpaque(false);
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 订单编号/ 客户ID/ 订单状态/ 支付状态/ 备注");
tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "订单状态", "支付状态", "订单总金额"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
resultTable.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
resultTable.getTableHeader().setOpaque(true);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
scrollPane.getViewport().setBackground(Color.WHITE);
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
buttonPanel.setBackground(SECONDARY_COLOR);
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(e -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<SalesOrders> resultList = new ArrayList<>();
try {
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
List<SalesOrders> orders = SelectSalesOrder.selectById(id);
if (orders != null && !orders.isEmpty()) {
resultList.addAll(orders);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (numberRadio.isSelected()) {
// 按订单编号查询
List<SalesOrders> orders = SelectSalesOrder.selectByOrderNumber(searchText);
if (orders != null && !orders.isEmpty()) {
resultList.addAll(orders);
}
} else if (customerRadio.isSelected()) {
// 按客户ID查询
try {
int customerId = Integer.parseInt(searchText);
List<SalesOrders> orders = SelectSalesOrder.selectByCustomerId(customerId);
if (orders != null && !orders.isEmpty()) {
resultList.addAll(orders);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "客户ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (keywordRadio.isSelected()) {
// 关键字查询
List<SalesOrders> orders = SelectSalesOrder.searchByKeyword(searchText);
if (orders != null && !orders.isEmpty()) {
resultList.addAll(orders);
}
}
// 更新表格数据
tableModel.setRowCount(0);
if (!resultList.isEmpty()) {
for (SalesOrders order : resultList) {
String orderDateStr = order.getOrderDate() != null ?
order.getOrderDate().format(DATETIME_FORMATTER) : "";
tableModel.addRow(new Object[]{
order.getOrderId(),
order.getOrderNumber(),
order.getCustomerId(),
orderDateStr,
STATUS_MAP.get(order.getOrderStatus()),
PAYMENT_STATUS_MAP.get(order.getPaymentStatus()),
order.getTotalAmount()
});
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int orderId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的订单数据
List<SalesOrders> orderList = SelectSalesOrder.selectById(orderId);
if (!orderList.isEmpty()) {
// 清空主表格并只显示选中的订单
updateTableData(table, orderList);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
autoRefreshTimer.stop();
}
// 更新状态消息
updateStatusMessage("已选择订单ID: " + orderId);
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
}

@ -1,142 +0,0 @@
package com.xky.ui.module.salesManagement;
import com.xky.pojo.SalesShipments;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.main.MainView;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
*
*
*/
public class SalesShipmentsInfo {
private static JTable shipmentsTable;
private static final String MODULE_NAME = "销售发货信息";
/**
*
*/
public static void showSalesShipmentsPage() {
try {
// 创建销售发货信息面板
JPanel shipmentsInfoPanel = SalesShipmentsManagement.createShipmentsPanel(SalesShipmentsInfo::refreshShipmentsData);
// 获取表格组件
Component centerComponent = null;
if (shipmentsInfoPanel.getLayout() instanceof BorderLayout) {
// 遍历所有组件查找位于CENTER位置的组件
for (Component comp : shipmentsInfoPanel.getComponents()) {
Object constraints = ((BorderLayout)shipmentsInfoPanel.getLayout())
.getConstraints(comp);
if (BorderLayout.CENTER.equals(constraints)) {
centerComponent = comp;
break;
}
}
// 如果找不到尝试直接查找JScrollPane
if (centerComponent == null) {
for (Component comp : shipmentsInfoPanel.getComponents()) {
if (comp instanceof JScrollPane) {
centerComponent = comp;
break;
}
}
}
}
if (centerComponent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) centerComponent;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
shipmentsTable = (JTable) viewComponent;
} else {
throw new IllegalStateException("无法找到表格组件: 视图组件不是表格");
}
} else {
throw new IllegalStateException("无法找到表格组件: 中心组件不是滚动面板");
}
// 更新右侧面板
MainView.rightPanel.removeAll();
MainView.rightPanel.add(shipmentsInfoPanel, BorderLayout.CENTER);
MainView.rightPanel.revalidate();
MainView.rightPanel.repaint();
// 注册刷新操作
MainView.registerRefreshAction(MODULE_NAME, SalesShipmentsInfo::refreshShipmentsData);
// 立即刷新一次
refreshShipmentsData();
// 更新状态消息
MainView.updateStatusMessage(MODULE_NAME + "页面已加载");
} catch (Exception e) {
handleException(e, "加载" + MODULE_NAME + "页面失败");
}
}
/**
*
*/
static void refreshShipmentsData() {
// 显示加载指示器
MainView.updateStatusMessage("正在加载" + MODULE_NAME + "数据...");
new SwingWorker<List<SalesShipments>, Void>() {
@Override
protected List<SalesShipments> doInBackground() {
validateTable();
DefaultTableModel model = (DefaultTableModel) shipmentsTable.getModel();
model.setRowCount(0);
// 获取所有销售发货数据
return SelectSalesShipment.selectAll();
}
@Override
protected void done() {
try {
List<SalesShipments> shipmentsList = get();
if (shipmentsTable != null) {
SalesShipmentsManagement.updateTableData(shipmentsTable, shipmentsList);
MainView.rightPanel.repaint();
MainView.updateStatusMessage("已加载 " + shipmentsList.size() + " 条" + MODULE_NAME + "数据");
}
} catch (InterruptedException | ExecutionException e) {
handleException(e, "刷新失败");
}
}
}.execute();
}
/**
*
* @throws IllegalStateException
*/
private static void validateTable() throws IllegalStateException {
if (shipmentsTable == null) {
throw new IllegalStateException("表格未初始化");
}
}
/**
*
* @param e
* @param message
*/
private static void handleException(Exception e, String message) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
message + ": " + e.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
MainView.updateStatusMessage(MODULE_NAME + "数据加载失败");
}
}

@ -1,498 +0,0 @@
package com.xky.ui.module.salesManagement;
import com.xky.pojo.SalesShipments;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.module.salesManagement.add.AddSalesShipment;
import com.xky.ui.module.salesManagement.delete.DeleteSalesShipment;
import com.xky.ui.module.salesManagement.select.AdvancedSearchSalesShipmentDialog;
import com.xky.ui.module.salesManagement.update.UpdateSalesShipment;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
/**
*
*/
public class SalesShipmentsManagement {
// 表格组件
private static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color ADD_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color UPDATE_BUTTON_COLOR = new Color(52, 152, 219);
private static final Color DELETE_BUTTON_COLOR = new Color(231, 76, 60);
private static final Color SEARCH_BUTTON_COLOR = new Color(52, 73, 94);
private static final Color REFRESH_BUTTON_COLOR = new Color(142, 68, 173);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color HIGHLIGHT_ROW_COLOR = new Color(235, 245, 251);
private static final Color ALTERNATE_ROW_COLOR = new Color(248, 251, 255);
// 定义字体常量
private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 26);
private static final Font SUBTITLE_FONT = new Font("微软雅黑", Font.PLAIN, 14);
private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
// 状态颜色映射
private static final Map<String, Color> STATUS_COLORS = new HashMap<>();
static {
STATUS_COLORS.put("待发货", new Color(230, 126, 34));
STATUS_COLORS.put("已发货", new Color(41, 128, 185));
STATUS_COLORS.put("运输中", new Color(46, 204, 113));
STATUS_COLORS.put("已签收", new Color(39, 174, 96));
STATUS_COLORS.put("已取消", new Color(231, 76, 60));
}
// 状态代码到显示文本的映射
private static final Map<String, String> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put("pending", "待发货");
STATUS_MAP.put("shipped", "已发货");
STATUS_MAP.put("in_transit", "运输中");
STATUS_MAP.put("delivered", "已签收");
STATUS_MAP.put("cancelled", "已取消");
}
// 日期时间格式化器
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
*
*
* @param refreshAction
* @return
*/
public static JPanel createShipmentsPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10)) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
// 创建渐变背景 - 从浅蓝色到白色
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(255, 255, 255));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
panel.setBorder(new EmptyBorder(15, 15, 15, 15));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout(0, 10));
topPanel.setOpaque(false);
// 标题面板
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("销售发货管理");
titleLabel.setFont(TITLE_FONT);
titleLabel.setForeground(PRIMARY_COLOR);
titleLabel.setBorder(new EmptyBorder(0, 10, 0, 0));
JLabel subtitleLabel = new JLabel("管理和查询所有销售发货信息");
subtitleLabel.setFont(SUBTITLE_FONT);
subtitleLabel.setForeground(Color.GRAY);
subtitleLabel.setBorder(new EmptyBorder(0, 12, 5, 0));
JPanel labelsPanel = new JPanel(new BorderLayout());
labelsPanel.setOpaque(false);
labelsPanel.add(titleLabel, BorderLayout.NORTH);
labelsPanel.add(subtitleLabel, BorderLayout.CENTER);
titlePanel.add(labelsPanel, BorderLayout.WEST);
// 分割线
JSeparator separator = new JSeparator();
separator.setForeground(SEPARATOR_COLOR);
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 创建表格和滚动面板
JScrollPane scrollPane = createShipmentsTable();
// 给表格添加圆角边框
scrollPane.setBorder(BorderFactory.createCompoundBorder(
new EmptyBorder(5, 0, 5, 0),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(SEPARATOR_COLOR, 1, true),
BorderFactory.createEmptyBorder(8, 8, 8, 8)
)
));
// 状态面板
JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.setOpaque(false);
statusPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(statusPanel, BorderLayout.SOUTH);
return panel;
}
/**
*
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 10));
buttonPanel.setOpaque(false);
// 创建按钮
JButton addButton = createStyledButton("添加发货", ADD_BUTTON_COLOR);
JButton updateButton = createStyledButton("修改发货", UPDATE_BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除发货", DELETE_BUTTON_COLOR);
JButton queryButton = createStyledButton("高级查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新数据", REFRESH_BUTTON_COLOR);
// 设置按钮大小更一致
Dimension buttonSize = new Dimension(110, 35);
addButton.setPreferredSize(buttonSize);
updateButton.setPreferredSize(buttonSize);
deleteButton.setPreferredSize(buttonSize);
queryButton.setPreferredSize(buttonSize);
refreshButton.setPreferredSize(buttonSize);
// 按钮事件
addButton.addActionListener(e -> {
new AddSalesShipment();
if (refreshAction != null) {
refreshAction.run();
}
});
updateButton.addActionListener(e -> {
if (table.getSelectedRow() != -1) {
int selectedRow = table.getSelectedRow();
if (table.getRowSorter() != null) {
selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
}
int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
new UpdateSalesShipment(shipmentId);
} else {
new UpdateSalesShipment();
}
if (refreshAction != null) {
refreshAction.run();
}
});
deleteButton.addActionListener(e -> {
if (table.getSelectedRow() != -1) {
int selectedRow = table.getSelectedRow();
if (table.getRowSorter() != null) {
selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
}
int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
new DeleteSalesShipment(shipmentId);
} else {
new DeleteSalesShipment();
}
if (refreshAction != null) {
refreshAction.run();
}
});
queryButton.addActionListener(e -> {
Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
AdvancedSearchSalesShipmentDialog dialog = new AdvancedSearchSalesShipmentDialog(window, table);
dialog.setVisible(true);
if (dialog.isConfirmed() && refreshAction != null) {
refreshAction.run();
updateStatusMessage("已执行高级查询");
}
});
refreshButton.addActionListener(e -> {
SelectSalesShipment.resetSearchStatus();
if (refreshAction != null) {
refreshAction.run();
updateStatusMessage("销售发货数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(updateButton);
buttonPanel.add(deleteButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(BUTTON_FONT);
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
// 设置按钮圆角
button.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
button.setMargin(new Insets(5, 10, 5, 10));
// 添加鼠标悬停效果
button.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
button.setBackground(brightenColor(bgColor, 0.1f));
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
button.setBackground(bgColor);
}
});
return button;
}
/**
*
*
* @param color
* @param factor
* @return
*/
private static Color brightenColor(Color color, float factor) {
int r = Math.min(255, (int) (color.getRed() * (1 + factor)));
int g = Math.min(255, (int) (color.getGreen() * (1 + factor)));
int b = Math.min(255, (int) (color.getBlue() * (1 + factor)));
return new Color(r, g, b);
}
/**
*
*
* @return
*/
public static JScrollPane createShipmentsTable() {
// 表格列名
String[] columnNames = {"发货单ID", "发货单号", "关联订单ID", "仓库ID", "发货日期",
"承运商", "物流单号", "运输方式", "状态", "备注",
"创建时间", "更新时间"};
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0 || columnIndex == 2 || columnIndex == 3) {
return Integer.class; // ID列使用整数类型
}
return String.class;
}
};
// 创建表格
table = new JTable(model);
table.setRowHeight(35);
table.setFont(TABLE_CELL_FONT);
table.getTableHeader().setFont(TABLE_HEADER_FONT);
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
table.getTableHeader().setOpaque(true);
table.getTableHeader().setReorderingAllowed(false); // 禁止拖动列
table.getTableHeader().setResizingAllowed(true); // 允许调整列宽
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
table.setFillsViewportHeight(true);
// 设置表格自动调整大小模式
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// 设置交替行颜色
table.setDefaultRenderer(Object.class, new TableCellRenderer() {
private final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel label = (JLabel) c;
label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
// 居中显示
if (column != 9) { // 备注列除外
label.setHorizontalAlignment(JLabel.CENTER);
}
// 设置行背景颜色
if (isSelected) {
c.setBackground(HIGHLIGHT_ROW_COLOR);
c.setForeground(PRIMARY_COLOR);
} else {
c.setBackground(row % 2 == 0 ? Color.WHITE : ALTERNATE_ROW_COLOR);
c.setForeground(Color.BLACK);
}
// 设置状态的显示样式
if (column == 8 && value != null) { // 状态列
String status = value.toString();
if (STATUS_COLORS.containsKey(status)) {
label.setForeground(Color.WHITE);
label.setBackground(STATUS_COLORS.get(status));
label.setOpaque(true);
label.setBorder(BorderFactory.createEmptyBorder(2, 8, 2, 8));
label.setHorizontalAlignment(JLabel.CENTER);
}
}
}
return c;
}
});
// 设置表格列宽
int[] columnWidths = {70, 100, 70, 70, 100, 100, 100, 100, 100, 200, 150, 150};
for (int i = 0; i < Math.min(columnWidths.length, table.getColumnModel().getColumnCount()); i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
}
// 添加双击打开编辑功能
table.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() == 2) {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
if (table.getRowSorter() != null) {
selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
}
int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
new UpdateSalesShipment(shipmentId);
}
}
}
});
// 设置表格排序
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
table.setRowSorter(sorter);
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
return scrollPane;
}
/**
*
*
* @param table
* @param shipmentsList
*/
public static void updateTableData(JTable table, List<SalesShipments> shipmentsList) {
if (table == null) return;
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (SalesShipments shipment : shipmentsList) {
// 获取状态的显示文本
String statusDisplay = STATUS_MAP.getOrDefault(shipment.getStatus(), shipment.getStatus());
Object[] rowData = {
shipment.getShipmentId(),
shipment.getShipmentNumber(),
shipment.getOrderId(),
shipment.getWarehouseId(),
shipment.getShipmentDate() != null ? shipment.getShipmentDate().format(DATE_FORMATTER) : "",
shipment.getCarrier(),
shipment.getTrackingNumber(),
shipment.getShippingMethod(),
statusDisplay,
shipment.getNotes(),
shipment.getCreatedTime() != null ? shipment.getCreatedTime().format(DATETIME_FORMATTER) : "",
shipment.getUpdatedTime() != null ? shipment.getUpdatedTime().format(DATETIME_FORMATTER) : ""
};
model.addRow(rowData);
}
// 更新状态栏信息
Component parent = table.getParent();
while (parent != null && !(parent instanceof JPanel)) {
parent = parent.getParent();
}
if (parent != null) {
Component[] components = parent.getParent().getComponents();
for (Component component : components) {
if (component instanceof JPanel && ((JPanel) component).getComponentCount() > 0) {
Component c = ((JPanel) component).getComponent(0);
if (c instanceof JLabel) {
JLabel statusLabel = (JLabel) c;
break;
}
}
}
}
}
}

@ -1,667 +0,0 @@
package com.xky.ui.module.salesManagement.add;
import com.xky.pojo.SalesOrders;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
/**
* -
*/
public class AddSalesOrder extends JFrame {
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SUCCESS_COLOR = new Color(46, 139, 87);
private static final Color ERROR_COLOR = new Color(178, 34, 34);
// 日期格式化
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 文本字段
private final JTextField orderNumberField;
private final JTextField customerIdField;
private final JTextField orderDateField;
private final JTextField expectedShipDateField;
private final JTextField actualShipDateField;
private final JTextField warehouseIdField;
private final JComboBox<String> orderStatusComboBox;
private final JComboBox<String> paymentStatusComboBox;
private final JTextField subtotalField;
private final JTextField taxAmountField;
private final JTextField discountAmountField;
private final JTextField totalAmountField;
private final JTextField paidAmountField;
private final JTextArea notesArea;
private final JTextField createdByField;
/**
*
*/
public AddSalesOrder() {
// 设置窗口属性
setTitle("添加销售订单");
setSize(500, 750);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
mainPanel.setBackground(SECONDARY_COLOR);
// 创建标题标签
JLabel titleLabel = new JLabel("添加销售订单", JLabel.CENTER);
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titleLabel.setBorder(new EmptyBorder(0, 0, 15, 0));
// 初始化文本字段
orderNumberField = new JTextField(20);
customerIdField = new JTextField(20);
orderDateField = new JTextField(20);
expectedShipDateField = new JTextField(20);
actualShipDateField = new JTextField(20);
warehouseIdField = new JTextField(20);
orderStatusComboBox = new JComboBox<>(new String[]{"待处理", "已确认", "已发货", "已完成", "已取消"});
paymentStatusComboBox = new JComboBox<>(new String[]{"未支付", "部分支付", "已支付", "已退款"});
subtotalField = new JTextField(20);
taxAmountField = new JTextField(20);
discountAmountField = new JTextField(20);
totalAmountField = new JTextField(20);
paidAmountField = new JTextField(20);
notesArea = new JTextArea(3, 20);
createdByField = new JTextField(20);
// 设置默认值和提示
orderDateField.setText(LocalDate.now().format(DATE_FORMATTER));
// 设置今天日期并添加自动计算总金额的焦点监听器
setupFieldListeners();
// 创建表单面板 - 使用JScrollPane包装以支持滚动
JScrollPane scrollPane = new JScrollPane(createFormPanel());
scrollPane.setBorder(null);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
// 创建按钮面板
JPanel buttonPanel = createButtonPanel();
// 添加组件到主面板
mainPanel.add(titleLabel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
// 设置内容面板
setContentPane(mainPanel);
// 显示窗口
setVisible(true);
}
/**
*
* @return
*/
private JPanel createFormPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(SECONDARY_COLOR);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(8, 8, 8, 8);
gbc.anchor = GridBagConstraints.WEST;
// 创建字段标签样式
Font labelFont = new Font("微软雅黑", Font.BOLD, 13);
// 订单基本信息区域
addSectionHeader(panel, "订单基本信息", gbc, 0);
// 订单编号
addFormField(panel, "订单编号:", orderNumberField, "必填项", gbc, 1, labelFont);
// 客户ID
addFormField(panel, "客户ID:", customerIdField, "必填项,必须为数字", gbc, 2, labelFont);
// 下单日期
addFormField(panel, "下单日期:", orderDateField, "格式: yyyy-MM-dd", gbc, 3, labelFont);
// 预计发货日期
addFormField(panel, "预计发货日期:", expectedShipDateField, "格式: yyyy-MM-dd", gbc, 4, labelFont);
// 实际发货日期
addFormField(panel, "实际发货日期:", actualShipDateField, "格式: yyyy-MM-dd", gbc, 5, labelFont);
// 仓库ID
addFormField(panel, "仓库ID:", warehouseIdField, "必填项,必须为数字", gbc, 6, labelFont);
// 订单状态区域
addSectionHeader(panel, "订单状态", gbc, 7);
// 订单状态
addFormField(panel, "订单状态:", orderStatusComboBox, null, gbc, 8, labelFont);
// 支付状态
addFormField(panel, "支付状态:", paymentStatusComboBox, null, gbc, 9, labelFont);
// 财务信息区域
addSectionHeader(panel, "财务信息", gbc, 10);
// 商品总额
addFormField(panel, "商品总额:", subtotalField, "必填项,必须为数字", gbc, 11, labelFont);
// 税额
addFormField(panel, "税额:", taxAmountField, "必填项,必须为数字", gbc, 12, labelFont);
// 折扣金额
addFormField(panel, "折扣金额:", discountAmountField, "必填项,必须为数字", gbc, 13, labelFont);
// 订单总金额
addFormField(panel, "订单总金额:", totalAmountField, "必填项,必须为数字", gbc, 14, labelFont);
// 已付金额
addFormField(panel, "已付金额:", paidAmountField, "必填项,必须为数字", gbc, 15, labelFont);
// 其他信息区域
addSectionHeader(panel, "其他信息", gbc, 16);
// 备注
gbc.gridx = 0;
gbc.gridy = 17;
JLabel notesLabel = new JLabel("备注:");
notesLabel.setFont(labelFont);
panel.add(notesLabel, gbc);
gbc.gridx = 1;
notesArea.setLineWrap(true);
notesArea.setWrapStyleWord(true);
JScrollPane notesScrollPane = new JScrollPane(notesArea);
notesScrollPane.setPreferredSize(new Dimension(300, 80));
panel.add(notesScrollPane, gbc);
return panel;
}
/**
*
* @return
*/
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel.setBackground(SECONDARY_COLOR);
// 创建保存按钮
JButton saveButton = createStyledButton("保存", BUTTON_COLOR);
saveButton.addActionListener(e -> saveSalesOrder());
// 创建取消按钮
JButton cancelButton = createStyledButton("取消", Color.LIGHT_GRAY);
cancelButton.addActionListener(e -> dispose());
// 创建重置按钮
JButton resetButton = createStyledButton("重置", new Color(220, 20, 60));
resetButton.addActionListener(e -> resetForm());
// 添加按钮到面板
panel.add(saveButton);
panel.add(resetButton);
panel.add(cancelButton);
return panel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 14));
button.setPreferredSize(new Dimension(100, 38));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
return button;
}
/**
*
* @param panel
* @param labelText
* @param component
* @param tooltip
* @param gbc
* @param gridY Y
* @param labelFont
*/
private void addFormField(JPanel panel, String labelText, JComponent component,
String tooltip, GridBagConstraints gbc, int gridY, Font labelFont) {
gbc.gridx = 0;
gbc.gridy = gridY;
JLabel label = new JLabel(labelText);
label.setFont(labelFont);
panel.add(label, gbc);
gbc.gridx = 1;
if (component instanceof JTextField) {
JTextField textField = (JTextField) component;
textField.setBorder(BorderFactory.createCompoundBorder(
textField.getBorder(),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
if (tooltip != null) {
textField.setToolTipText(tooltip);
}
}
panel.add(component, gbc);
}
/**
*
* @param panel
* @param title
* @param gbc
* @param gridY Y
*/
private void addSectionHeader(JPanel panel, String title, GridBagConstraints gbc, int gridY) {
gbc.gridx = 0;
gbc.gridy = gridY;
gbc.gridwidth = 2;
JLabel sectionLabel = new JLabel(title);
sectionLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
sectionLabel.setForeground(PRIMARY_COLOR);
sectionLabel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, PRIMARY_COLOR),
BorderFactory.createEmptyBorder(5, 0, 5, 0)
));
panel.add(sectionLabel, gbc);
// 重置网格宽度
gbc.gridwidth = 1;
}
/**
*
*/
private void setupFieldListeners() {
// 焦点监听器,用于自动计算总金额
FocusAdapter amountCalculator = new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
calculateTotalAmount();
}
};
// 添加焦点监听器到金额字段
subtotalField.addFocusListener(amountCalculator);
taxAmountField.addFocusListener(amountCalculator);
discountAmountField.addFocusListener(amountCalculator);
}
/**
*
*/
private void calculateTotalAmount() {
try {
// 获取各个金额字段的值
BigDecimal subtotal = getDecimalValue(subtotalField.getText(), BigDecimal.ZERO);
BigDecimal taxAmount = getDecimalValue(taxAmountField.getText(), BigDecimal.ZERO);
BigDecimal discountAmount = getDecimalValue(discountAmountField.getText(), BigDecimal.ZERO);
// 计算总金额: subtotal + taxAmount - discountAmount
BigDecimal totalAmount = subtotal.add(taxAmount).subtract(discountAmount);
// 更新总金额字段
totalAmountField.setText(totalAmount.toString());
} catch (NumberFormatException e) {
// 忽略非数字输入
}
}
/**
* BigDecimal
* @param text
* @param defaultValue
* @return BigDecimal
*/
private BigDecimal getDecimalValue(String text, BigDecimal defaultValue) {
if (text == null || text.trim().isEmpty()) {
return defaultValue;
}
try {
return new BigDecimal(text.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
*
*/
private void resetForm() {
// 重置所有字段
orderNumberField.setText("");
customerIdField.setText("");
orderDateField.setText(LocalDate.now().format(DATE_FORMATTER));
expectedShipDateField.setText("");
actualShipDateField.setText("");
warehouseIdField.setText("");
orderStatusComboBox.setSelectedIndex(0);
paymentStatusComboBox.setSelectedIndex(0);
subtotalField.setText("");
taxAmountField.setText("");
discountAmountField.setText("");
totalAmountField.setText("");
paidAmountField.setText("");
notesArea.setText("");
}
/**
*
*/
private void saveSalesOrder() {
// 验证输入
if (!validateInput()) {
return;
}
try {
// 构造销售订单对象
SalesOrders order = constructSalesOrder();
// 保存到数据库
if (insertSalesOrder(order)) {
showMessage("销售订单添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
showMessage("销售订单添加失败!", "错误", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
showMessage("发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
/**
*
* @param message
* @param title
* @param messageType
*/
private void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(this, message, title, messageType);
}
/**
*
* @return
*/
private boolean validateInput() {
// 验证订单编号
if (orderNumberField.getText().trim().isEmpty()) {
showMessage("请输入订单编号!", "输入错误", JOptionPane.ERROR_MESSAGE);
orderNumberField.requestFocus();
return false;
}
// 验证客户ID
try {
Integer.parseInt(customerIdField.getText().trim());
} catch (NumberFormatException e) {
showMessage("客户ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
customerIdField.requestFocus();
return false;
}
// 验证下单日期
try {
LocalDate.parse(orderDateField.getText().trim(), DATE_FORMATTER);
} catch (DateTimeParseException e) {
showMessage("下单日期格式不正确请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
orderDateField.requestFocus();
return false;
}
// 验证预计发货日期
if (!expectedShipDateField.getText().trim().isEmpty()) {
try {
LocalDate.parse(expectedShipDateField.getText().trim(), DATE_FORMATTER);
} catch (DateTimeParseException e) {
showMessage("预计发货日期格式不正确请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
expectedShipDateField.requestFocus();
return false;
}
}
// 验证实际发货日期
if (!actualShipDateField.getText().trim().isEmpty()) {
try {
LocalDate.parse(actualShipDateField.getText().trim(), DATE_FORMATTER);
} catch (DateTimeParseException e) {
showMessage("实际发货日期格式不正确请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
actualShipDateField.requestFocus();
return false;
}
}
// 验证仓库ID
try {
Integer.parseInt(warehouseIdField.getText().trim());
} catch (NumberFormatException e) {
showMessage("仓库ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
warehouseIdField.requestFocus();
return false;
}
// 验证金额字段
String[] amountFields = {
subtotalField.getText().trim(),
taxAmountField.getText().trim(),
discountAmountField.getText().trim(),
totalAmountField.getText().trim(),
paidAmountField.getText().trim()
};
String[] fieldNames = {
"商品总额", "税额", "折扣金额", "订单总金额", "已付金额"
};
JTextField[] fields = {
subtotalField, taxAmountField, discountAmountField,
totalAmountField, paidAmountField
};
for (int i = 0; i < amountFields.length; i++) {
try {
new BigDecimal(amountFields[i]);
} catch (NumberFormatException e) {
showMessage(fieldNames[i] + "必须是有效的数字!", "输入错误", JOptionPane.ERROR_MESSAGE);
fields[i].requestFocus();
return false;
}
}
return true;
}
/**
*
* @return z
*/
private SalesOrders constructSalesOrder() {
SalesOrders order = new SalesOrders();
order.setOrderNumber(orderNumberField.getText().trim());
order.setCustomerId(Integer.parseInt(customerIdField.getText().trim()));
// 设置日期和时间
LocalDateTime orderTime = LocalDate.parse(orderDateField.getText().trim(), DATE_FORMATTER).atStartOfDay();
order.setOrderDate(orderTime);
if (!expectedShipDateField.getText().trim().isEmpty()) {
LocalDate expectedShipDate = LocalDate.parse(expectedShipDateField.getText().trim(), DATE_FORMATTER);
order.setExpectedShipDate(expectedShipDate);
}
if (!actualShipDateField.getText().trim().isEmpty()) {
LocalDate actualShipDate = LocalDate.parse(actualShipDateField.getText().trim(), DATE_FORMATTER);
order.setActualShipDate(actualShipDate);
}
order.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
// 根据选择的订单状态设置订单状态代码
String orderStatusText = (String) orderStatusComboBox.getSelectedItem();
String orderStatusCode = convertOrderStatusToCode(orderStatusText);
order.setOrderStatus(orderStatusCode);
// 根据选择的支付状态设置支付状态代码
String paymentStatusText = (String) paymentStatusComboBox.getSelectedItem();
String paymentStatusCode = convertPaymentStatusToCode(paymentStatusText);
order.setPaymentStatus(paymentStatusCode);
order.setSubtotal(new BigDecimal(subtotalField.getText().trim()));
order.setTaxAmount(new BigDecimal(taxAmountField.getText().trim()));
order.setDiscountAmount(new BigDecimal(discountAmountField.getText().trim()));
order.setTotalAmount(new BigDecimal(totalAmountField.getText().trim()));
order.setPaidAmount(new BigDecimal(paidAmountField.getText().trim()));
order.setNotes(notesArea.getText().trim());
if (!createdByField.getText().trim().isEmpty()) {
order.setCreatedBy(Integer.parseInt(createdByField.getText().trim()));
}
order.setCreatedTime(LocalDateTime.now());
order.setUpdatedTime(LocalDateTime.now());
return order;
}
/**
*
* @param statusText
* @return
*/
private String convertOrderStatusToCode(String statusText) {
switch (statusText) {
case "待处理": return "PENDING";
case "已确认": return "CONFIRMED";
case "已发货": return "SHIPPED";
case "已完成": return "COMPLETED";
case "已取消": return "CANCELLED";
default: return "PENDING";
}
}
/**
*
* @param statusText
* @return
*/
private String convertPaymentStatusToCode(String statusText) {
switch (statusText) {
case "未支付": return "UNPAID";
case "部分支付": return "PARTIAL";
case "已支付": return "PAID";
case "已退款": return "REFUNDED";
default: return "UNPAID";
}
}
/**
*
* @param order
* @return
*/
private boolean insertSalesOrder(SalesOrders order) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtils.getConnection();
String sql = "INSERT INTO sales_orders (order_number, customer_id, order_date, expected_ship_date, " +
"actual_ship_date, warehouse_id, order_status, payment_status, " +
"subtotal, tax_amount, discount_amount, total_amount, paid_amount, " +
"notes, created_time, updated_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
int index = 1;
pstmt.setString(index++, order.getOrderNumber());
pstmt.setInt(index++, order.getCustomerId());
pstmt.setTimestamp(index++, Timestamp.valueOf(order.getOrderDate()));
if (order.getExpectedShipDate() != null) {
pstmt.setDate(index++, java.sql.Date.valueOf(order.getExpectedShipDate()));
} else {
pstmt.setNull(index++, java.sql.Types.DATE);
}
if (order.getActualShipDate() != null) {
pstmt.setDate(index++, java.sql.Date.valueOf(order.getActualShipDate()));
} else {
pstmt.setNull(index++, java.sql.Types.DATE);
}
pstmt.setInt(index++, order.getWarehouseId());
pstmt.setString(index++, order.getOrderStatus());
pstmt.setString(index++, order.getPaymentStatus());
pstmt.setBigDecimal(index++, order.getSubtotal());
pstmt.setBigDecimal(index++, order.getTaxAmount());
pstmt.setBigDecimal(index++, order.getDiscountAmount());
pstmt.setBigDecimal(index++, order.getTotalAmount());
pstmt.setBigDecimal(index++, order.getPaidAmount());
pstmt.setString(index++, order.getNotes());
pstmt.setTimestamp(index++, Timestamp.valueOf(order.getCreatedTime()));
pstmt.setTimestamp(index++, Timestamp.valueOf(order.getUpdatedTime()));
int rowsAffected = pstmt.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
showMessage("数据库错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
return false;
} finally {
DBUtils.closeAll(conn, pstmt, null);
}
}
/**
*
*/
public static void main(String[] args) {
try {
// 使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// 启动应用程序
SwingUtilities.invokeLater(AddSalesOrder::new);
}
}

@ -1,556 +0,0 @@
package com.xky.ui.module.salesManagement.add;
import com.xky.pojo.SalesShipments;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class AddSalesShipment extends JDialog {
// 表单字段
private JTextField shipmentNumberField; // shipmentNumber - 发货单号
private JTextField orderIdField; // orderId - 关联订单ID
private JTextField warehouseIdField; // warehouseId - 发货仓库ID
private JTextField shipmentDateField; // shipmentDate - 发货日期
private JTextField carrierField; // carrier - 承运商
private JTextField trackingNumberField; // trackingNumber - 物流单号
private JComboBox<String> shippingMethodComboBox; // shippingMethod - 运输方式
private JComboBox<String> statusComboBox; // status - 状态
private JTextArea notesArea; // notes - 备注
// 日期格式
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 状态映射
private static final Map<String, String> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put("待发货", "pending");
STATUS_MAP.put("已发货", "shipped");
STATUS_MAP.put("运输中", "in_transit");
STATUS_MAP.put("已签收", "delivered");
STATUS_MAP.put("已取消", "cancelled");
}
// 颜色常量
private static final Color PRIMARY_COLOR = new Color(52, 152, 219); // 蓝色
private static final Color SECONDARY_COLOR = new Color(41, 128, 185); // 深蓝色
private static final Color BACKGROUND_COLOR = new Color(248, 249, 250); // 浅灰色背景
private static final Color TEXT_COLOR = new Color(44, 62, 80); // 深色文本
private static final Color FIELD_BACKGROUND = new Color(255, 255, 255); // 输入框背景
private static final Color SUCCESS_COLOR = new Color(46, 204, 113); // 成功绿色
private static final Color CANCEL_COLOR = new Color(189, 195, 199); // 取消按钮灰色
/**
*
*/
public AddSalesShipment() {
try {
// 使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// 设置窗口属性
setTitle("添加销售发货单");
setSize(500, 700);
setLocationRelativeTo(null);
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// 初始化组件
initComponents();
// 显示对话框
setVisible(true);
}
/**
*
*/
private void initComponents() {
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout(0, 0));
mainPanel.setBackground(BACKGROUND_COLOR);
// 创建顶部标题面板
JPanel headerPanel = createHeaderPanel();
// 创建表单面板
JScrollPane formPanel = createFormPanel();
// 创建按钮面板
JPanel buttonPanel = createButtonPanel();
// 将面板添加到主面板
mainPanel.add(headerPanel, BorderLayout.NORTH);
mainPanel.add(formPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
// 添加到对话框
add(mainPanel);
}
/**
*
*/
private JPanel createHeaderPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, PRIMARY_COLOR, 0, h, SECONDARY_COLOR);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(500, 60));
JLabel titleLabel = new JLabel("新增销售发货单", JLabel.CENTER);
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
titleLabel.setForeground(Color.WHITE);
titleLabel.setBorder(new EmptyBorder(10, 0, 10, 0));
panel.add(titleLabel, BorderLayout.CENTER);
return panel;
}
/**
*
*/
private JScrollPane createFormPanel() {
// 初始化输入组件
shipmentNumberField = createTextField(15); // shipmentNumber - 发货单号
orderIdField = createTextField(15); // orderId - 关联订单ID
warehouseIdField = createTextField(15); // warehouseId - 发货仓库ID
shipmentDateField = createTextField(15); // shipmentDate - 发货日期
shipmentDateField.setText(LocalDate.now().format(DATE_FORMATTER));
shipmentDateField.setToolTipText("格式yyyy-MM-dd");
carrierField = createTextField(15); // carrier - 承运商
trackingNumberField = createTextField(15); // trackingNumber - 物流单号
String[] shippingMethods = {"顺丰速运", "京东物流", "中通快递","圆通速递","申通快递","极兔速递"};
shippingMethodComboBox = createComboBox(shippingMethods); // shippingMethod - 运输方式
String[] statuses = {"待发货", "已发货", "运输中", "已签收", "已取消"};
statusComboBox = createComboBox(statuses); // status - 状态
notesArea = createTextArea(5, 20); // notes - 备注
// 创建主表单面板
JPanel formPanel = new JPanel();
formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
formPanel.setBackground(BACKGROUND_COLOR);
formPanel.setBorder(new EmptyBorder(15, 20, 15, 20));
// 基本信息面板
JPanel basicInfoPanel = createSectionPanel("基本信息");
GridBagLayout basicLayout = new GridBagLayout();
basicInfoPanel.setLayout(basicLayout);
// 添加基本信息字段
addFormField(basicInfoPanel, "发货单号:", shipmentNumberField, 0); // shipmentNumber
addFormField(basicInfoPanel, "关联订单ID:", orderIdField, 1); // orderId
addFormField(basicInfoPanel, "发货仓库ID:", warehouseIdField, 2); // warehouseId
// 发货信息面板
JPanel shipmentInfoPanel = createSectionPanel("发货信息");
GridBagLayout shipmentLayout = new GridBagLayout();
shipmentInfoPanel.setLayout(shipmentLayout);
// 添加发货信息字段
addFormField(shipmentInfoPanel, "发货日期:", shipmentDateField, 0); // shipmentDate
addFormField(shipmentInfoPanel, "承运商:", carrierField, 1); // carrier
addFormField(shipmentInfoPanel, "物流单号:", trackingNumberField, 2); // trackingNumber
addFormField(shipmentInfoPanel, "运输方式:", shippingMethodComboBox, 3); // shippingMethod
addFormField(shipmentInfoPanel, "状态:", statusComboBox, 4); // status
// 备注信息面板
JPanel notesPanel = createSectionPanel("备注信息");
notesPanel.setLayout(new BorderLayout(0, 5));
JScrollPane notesScrollPane = new JScrollPane(notesArea);
notesScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
notesScrollPane.setPreferredSize(new Dimension(0, 80));
notesPanel.add(notesScrollPane, BorderLayout.CENTER);
// 添加所有部分到表单面板
formPanel.add(basicInfoPanel);
formPanel.add(Box.createVerticalStrut(10));
formPanel.add(shipmentInfoPanel);
formPanel.add(Box.createVerticalStrut(10));
formPanel.add(notesPanel);
JScrollPane scrollPane = new JScrollPane(formPanel);
scrollPane.setBorder(null);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
return scrollPane;
}
/**
*
*/
private JPanel createSectionPanel(String title) {
JPanel panel = new JPanel();
panel.setBackground(BACKGROUND_COLOR);
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(PRIMARY_COLOR, 1, true),
title,
TitledBorder.LEFT,
TitledBorder.TOP,
new Font("微软雅黑", Font.BOLD, 12)
));
return panel;
}
/**
*
*/
private void addFormField(JPanel panel, String labelText, JComponent field, int row) {
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.gridx = 0;
labelConstraints.gridy = row;
labelConstraints.anchor = GridBagConstraints.EAST;
labelConstraints.insets = new Insets(5, 5, 5, 10);
GridBagConstraints fieldConstraints = new GridBagConstraints();
fieldConstraints.gridx = 1;
fieldConstraints.gridy = row;
fieldConstraints.fill = GridBagConstraints.HORIZONTAL;
fieldConstraints.weightx = 1.0;
fieldConstraints.insets = new Insets(5, 0, 5, 5);
JLabel label = new JLabel(labelText);
label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
label.setForeground(TEXT_COLOR);
panel.add(label, labelConstraints);
panel.add(field, fieldConstraints);
}
/**
*
*/
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 15));
panel.setBackground(BACKGROUND_COLOR);
JButton saveButton = new JButton("保存");
styleButton(saveButton, SUCCESS_COLOR);
JButton cancelButton = new JButton("取消");
styleButton(cancelButton, CANCEL_COLOR);
panel.add(saveButton);
panel.add(cancelButton);
// 添加事件监听
saveButton.addActionListener(e -> saveShipment());
cancelButton.addActionListener(e -> dispose());
return panel;
}
/**
*
*/
private void styleButton(JButton button, Color color) {
button.setFont(new Font("微软雅黑", Font.BOLD, 14));
button.setForeground(Color.WHITE);
button.setBackground(color);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setPreferredSize(new Dimension(100, 36));
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
/**
*
*/
private JTextField createTextField(int columns) {
JTextField field = new JTextField(columns);
field.setFont(new Font("微软雅黑", Font.PLAIN, 12));
field.setPreferredSize(new Dimension(field.getPreferredSize().width, 25));
field.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(220, 220, 220)),
BorderFactory.createEmptyBorder(2, 5, 2, 5)
));
field.setBackground(FIELD_BACKGROUND);
return field;
}
/**
*
*/
private JComboBox<String> createComboBox(String[] items) {
JComboBox<String> comboBox = new JComboBox<>(items);
comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));
comboBox.setPreferredSize(new Dimension(comboBox.getPreferredSize().width, 25));
comboBox.setBackground(FIELD_BACKGROUND);
return comboBox;
}
/**
*
*/
private JTextArea createTextArea(int rows, int columns) {
JTextArea area = new JTextArea(rows, columns);
area.setFont(new Font("微软雅黑", Font.PLAIN, 12));
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
area.setBackground(FIELD_BACKGROUND);
return area;
}
/**
*
*/
private void saveShipment() {
try {
// 验证输入
if (!validateInput()) {
return;
}
// 构造发货单对象
SalesShipments shipment = constructSalesShipment();
// 检查订单ID是否存在
if (!orderExists(shipment.getOrderId())) {
JOptionPane.showMessageDialog(this,
"无法保存发货单订单ID " + shipment.getOrderId() + " 不存在请输入正确的订单ID",
"错误", JOptionPane.ERROR_MESSAGE);
orderIdField.requestFocus();
return;
}
// 插入数据库
if (insertSalesShipment(shipment)) {
JOptionPane.showMessageDialog(this,
"发货单保存成功",
"保存成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this,
"发货单保存失败,请重试",
"保存失败", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this,
"保存过程中出错: " + e.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
}
}
/**
*
* @return
*/
private boolean validateInput() {
// 验证发货单号
if (shipmentNumberField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this,
"请输入发货单号",
"输入错误", JOptionPane.ERROR_MESSAGE);
shipmentNumberField.requestFocus();
return false;
}
// 验证订单ID
String orderIdText = orderIdField.getText().trim();
if (orderIdText.isEmpty()) {
JOptionPane.showMessageDialog(this,
"请输入订单ID",
"输入错误", JOptionPane.ERROR_MESSAGE);
orderIdField.requestFocus();
return false;
}
try {
Integer.parseInt(orderIdText);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"订单ID必须是数字",
"输入错误", JOptionPane.ERROR_MESSAGE);
orderIdField.requestFocus();
return false;
}
// 验证仓库ID
String warehouseIdText = warehouseIdField.getText().trim();
if (warehouseIdText.isEmpty()) {
JOptionPane.showMessageDialog(this,
"请输入仓库ID",
"输入错误", JOptionPane.ERROR_MESSAGE);
warehouseIdField.requestFocus();
return false;
}
try {
Integer.parseInt(warehouseIdText);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"仓库ID必须是数字",
"输入错误", JOptionPane.ERROR_MESSAGE);
warehouseIdField.requestFocus();
return false;
}
// 验证日期格式
String shipmentDateText = shipmentDateField.getText().trim();
if (!shipmentDateText.isEmpty()) {
try {
LocalDate.parse(shipmentDateText, DATE_FORMATTER);
} catch (Exception e) {
JOptionPane.showMessageDialog(this,
"发货日期格式不正确请使用yyyy-MM-dd格式",
"输入错误", JOptionPane.ERROR_MESSAGE);
shipmentDateField.requestFocus();
return false;
}
}
return true;
}
/**
*
* @return
*/
private SalesShipments constructSalesShipment() {
SalesShipments shipment = new SalesShipments();
// shipmentId 由数据库自动生成
shipment.setShipmentNumber(shipmentNumberField.getText().trim()); // shipmentNumber - 发货单号
shipment.setOrderId(Integer.parseInt(orderIdField.getText().trim())); // orderId - 关联订单ID
shipment.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim())); // warehouseId - 发货仓库ID
// 设置日期
if (!shipmentDateField.getText().trim().isEmpty()) {
LocalDate shipmentDate = LocalDate.parse(shipmentDateField.getText().trim(), DATE_FORMATTER);
shipment.setShipmentDate(shipmentDate); // shipmentDate - 发货日期
}
shipment.setCarrier(carrierField.getText().trim()); // carrier - 承运商
shipment.setTrackingNumber(trackingNumberField.getText().trim()); // trackingNumber - 物流单号
shipment.setShippingMethod((String) shippingMethodComboBox.getSelectedItem()); // shippingMethod - 运输方式
// 根据选择的状态设置状态代码
String statusText = (String) statusComboBox.getSelectedItem();
String statusCode = STATUS_MAP.get(statusText);
shipment.setStatus(statusCode); // status - 状态
shipment.setNotes(notesArea.getText().trim()); // notes - 备注
// 设置创建和更新时间
LocalDateTime now = LocalDateTime.now();
shipment.setCreatedTime(now); // createdTime - 创建时间
shipment.setUpdatedTime(now); // updatedTime - 更新时间
return shipment;
}
/**
* ID
* @param orderId ID
* @return ID
*/
private boolean orderExists(int orderId) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
String sql = "SELECT COUNT(*) FROM sales_orders WHERE order_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, orderId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param shipment
* @return
*/
private boolean insertSalesShipment(SalesShipments shipment) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtils.getConnection();
String sql = "INSERT INTO sales_shipments (shipment_number, order_id, warehouse_id, shipment_date, carrier, tracking_number, shipping_method, status, notes, created_time, updated_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
int index = 1;
pstmt.setString(index++, shipment.getShipmentNumber());
pstmt.setInt(index++, shipment.getOrderId());
pstmt.setInt(index++, shipment.getWarehouseId());
if (shipment.getShipmentDate() != null) {
pstmt.setDate(index++, java.sql.Date.valueOf(shipment.getShipmentDate()));
} else {
pstmt.setNull(index++, java.sql.Types.DATE);
}
pstmt.setString(index++, shipment.getCarrier());
pstmt.setString(index++, shipment.getTrackingNumber());
pstmt.setString(index++, shipment.getShippingMethod());
pstmt.setString(index++, shipment.getStatus());
pstmt.setString(index++, shipment.getNotes());
pstmt.setTimestamp(index++, Timestamp.valueOf(shipment.getCreatedTime()));
pstmt.setTimestamp(index++, Timestamp.valueOf(shipment.getUpdatedTime()));
int rows = pstmt.executeUpdate();
return rows > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(conn, pstmt, null);
}
}
public static void main(String[] args) {
new AddSalesShipment();
}
}

@ -1,305 +0,0 @@
package com.xky.ui.module.salesManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*/
public class DeleteSalesOrder extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteSalesOrder() {
setTitle("删除销售订单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
/**
* ID
* @param orderId ID
*/
public DeleteSalesOrder(int orderId) {
setTitle("删除销售订单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
// 自动填充订单ID
JTextField idField = (JTextField) ((JPanel)((JPanel)getContentPane().getComponent(0)).getComponent(1)).getComponent(0);
idField.setText(String.valueOf(orderId));
setVisible(true);
}
void init() {
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的销售订单ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有销售订单的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有销售订单");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个销售订单删除按钮事件
jButton.addActionListener(e -> {
String idText = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入你要删除的销售订单ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
Integer id = Integer.valueOf(idText);
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该销售订单吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
if (orderExists(id)) {
deleteSalesOrder(id);
JOptionPane.showMessageDialog(null, "该销售订单删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该销售订单ID,删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有销售订单按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有销售订单信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有销售订单的操作
if (deleteAllSalesOrders()) {
JOptionPane.showMessageDialog(
null,
"所有销售订单已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有销售订单失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
* ID
* @param id ID
* @return
*/
private boolean orderExists(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM sales_orders WHERE order_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param id ID
* @return
*/
public boolean deleteSalesOrder(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM sales_orders WHERE order_id = ?");
preparedStatement.setInt(1, id);
int rows = preparedStatement.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllSalesOrders() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM sales_orders");
int rows = preparedStatement.executeUpdate();
return true; // 即使没有记录被删除也算成功
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
new DeleteSalesOrder();
}
}

@ -1,305 +0,0 @@
package com.xky.ui.module.salesManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*/
public class DeleteSalesShipment extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteSalesShipment() {
setTitle("删除销售发货单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
/**
* ID
* @param shipmentId ID
*/
public DeleteSalesShipment(int shipmentId) {
setTitle("删除销售发货单");
setSize(320, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
// 自动填充发货单ID
JTextField idField = (JTextField) ((JPanel)((JPanel)getContentPane().getComponent(0)).getComponent(1)).getComponent(0);
idField.setText(String.valueOf(shipmentId));
setVisible(true);
}
void init() {
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的销售发货单ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有销售发货单的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有销售发货单");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 16));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个销售发货单删除按钮事件
jButton.addActionListener(e -> {
String idText = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入你要删除的销售发货单ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
Integer id = Integer.valueOf(idText);
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该销售发货单吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
if (shipmentExists(id)) {
deleteSalesShipment(id);
JOptionPane.showMessageDialog(null, "该销售发货单删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该销售发货单ID,删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有销售发货单按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有销售发货单信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有销售发货单的操作
if (deleteAllSalesShipments()) {
JOptionPane.showMessageDialog(
null,
"所有销售发货单已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有销售发货单失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
* ID
* @param id ID
* @return
*/
private boolean shipmentExists(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM sales_shipments WHERE shipment_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param id ID
* @return
*/
public boolean deleteSalesShipment(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM sales_shipments WHERE shipment_id = ?");
preparedStatement.setInt(1, id);
int rows = preparedStatement.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllSalesShipments() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM sales_shipments");
int rows = preparedStatement.executeUpdate();
return true; // 即使没有记录被删除也算成功
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
new DeleteSalesShipment();
}
}

@ -1,614 +0,0 @@
package com.xky.ui.module.salesManagement.select;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder.QueryCriteria;
import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.SalesMassage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
public class AdvancedQueryDialog extends JDialog {
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color RESET_BUTTON_COLOR = new Color(231, 76, 60);
// 定义字体常量
private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 20);
private static final Font LABEL_FONT = new Font("微软雅黑", Font.BOLD, 14);
private static final Font FIELD_FONT = new Font("微软雅黑", Font.PLAIN, 14);
private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
// 状态代码到显示文本的映射
private static final Map<String, String> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put("pending", "待处理");
STATUS_MAP.put("confirmed", "已确认");
STATUS_MAP.put("shipped", "已发货");
STATUS_MAP.put("completed", "已完成");
STATUS_MAP.put("cancelled", "已取消");
}
private static final Map<String, String> PAYMENT_STATUS_MAP = new HashMap<>();
static {
PAYMENT_STATUS_MAP.put("unpaid", "未支付");
PAYMENT_STATUS_MAP.put("partial", "部分支付");
PAYMENT_STATUS_MAP.put("paid", "已支付");
PAYMENT_STATUS_MAP.put("refunded", "已退款");
}
// 反向映射(显示文本到状态代码)
private static final Map<String, String> REVERSE_STATUS_MAP = new HashMap<>();
static {
for (Map.Entry<String, String> entry : STATUS_MAP.entrySet()) {
REVERSE_STATUS_MAP.put(entry.getValue(), entry.getKey());
}
}
private static final Map<String, String> REVERSE_PAYMENT_STATUS_MAP = new HashMap<>();
static {
for (Map.Entry<String, String> entry : PAYMENT_STATUS_MAP.entrySet()) {
REVERSE_PAYMENT_STATUS_MAP.put(entry.getValue(), entry.getKey());
}
}
// 日期格式化器
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 界面组件
private JTextField orderIdField;
private JTextField orderNumberField;
private JTextField customerIdField;
private JTextField startDateField;
private JTextField endDateField;
private JComboBox<String> orderStatusCombo;
private JComboBox<String> paymentStatusCombo;
private JTextField minAmountField;
private JTextField maxAmountField;
private JTextField warehouseIdField;
private JTextField keywordField;
private JTable resultTable;
private DefaultTableModel tableModel;
private JLabel resultCountLabel;
private JTable mainTable; // 主界面表格引用
private Runnable refreshAction; // 刷新主界面的操作
/**
*
* @param mainTable
* @param refreshAction
*/
public AdvancedQueryDialog(JTable mainTable, Runnable refreshAction) {
super(SwingUtilities.getWindowAncestor(mainTable) instanceof Frame ?
(Frame)SwingUtilities.getWindowAncestor(mainTable) : null, "销售订单高级查询", true);
this.mainTable = mainTable;
this.refreshAction = refreshAction;
initComponents();
setupLayout();
setupListeners();
// 设置对话框属性
setSize(1000, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initComponents() {
// 初始化文本字段
orderIdField = createTextField();
orderNumberField = createTextField();
customerIdField = createTextField();
startDateField = createTextField();
endDateField = createTextField();
minAmountField = createTextField();
maxAmountField = createTextField();
warehouseIdField = createTextField();
keywordField = createTextField();
// 初始化下拉框
orderStatusCombo = new JComboBox<>();
orderStatusCombo.addItem("全部");
for (String status : STATUS_MAP.values()) {
orderStatusCombo.addItem(status);
}
orderStatusCombo.setFont(FIELD_FONT);
orderStatusCombo.setBackground(Color.WHITE);
paymentStatusCombo = new JComboBox<>();
paymentStatusCombo.addItem("全部");
for (String status : PAYMENT_STATUS_MAP.values()) {
paymentStatusCombo.addItem(status);
}
paymentStatusCombo.setFont(FIELD_FONT);
paymentStatusCombo.setBackground(Color.WHITE);
// 初始化表格
String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "订单状态", "支付状态", "订单总金额"};
tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(FIELD_FONT);
resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
resultTable.getTableHeader().setForeground(Color.BLACK);
resultTable.getTableHeader().setOpaque(true);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
// 设置列宽
resultTable.getColumnModel().getColumn(0).setPreferredWidth(70);
resultTable.getColumnModel().getColumn(1).setPreferredWidth(120);
resultTable.getColumnModel().getColumn(2).setPreferredWidth(70);
resultTable.getColumnModel().getColumn(3).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(4).setPreferredWidth(100);
resultTable.getColumnModel().getColumn(5).setPreferredWidth(100);
resultTable.getColumnModel().getColumn(6).setPreferredWidth(120);
// 结果计数标签
resultCountLabel = new JLabel("查询结果: 0 条记录");
resultCountLabel.setFont(LABEL_FONT);
}
/**
*
* @return
*/
private JTextField createTextField() {
JTextField textField = new JTextField();
textField.setFont(FIELD_FONT);
textField.setPreferredSize(new Dimension(150, 30));
return textField;
}
/**
*
*/
private void setupLayout() {
setLayout(new BorderLayout(10, 10));
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("销售订单高级查询");
titleLabel.setFont(TITLE_FONT);
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 查询条件面板
JPanel criteriaPanel = new JPanel(new GridBagLayout());
criteriaPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(PRIMARY_COLOR),
"查询条件",
TitledBorder.LEFT,
TitledBorder.TOP,
LABEL_FONT,
PRIMARY_COLOR));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
// 第一行
gbc.gridx = 0;
gbc.gridy = 0;
criteriaPanel.add(createLabelWithFont("订单ID:"), gbc);
gbc.gridx = 1;
criteriaPanel.add(orderIdField, gbc);
gbc.gridx = 2;
criteriaPanel.add(createLabelWithFont("订单编号:"), gbc);
gbc.gridx = 3;
criteriaPanel.add(orderNumberField, gbc);
gbc.gridx = 4;
criteriaPanel.add(createLabelWithFont("客户ID:"), gbc);
gbc.gridx = 5;
criteriaPanel.add(customerIdField, gbc);
// 第二行
gbc.gridx = 0;
gbc.gridy = 1;
criteriaPanel.add(createLabelWithFont("开始日期:"), gbc);
gbc.gridx = 1;
criteriaPanel.add(startDateField, gbc);
gbc.gridx = 2;
criteriaPanel.add(createLabelWithFont("结束日期:"), gbc);
gbc.gridx = 3;
criteriaPanel.add(endDateField, gbc);
gbc.gridx = 4;
criteriaPanel.add(createLabelWithFont("仓库ID:"), gbc);
gbc.gridx = 5;
criteriaPanel.add(warehouseIdField, gbc);
// 第三行
gbc.gridx = 0;
gbc.gridy = 2;
criteriaPanel.add(createLabelWithFont("订单状态:"), gbc);
gbc.gridx = 1;
criteriaPanel.add(orderStatusCombo, gbc);
gbc.gridx = 2;
criteriaPanel.add(createLabelWithFont("支付状态:"), gbc);
gbc.gridx = 3;
criteriaPanel.add(paymentStatusCombo, gbc);
gbc.gridx = 4;
criteriaPanel.add(createLabelWithFont("关键字:"), gbc);
gbc.gridx = 5;
criteriaPanel.add(keywordField, gbc);
// 第四行
gbc.gridx = 0;
gbc.gridy = 3;
criteriaPanel.add(createLabelWithFont("最小金额:"), gbc);
gbc.gridx = 1;
criteriaPanel.add(minAmountField, gbc);
gbc.gridx = 2;
criteriaPanel.add(createLabelWithFont("最大金额:"), gbc);
gbc.gridx = 3;
criteriaPanel.add(maxAmountField, gbc);
// 日期格式提示
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 6;
JLabel dateFormatLabel = new JLabel("日期格式: yyyy-MM-dd (例如: 2023-01-01)");
dateFormatLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
dateFormatLabel.setForeground(Color.GRAY);
criteriaPanel.add(dateFormatLabel, gbc);
// 按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
JButton searchButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton resetButton = createStyledButton("重置", RESET_BUTTON_COLOR);
buttonPanel.add(searchButton);
buttonPanel.add(resetButton);
// 结果面板
JPanel resultPanel = new JPanel(new BorderLayout(5, 5));
resultPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(PRIMARY_COLOR),
"查询结果",
TitledBorder.LEFT,
TitledBorder.TOP,
LABEL_FONT,
PRIMARY_COLOR));
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel resultInfoPanel = new JPanel(new BorderLayout());
resultInfoPanel.add(resultCountLabel, BorderLayout.WEST);
resultPanel.add(resultInfoPanel, BorderLayout.NORTH);
resultPanel.add(scrollPane, BorderLayout.CENTER);
// 底部按钮面板
JPanel bottomButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
bottomButtonPanel.add(selectButton);
bottomButtonPanel.add(cancelButton);
// 顶部面板(标题+查询条件+按钮)
JPanel topPanel = new JPanel(new BorderLayout(10, 10));
topPanel.setBorder(new EmptyBorder(10, 10, 5, 10));
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(criteriaPanel, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 添加到主面板
add(topPanel, BorderLayout.NORTH);
add(resultPanel, BorderLayout.CENTER);
add(bottomButtonPanel, BorderLayout.SOUTH);
// 设置事件监听器
searchButton.addActionListener(e -> performSearch());
resetButton.addActionListener(e -> resetFields());
selectButton.addActionListener(e -> selectRecord());
cancelButton.addActionListener(e -> dispose());
// 设置回车键触发搜索
getRootPane().setDefaultButton(searchButton);
}
/**
*
* @param text
* @return
*/
private JLabel createLabelWithFont(String text) {
JLabel label = new JLabel(text);
label.setFont(LABEL_FONT);
return label;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(BUTTON_FONT);
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
*/
private void setupListeners() {
// 双击选择记录
resultTable.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() == 2) {
selectRecord();
}
}
});
}
/**
*
*/
private void performSearch() {
try {
// 创建查询条件对象
QueryCriteria criteria = new QueryCriteria();
// 设置订单ID
if (!orderIdField.getText().trim().isEmpty()) {
try {
criteria.setOrderId(Integer.parseInt(orderIdField.getText().trim()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "订单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 设置订单编号
if (!orderNumberField.getText().trim().isEmpty()) {
criteria.setOrderNumber(orderNumberField.getText().trim());
}
// 设置客户ID
if (!customerIdField.getText().trim().isEmpty()) {
try {
criteria.setCustomerId(Integer.parseInt(customerIdField.getText().trim()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "客户ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 设置日期范围
if (!startDateField.getText().trim().isEmpty()) {
try {
LocalDate startDate = LocalDate.parse(startDateField.getText().trim(), DATE_FORMATTER);
criteria.setStartDate(startDate);
} catch (DateTimeParseException e) {
JOptionPane.showMessageDialog(this, "开始日期格式不正确请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!endDateField.getText().trim().isEmpty()) {
try {
LocalDate endDate = LocalDate.parse(endDateField.getText().trim(), DATE_FORMATTER);
criteria.setEndDate(endDate);
} catch (DateTimeParseException e) {
JOptionPane.showMessageDialog(this, "结束日期格式不正确请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 设置订单状态
if (orderStatusCombo.getSelectedIndex() > 0) {
String statusDisplay = (String) orderStatusCombo.getSelectedItem();
String statusCode = REVERSE_STATUS_MAP.get(statusDisplay);
criteria.setOrderStatus(statusCode);
}
// 设置支付状态
if (paymentStatusCombo.getSelectedIndex() > 0) {
String statusDisplay = (String) paymentStatusCombo.getSelectedItem();
String statusCode = REVERSE_PAYMENT_STATUS_MAP.get(statusDisplay);
criteria.setPaymentStatus(statusCode);
}
// 设置金额范围
if (!minAmountField.getText().trim().isEmpty()) {
try {
criteria.setMinAmount(BigDecimal.valueOf(Double.parseDouble(minAmountField.getText().trim())));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "最小金额必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!maxAmountField.getText().trim().isEmpty()) {
try {
criteria.setMaxAmount(BigDecimal.valueOf(Double.parseDouble(maxAmountField.getText().trim())));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "最大金额必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 设置仓库ID
if (!warehouseIdField.getText().trim().isEmpty()) {
try {
criteria.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "仓库ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 设置关键字
if (!keywordField.getText().trim().isEmpty()) {
criteria.setKeyword(keywordField.getText().trim());
}
// 执行查询
List<SalesOrders> resultList = SelectSalesOrder.advancedQuery(criteria);
// 更新表格数据
updateTableData(resultList);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "查询发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
/**
*
* @param orderList
*/
private void updateTableData(List<SalesOrders> orderList) {
// 清空表格
tableModel.setRowCount(0);
if (orderList != null && !orderList.isEmpty()) {
for (SalesOrders order : orderList) {
String orderDateStr = order.getOrderDate() != null ?
order.getOrderDate().format(DATETIME_FORMATTER) : "";
tableModel.addRow(new Object[]{
order.getOrderId(),
order.getOrderNumber(),
order.getCustomerId(),
orderDateStr,
STATUS_MAP.get(order.getOrderStatus()),
PAYMENT_STATUS_MAP.get(order.getPaymentStatus()),
order.getTotalAmount()
});
}
resultCountLabel.setText("查询结果: " + orderList.size() + " 条记录");
} else {
resultCountLabel.setText("查询结果: 0 条记录");
JOptionPane.showMessageDialog(this, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
*
*/
private void resetFields() {
orderIdField.setText("");
orderNumberField.setText("");
customerIdField.setText("");
startDateField.setText("");
endDateField.setText("");
orderStatusCombo.setSelectedIndex(0);
paymentStatusCombo.setSelectedIndex(0);
minAmountField.setText("");
maxAmountField.setText("");
warehouseIdField.setText("");
keywordField.setText("");
// 清空表格
tableModel.setRowCount(0);
resultCountLabel.setText("查询结果: 0 条记录");
}
/**
*
*/
private void selectRecord() {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int orderId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的订单数据
List<SalesOrders> orderList = SelectSalesOrder.selectById(orderId);
if (!orderList.isEmpty()) {
// 更新主界面表格
if (mainTable != null) {
SalesMassage.updateTableData(mainTable, orderList);
// 更新状态消息
com.xky.ui.main.MainView.updateStatusMessage("已选择订单ID: " + orderId);
// 关闭对话框
dispose();
}
}
} else {
JOptionPane.showMessageDialog(this, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
*
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
AdvancedQueryDialog dialog = new AdvancedQueryDialog(null, null);
dialog.setVisible(true);
});
}
}

@ -1,569 +0,0 @@
package com.xky.ui.module.salesManagement.select;
import com.xky.pojo.SalesShipments;
import com.xky.ui.main.MainView;
import com.xky.ui.module.salesManagement.SalesShipmentsManagement;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
public class AdvancedSearchSalesShipmentDialog extends JDialog {
// 日期格式化器
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 界面颜色
private static final Color BACKGROUND_COLOR = new Color(240, 248, 255);
private static final Color HEADER_COLOR = new Color(79, 129, 189);
private static final Color BUTTON_COLOR = new Color(65, 131, 196);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
private static final Color RESET_BUTTON_COLOR = new Color(231, 76, 60);
// 界面组件
private JTextField shipmentIdField;
private JTextField shipmentNumberField;
private JTextField orderIdField;
private JTextField warehouseIdField;
private JTextField startDateField;
private JTextField endDateField;
private JTextField carrierField;
private JTextField trackingNumberField;
private JComboBox<String> shippingMethodCombo;
private JComboBox<String> statusCombo;
private JTextField notesField;
private JTable resultTable;
private DefaultTableModel tableModel;
private JButton selectButton;
private JButton cancelButton;
// 数据相关
private JTable mainTable;
private boolean confirmed = false;
private SalesShipments selectedShipment;
/**
*
* @param owner
* @param mainTable
*/
public AdvancedSearchSalesShipmentDialog(Window owner, JTable mainTable) {
super(owner, "查询销售发货单", ModalityType.APPLICATION_MODAL);
this.mainTable = mainTable;
initUI();
}
/**
*
*/
private void initUI() {
// 设置窗口属性
setSize(900, 650);
setLocationRelativeTo(null);
setResizable(false);
// 主面板
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(BACKGROUND_COLOR);
mainPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
// 顶部查询面板
JPanel searchPanel = createSearchPanel();
// 中间表格面板
JScrollPane tableScrollPane = createTablePanel();
// 底部按钮面板
JPanel buttonPanel = createButtonPanel();
// 组装界面
mainPanel.add(searchPanel, BorderLayout.NORTH);
mainPanel.add(tableScrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setContentPane(mainPanel);
}
/**
*
*/
private JPanel createSearchPanel() {
JPanel panel = new JPanel(new BorderLayout(0, 10));
panel.setOpaque(false);
panel.setBorder(new EmptyBorder(0, 0, 10, 0));
// 创建表单面板
JPanel formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
formPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(HEADER_COLOR),
"查询条件",
TitledBorder.LEFT,
TitledBorder.TOP,
new Font("微软雅黑", Font.BOLD, 14),
HEADER_COLOR
));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
// 第一行
gbc.gridx = 0;
gbc.gridy = 0;
formPanel.add(createLabel("发货单ID:"), gbc);
gbc.gridx = 1;
shipmentIdField = createTextField();
formPanel.add(shipmentIdField, gbc);
gbc.gridx = 2;
formPanel.add(createLabel("发货单号:"), gbc);
gbc.gridx = 3;
shipmentNumberField = createTextField();
formPanel.add(shipmentNumberField, gbc);
// 第二行
gbc.gridx = 0;
gbc.gridy = 1;
formPanel.add(createLabel("关联订单ID:"), gbc);
gbc.gridx = 1;
orderIdField = createTextField();
formPanel.add(orderIdField, gbc);
gbc.gridx = 2;
formPanel.add(createLabel("发货仓库ID:"), gbc);
gbc.gridx = 3;
warehouseIdField = createTextField();
formPanel.add(warehouseIdField, gbc);
// 第三行
gbc.gridx = 0;
gbc.gridy = 2;
formPanel.add(createLabel("发货日期从:"), gbc);
gbc.gridx = 1;
startDateField = createTextField();
startDateField.setToolTipText("格式: yyyy-MM-dd");
formPanel.add(startDateField, gbc);
gbc.gridx = 2;
formPanel.add(createLabel("发货日期至:"), gbc);
gbc.gridx = 3;
endDateField = createTextField();
endDateField.setToolTipText("格式: yyyy-MM-dd");
formPanel.add(endDateField, gbc);
// 第四行
gbc.gridx = 0;
gbc.gridy = 3;
formPanel.add(createLabel("承运商:"), gbc);
gbc.gridx = 1;
carrierField = createTextField();
formPanel.add(carrierField, gbc);
gbc.gridx = 2;
formPanel.add(createLabel("物流单号:"), gbc);
gbc.gridx = 3;
trackingNumberField = createTextField();
formPanel.add(trackingNumberField, gbc);
// 第五行
gbc.gridx = 0;
gbc.gridy = 4;
formPanel.add(createLabel("运输方式:"), gbc);
gbc.gridx = 1;
shippingMethodCombo = new JComboBox<>(new String[]{"", "空运", "海运", "陆运", "快递"});
shippingMethodCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
formPanel.add(shippingMethodCombo, gbc);
gbc.gridx = 2;
formPanel.add(createLabel("状态:"), gbc);
gbc.gridx = 3;
statusCombo = new JComboBox<>(new String[]{"", "待发货", "已发货", "运输中", "已签收", "已取消"});
statusCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
formPanel.add(statusCombo, gbc);
// 第六行
gbc.gridx = 0;
gbc.gridy = 5;
formPanel.add(createLabel("备注:"), gbc);
gbc.gridx = 1;
gbc.gridwidth = 3;
notesField = createTextField();
formPanel.add(notesField, gbc);
// 按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
JButton searchButton = new JButton("搜索");
searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
searchButton.setBackground(SEARCH_BUTTON_COLOR);
searchButton.setForeground(Color.WHITE);
searchButton.setPreferredSize(new Dimension(100, 35));
searchButton.setFocusPainted(false);
searchButton.setBorderPainted(false);
searchButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
JButton resetButton = new JButton("重置");
resetButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
resetButton.setBackground(RESET_BUTTON_COLOR);
resetButton.setForeground(Color.WHITE);
resetButton.setPreferredSize(new Dimension(100, 35));
resetButton.setFocusPainted(false);
resetButton.setBorderPainted(false);
resetButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
buttonPanel.add(searchButton);
buttonPanel.add(resetButton);
// 添加搜索按钮事件
searchButton.addActionListener(e -> performSearch());
// 添加重置按钮事件
resetButton.addActionListener(e -> resetForm());
// 组装查询面板
panel.add(formPanel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.SOUTH);
return panel;
}
/**
*
*/
private JLabel createLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(new Font("微软雅黑", Font.BOLD, 14));
return label;
}
/**
*
*/
private JTextField createTextField() {
JTextField textField = new JTextField();
textField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
textField.setPreferredSize(new Dimension(150, 30));
return textField;
}
/**
*
*/
private JScrollPane createTablePanel() {
// 创建表格模型
String[] columnNames = {"发货单ID", "发货单号", "关联订单ID", "仓库ID", "发货日期", "承运商", "物流单号", "运输方式", "状态", "备注"};
tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// 创建表格
resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
resultTable.getTableHeader().setBackground(HEADER_COLOR);
resultTable.getTableHeader().setForeground(Color.BLACK);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
// 设置表格内容居中
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
for (int i = 0; i < resultTable.getColumnCount(); i++) {
resultTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
// 添加双击事件
resultTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
selectShipment();
}
}
});
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));
return scrollPane;
}
/**
*
*/
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
panel.setOpaque(false);
selectButton = new JButton("选择");
selectButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
selectButton.setBackground(BUTTON_COLOR);
selectButton.setForeground(Color.WHITE);
selectButton.setPreferredSize(new Dimension(120, 40));
selectButton.setFocusPainted(false);
selectButton.setBorderPainted(false);
selectButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
cancelButton = new JButton("取消");
cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
cancelButton.setBackground(new Color(231, 76, 60));
cancelButton.setForeground(Color.WHITE);
cancelButton.setPreferredSize(new Dimension(120, 40));
cancelButton.setFocusPainted(false);
cancelButton.setBorderPainted(false);
cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
panel.add(selectButton);
panel.add(cancelButton);
// 添加按钮事件
selectButton.addActionListener(e -> selectShipment());
cancelButton.addActionListener(e -> dispose());
return panel;
}
/**
*
*/
private void performSearch() {
Map<String, Object> conditions = new HashMap<>();
// 收集查询条件
if (!shipmentIdField.getText().trim().isEmpty()) {
try {
int id = Integer.parseInt(shipmentIdField.getText().trim());
conditions.put("shipmentId", id);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "发货单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!shipmentNumberField.getText().trim().isEmpty()) {
conditions.put("shipmentNumber", shipmentNumberField.getText().trim());
}
if (!orderIdField.getText().trim().isEmpty()) {
try {
int orderId = Integer.parseInt(orderIdField.getText().trim());
conditions.put("orderId", orderId);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "订单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!warehouseIdField.getText().trim().isEmpty()) {
try {
int warehouseId = Integer.parseInt(warehouseIdField.getText().trim());
conditions.put("warehouseId", warehouseId);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "仓库ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
// 处理日期范围
if (!startDateField.getText().trim().isEmpty()) {
try {
LocalDate.parse(startDateField.getText().trim(), DATE_FORMATTER);
conditions.put("shipDateFrom", startDateField.getText().trim());
} catch (DateTimeParseException e) {
JOptionPane.showMessageDialog(this, "开始日期格式错误请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!endDateField.getText().trim().isEmpty()) {
try {
LocalDate.parse(endDateField.getText().trim(), DATE_FORMATTER);
conditions.put("shipDateTo", endDateField.getText().trim());
} catch (DateTimeParseException e) {
JOptionPane.showMessageDialog(this, "结束日期格式错误请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (!carrierField.getText().trim().isEmpty()) {
conditions.put("carrier", carrierField.getText().trim());
}
if (!trackingNumberField.getText().trim().isEmpty()) {
conditions.put("trackingNumber", trackingNumberField.getText().trim());
}
if (shippingMethodCombo.getSelectedIndex() > 0) {
conditions.put("shippingMethod", shippingMethodCombo.getSelectedItem().toString());
}
if (statusCombo.getSelectedIndex() > 0) {
conditions.put("status", statusCombo.getSelectedItem().toString());
}
if (!notesField.getText().trim().isEmpty()) {
conditions.put("notes", notesField.getText().trim());
}
// 检查是否有查询条件
if (conditions.isEmpty()) {
JOptionPane.showMessageDialog(this, "请至少输入一个查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
// 执行高级查询
List<SalesShipments> results = SelectSalesShipment.advancedSearchWithMap(conditions);
updateTable(results);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "查询过程中发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
/**
*
*/
private void resetForm() {
shipmentIdField.setText("");
shipmentNumberField.setText("");
orderIdField.setText("");
warehouseIdField.setText("");
startDateField.setText("");
endDateField.setText("");
carrierField.setText("");
trackingNumberField.setText("");
shippingMethodCombo.setSelectedIndex(0);
statusCombo.setSelectedIndex(0);
notesField.setText("");
// 清空表格
tableModel.setRowCount(0);
}
/**
*
*/
private void updateTable(List<SalesShipments> shipments) {
// 清空表格
tableModel.setRowCount(0);
if (shipments == null || shipments.isEmpty()) {
JOptionPane.showMessageDialog(this, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
// 填充表格
for (SalesShipments shipment : shipments) {
String dateStr = shipment.getShipmentDate() != null ?
shipment.getShipmentDate().format(DATE_FORMATTER) : "";
Object[] rowData = {
shipment.getShipmentId(),
shipment.getShipmentNumber(),
shipment.getOrderId(),
shipment.getWarehouseId(),
dateStr,
shipment.getCarrier(),
shipment.getTrackingNumber(),
shipment.getShippingMethod(),
shipment.getStatus(),
shipment.getNotes()
};
tableModel.addRow(rowData);
}
}
/**
*
*/
private void selectShipment() {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow == -1) {
JOptionPane.showMessageDialog(this, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
int id = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的发货单
List<SalesShipments> shipments = SelectSalesShipment.selectById(id);
if (shipments != null && !shipments.isEmpty()) {
selectedShipment = shipments.get(0);
confirmed = true;
// 更新主表格
if (mainTable != null) {
SalesShipmentsManagement.updateTableData(mainTable, shipments);
MainView.updateStatusMessage("已选择发货单ID: " + id);
}
dispose();
}
}
/**
*
*/
public boolean isConfirmed() {
return confirmed;
}
/**
*
*/
public SalesShipments getSelectedShipment() {
return selectedShipment;
}
/**
*
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
AdvancedSearchSalesShipmentDialog dialog = new AdvancedSearchSalesShipmentDialog(null, null);
dialog.setVisible(true);
});
}
}

@ -1,475 +0,0 @@
package com.xky.ui.module.salesManagement.select;
import com.xky.pojo.SalesOrders;
import com.xky.utils.DBUtils;
import javax.swing.JOptionPane;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
*
*/
public class SelectSalesOrder {
private static boolean searchMode = false;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/**
*
*/
public static void resetSearchStatus() {
searchMode = false;
}
/**
*
* @return
*/
public static List<SalesOrders> selectAll() {
String sql = "SELECT * FROM sales_orders ORDER BY order_id DESC";
return executeQuery(sql, null);
}
/**
* ID
* @param id ID
* @return
*/
public static List<SalesOrders> selectById(Integer id) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE order_id = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, id);
});
}
/**
*
* @param orderNumber
* @return
*/
public static List<SalesOrders> selectByOrderNumber(String orderNumber) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE order_number = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setString(1, orderNumber);
});
}
/**
* ID
* @param customerId ID
* @return
*/
public static List<SalesOrders> selectByCustomerId(Integer customerId) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE customer_id = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, customerId);
});
}
/**
*
* @param status
* @return
*/
public static List<SalesOrders> selectByStatus(String status) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE order_status = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setString(1, status);
});
}
/**
*
* @param startDate
* @param endDate
* @return
*/
public static List<SalesOrders> selectByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE order_date BETWEEN ? AND ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setTimestamp(1, Timestamp.valueOf(startDate));
preparedStatement.setTimestamp(2, Timestamp.valueOf(endDate));
});
}
/**
*
* @param keyword
* @return
*/
public static List<SalesOrders> searchByKeyword(String keyword) {
searchMode = true;
String sql = "SELECT * FROM sales_orders WHERE order_number LIKE ? OR notes LIKE ?";
return executeQuery(sql, preparedStatement -> {
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
preparedStatement.setString(2, searchPattern);
});
}
/**
* 使Map
* @param conditions Map
* @return
*/
public static List<SalesOrders> advancedSearchWithMap(Map<String, Object> conditions) {
searchMode = true;
StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM sales_orders WHERE 1=1");
List<Object> params = new ArrayList<>();
// 处理订单ID
if (conditions.containsKey("orderId")) {
sqlBuilder.append(" AND order_id = ?");
params.add(Integer.parseInt(conditions.get("orderId").toString()));
}
// 处理订单编号
if (conditions.containsKey("orderNumber")) {
sqlBuilder.append(" AND order_number LIKE ?");
params.add("%" + conditions.get("orderNumber") + "%");
}
// 处理客户ID
if (conditions.containsKey("customerId")) {
sqlBuilder.append(" AND customer_id = ?");
params.add(Integer.parseInt(conditions.get("customerId").toString()));
}
// 处理仓库ID
if (conditions.containsKey("warehouseId")) {
sqlBuilder.append(" AND warehouse_id = ?");
params.add(Integer.parseInt(conditions.get("warehouseId").toString()));
}
// 处理订单日期范围
if (conditions.containsKey("orderDateFrom")) {
sqlBuilder.append(" AND order_date >= ?");
LocalDate fromDate = LocalDate.parse(conditions.get("orderDateFrom").toString(), DATE_FORMATTER);
params.add(Timestamp.valueOf(fromDate.atStartOfDay()));
}
if (conditions.containsKey("orderDateTo")) {
sqlBuilder.append(" AND order_date <= ?");
LocalDate toDate = LocalDate.parse(conditions.get("orderDateTo").toString(), DATE_FORMATTER);
params.add(Timestamp.valueOf(toDate.plusDays(1).atStartOfDay().minusNanos(1)));
}
// 处理订单状态
if (conditions.containsKey("orderStatus")) {
sqlBuilder.append(" AND order_status = ?");
params.add(conditions.get("orderStatus").toString());
}
// 处理支付状态
if (conditions.containsKey("paymentStatus")) {
sqlBuilder.append(" AND payment_status = ?");
params.add(conditions.get("paymentStatus").toString());
}
// 处理金额范围
if (conditions.containsKey("minAmount")) {
sqlBuilder.append(" AND total_amount >= ?");
params.add(new BigDecimal(conditions.get("minAmount").toString()));
}
if (conditions.containsKey("maxAmount")) {
sqlBuilder.append(" AND total_amount <= ?");
params.add(new BigDecimal(conditions.get("maxAmount").toString()));
}
// 处理关键字查询(订单编号或备注)
if (conditions.containsKey("keyword")) {
sqlBuilder.append(" AND (order_number LIKE ? OR notes LIKE ?)");
String keyword = "%" + conditions.get("keyword") + "%";
params.add(keyword);
params.add(keyword);
}
// 添加排序
sqlBuilder.append(" ORDER BY order_id DESC");
// 执行查询
return executeQueryWithParams(sqlBuilder.toString(), params);
}
/**
*
* @param sql SQL
* @param params
* @return
*/
private static List<SalesOrders> executeQueryWithParams(String sql, List<Object> params) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<SalesOrders> orderList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
// 设置参数
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i));
}
resultSet = preparedStatement.executeQuery();
orderList = extractOrdersFromResultSet(resultSet);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询销售订单失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return orderList;
}
/**
*
* @param sql SQL
* @param preparer SQL
* @return
*/
private static List<SalesOrders> executeQuery(String sql, PreparedStatementPreparer preparer) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<SalesOrders> orderList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
// 如果有参数需要设置
if (preparer != null) {
preparer.prepare(preparedStatement);
}
resultSet = preparedStatement.executeQuery();
orderList = extractOrdersFromResultSet(resultSet);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询销售订单失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return orderList;
}
/**
*
* @param resultSet
* @return
* @throws SQLException SQL
*/
private static List<SalesOrders> extractOrdersFromResultSet(ResultSet resultSet) throws SQLException {
List<SalesOrders> orderList = new ArrayList<>();
while (resultSet.next()) {
SalesOrders order = new SalesOrders();
order.setOrderId(resultSet.getInt("order_id"));
order.setOrderNumber(resultSet.getString("order_number"));
order.setCustomerId(resultSet.getInt("customer_id"));
// 设置日期时间
Timestamp orderDate = resultSet.getTimestamp("order_date");
if (orderDate != null) {
order.setOrderDate(orderDate.toLocalDateTime());
}
Date expectedShipDate = resultSet.getDate("expected_ship_date");
if (expectedShipDate != null) {
order.setExpectedShipDate(expectedShipDate.toLocalDate());
}
Date actualShipDate = resultSet.getDate("actual_ship_date");
if (actualShipDate != null) {
order.setActualShipDate(actualShipDate.toLocalDate());
}
order.setWarehouseId(resultSet.getInt("warehouse_id"));
order.setOrderStatus(resultSet.getString("order_status"));
order.setPaymentStatus(resultSet.getString("payment_status"));
order.setSubtotal(resultSet.getBigDecimal("subtotal"));
order.setTaxAmount(resultSet.getBigDecimal("tax_amount"));
order.setDiscountAmount(resultSet.getBigDecimal("discount_amount"));
order.setTotalAmount(resultSet.getBigDecimal("total_amount"));
order.setPaidAmount(resultSet.getBigDecimal("paid_amount"));
// 获取备注字段
order.setNotes(resultSet.getString("notes"));
// 设置时间戳
Timestamp createdTime = resultSet.getTimestamp("created_time");
if (createdTime != null) {
order.setCreatedTime(createdTime.toLocalDateTime());
}
Timestamp updatedTime = resultSet.getTimestamp("updated_time");
if (updatedTime != null) {
order.setUpdatedTime(updatedTime.toLocalDateTime());
}
orderList.add(order);
}
return orderList;
}
/**
* PreparedStatement
*/
@FunctionalInterface
private interface PreparedStatementPreparer {
void prepare(PreparedStatement preparedStatement) throws SQLException;
}
/**
*
*/
public static class QueryCriteria {
private Integer orderId;
private String orderNumber;
private Integer customerId;
private LocalDate startDate;
private LocalDate endDate;
private String orderStatus;
private String paymentStatus;
private BigDecimal minAmount;
private BigDecimal maxAmount;
private Integer warehouseId;
private String keyword;
// Getters and Setters
public Integer getOrderId() { return orderId; }
public void setOrderId(Integer orderId) { this.orderId = orderId; }
public String getOrderNumber() { return orderNumber; }
public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; }
public Integer getCustomerId() { return customerId; }
public void setCustomerId(Integer customerId) { this.customerId = customerId; }
public LocalDate getStartDate() { return startDate; }
public void setStartDate(LocalDate startDate) { this.startDate = startDate; }
public LocalDate getEndDate() { return endDate; }
public void setEndDate(LocalDate endDate) { this.endDate = endDate; }
public String getOrderStatus() { return orderStatus; }
public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; }
public String getPaymentStatus() { return paymentStatus; }
public void setPaymentStatus(String paymentStatus) { this.paymentStatus = paymentStatus; }
public BigDecimal getMinAmount() { return minAmount; }
public void setMinAmount(BigDecimal minAmount) { this.minAmount = minAmount; }
public BigDecimal getMaxAmount() { return maxAmount; }
public void setMaxAmount(BigDecimal maxAmount) { this.maxAmount = maxAmount; }
public Integer getWarehouseId() { return warehouseId; }
public void setWarehouseId(Integer warehouseId) { this.warehouseId = warehouseId; }
public String getKeyword() { return keyword; }
public void setKeyword(String keyword) { this.keyword = keyword; }
}
/**
* 使
* @param criteria
* @return
*/
public static List<SalesOrders> advancedQuery(QueryCriteria criteria) {
searchMode = true;
StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM sales_orders WHERE 1=1");
List<Object> params = new ArrayList<>();
// 添加订单ID条件
if (criteria.getOrderId() != null) {
sqlBuilder.append(" AND order_id = ?");
params.add(criteria.getOrderId());
}
// 添加订单编号条件
if (criteria.getOrderNumber() != null && !criteria.getOrderNumber().isEmpty()) {
sqlBuilder.append(" AND order_number LIKE ?");
params.add("%" + criteria.getOrderNumber() + "%");
}
// 添加客户ID条件
if (criteria.getCustomerId() != null) {
sqlBuilder.append(" AND customer_id = ?");
params.add(criteria.getCustomerId());
}
// 添加订单日期范围条件
if (criteria.getStartDate() != null) {
sqlBuilder.append(" AND order_date >= ?");
params.add(Timestamp.valueOf(criteria.getStartDate().atStartOfDay()));
}
if (criteria.getEndDate() != null) {
sqlBuilder.append(" AND order_date <= ?");
params.add(Timestamp.valueOf(criteria.getEndDate().plusDays(1).atStartOfDay().minusNanos(1)));
}
// 添加订单状态条件
if (criteria.getOrderStatus() != null && !criteria.getOrderStatus().isEmpty()) {
sqlBuilder.append(" AND order_status = ?");
params.add(criteria.getOrderStatus());
}
// 添加支付状态条件
if (criteria.getPaymentStatus() != null && !criteria.getPaymentStatus().isEmpty()) {
sqlBuilder.append(" AND payment_status = ?");
params.add(criteria.getPaymentStatus());
}
// 添加金额范围条件
if (criteria.getMinAmount() != null) {
sqlBuilder.append(" AND total_amount >= ?");
params.add(criteria.getMinAmount());
}
if (criteria.getMaxAmount() != null) {
sqlBuilder.append(" AND total_amount <= ?");
params.add(criteria.getMaxAmount());
}
// 添加仓库ID条件
if (criteria.getWarehouseId() != null) {
sqlBuilder.append(" AND warehouse_id = ?");
params.add(criteria.getWarehouseId());
}
// 添加关键字搜索条件(搜索备注字段)
if (criteria.getKeyword() != null && !criteria.getKeyword().isEmpty()) {
sqlBuilder.append(" AND (order_number LIKE ? OR notes LIKE ?)");
params.add("%" + criteria.getKeyword() + "%");
params.add("%" + criteria.getKeyword() + "%");
}
// 添加排序
sqlBuilder.append(" ORDER BY order_id DESC");
return executeQueryWithParams(sqlBuilder.toString(), params);
}
}

@ -1,334 +0,0 @@
package com.xky.ui.module.salesManagement.select;
import com.xky.pojo.SalesShipments;
import com.xky.utils.DBUtils;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
/**
*
*/
public class SelectSalesShipment {
private static boolean searchMode = false;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/**
*
*/
public static void resetSearchStatus() {
searchMode = false;
}
/**
*
* @return
*/
public static List<SalesShipments> selectAll() {
String sql = "SELECT * FROM sales_shipments ORDER BY shipment_id DESC";
return executeQuery(sql, null);
}
/**
* ID
* @param id ID
* @return
*/
public static List<SalesShipments> selectById(Integer id) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE shipment_id = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, id);
});
}
/**
*
* @param shipmentNumber
* @return
*/
public static List<SalesShipments> selectByShipmentNumber(String shipmentNumber) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE shipment_number LIKE ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setString(1, "%" + shipmentNumber + "%");
});
}
/**
* ID
* @param orderId ID
* @return
*/
public static List<SalesShipments> selectByOrderId(Integer orderId) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE order_id = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setInt(1, orderId);
});
}
/**
*
* @param status
* @return
*/
public static List<SalesShipments> selectByStatus(String status) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE status = ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setString(1, status);
});
}
/**
*
* @param keyword
* @return
*/
public static List<SalesShipments> searchByKeyword(String keyword) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE " +
"shipment_number LIKE ? OR " +
"CAST(order_id AS CHAR) LIKE ? OR " +
"status LIKE ? OR " +
"carrier LIKE ? OR " +
"tracking_number LIKE ? OR " +
"notes LIKE ? " +
"ORDER BY shipment_id DESC";
return executeQuery(sql, preparedStatement -> {
String param = "%" + keyword + "%";
for (int i = 1; i <= 6; i++) {
preparedStatement.setString(i, param);
}
});
}
/**
*
* @param startDate
* @param endDate
* @return
*/
public static List<SalesShipments> selectByDateRange(LocalDate startDate, LocalDate endDate) {
searchMode = true;
String sql = "SELECT * FROM sales_shipments WHERE shipment_date BETWEEN ? AND ?";
return executeQuery(sql, preparedStatement -> {
preparedStatement.setDate(1, java.sql.Date.valueOf(startDate));
preparedStatement.setDate(2, java.sql.Date.valueOf(endDate));
});
}
/**
*
* @param shipmentNumber
* @param orderId ID
* @param status
* @param startDate
* @param endDate
* @return
*/
public static List<SalesShipments> advancedSearch(String shipmentNumber, Integer orderId, String status,
LocalDate startDate, LocalDate endDate) {
searchMode = true;
StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM sales_shipments WHERE 1=1");
List<Object> params = new ArrayList<>();
if (shipmentNumber != null && !shipmentNumber.trim().isEmpty()) {
sqlBuilder.append(" AND shipment_number LIKE ?");
params.add("%" + shipmentNumber + "%");
}
if (orderId != null) {
sqlBuilder.append(" AND order_id = ?");
params.add(orderId);
}
if (status != null && !status.trim().isEmpty()) {
sqlBuilder.append(" AND status = ?");
params.add(status);
}
if (startDate != null) {
sqlBuilder.append(" AND shipment_date >= ?");
params.add(java.sql.Date.valueOf(startDate));
}
if (endDate != null) {
sqlBuilder.append(" AND shipment_date <= ?");
params.add(java.sql.Date.valueOf(endDate));
}
sqlBuilder.append(" ORDER BY shipment_id DESC");
return executeQuery(sqlBuilder.toString(), preparedStatement -> {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i));
}
});
}
/**
* 使Map
* @param conditions Map
* @return
*/
public static List<SalesShipments> advancedSearchWithMap(Map<String, Object> conditions) {
searchMode = true;
StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM sales_shipments WHERE 1=1");
List<Object> params = new ArrayList<>();
// 处理发货单ID
if (conditions.containsKey("shipmentId")) {
sqlBuilder.append(" AND shipment_id = ?");
params.add(Integer.parseInt(conditions.get("shipmentId").toString()));
}
// 处理发货单号
if (conditions.containsKey("shipmentNumber")) {
sqlBuilder.append(" AND shipment_number LIKE ?");
params.add("%" + conditions.get("shipmentNumber") + "%");
}
// 处理订单ID
if (conditions.containsKey("orderId")) {
sqlBuilder.append(" AND order_id = ?");
params.add(Integer.parseInt(conditions.get("orderId").toString()));
}
// 处理仓库ID
if (conditions.containsKey("warehouseId")) {
sqlBuilder.append(" AND warehouse_id = ?");
params.add(Integer.parseInt(conditions.get("warehouseId").toString()));
}
// 处理发货日期范围
if (conditions.containsKey("shipDateFrom")) {
sqlBuilder.append(" AND shipment_date >= ?");
LocalDate fromDate = LocalDate.parse(conditions.get("shipDateFrom").toString(), DATE_FORMATTER);
params.add(java.sql.Date.valueOf(fromDate));
}
if (conditions.containsKey("shipDateTo")) {
sqlBuilder.append(" AND shipment_date <= ?");
LocalDate toDate = LocalDate.parse(conditions.get("shipDateTo").toString(), DATE_FORMATTER);
params.add(java.sql.Date.valueOf(toDate));
}
// 处理承运商
if (conditions.containsKey("carrier")) {
sqlBuilder.append(" AND carrier LIKE ?");
params.add("%" + conditions.get("carrier") + "%");
}
// 处理物流单号
if (conditions.containsKey("trackingNumber")) {
sqlBuilder.append(" AND tracking_number LIKE ?");
params.add("%" + conditions.get("trackingNumber") + "%");
}
// 处理运输方式
if (conditions.containsKey("shippingMethod")) {
sqlBuilder.append(" AND shipping_method = ?");
params.add(conditions.get("shippingMethod").toString());
}
// 处理状态
if (conditions.containsKey("status")) {
sqlBuilder.append(" AND status = ?");
params.add(conditions.get("status").toString());
}
sqlBuilder.append(" ORDER BY shipment_id DESC");
return executeQuery(sqlBuilder.toString(), preparedStatement -> {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i));
}
});
}
/**
*
* @param sql SQL
* @param paramsSetter
* @return
*/
private static List<SalesShipments> executeQuery(String sql, ParamsSetter paramsSetter) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
List<SalesShipments> shipmentsList = new ArrayList<>();
try {
conn = DBUtils.getConnection();
pstmt = conn.prepareStatement(sql);
if (paramsSetter != null) {
paramsSetter.setParams(pstmt);
}
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
SalesShipments shipment = new SalesShipments();
shipment.setShipmentId(resultSet.getInt("shipment_id"));
shipment.setShipmentNumber(resultSet.getString("shipment_number"));
shipment.setOrderId(resultSet.getInt("order_id"));
shipment.setWarehouseId(resultSet.getInt("warehouse_id"));
// 设置日期
Date shipmentDate = resultSet.getDate("shipment_date");
if (shipmentDate != null) {
shipment.setShipmentDate(shipmentDate.toLocalDate());
}
shipment.setCarrier(resultSet.getString("carrier"));
shipment.setTrackingNumber(resultSet.getString("tracking_number"));
shipment.setShippingMethod(resultSet.getString("shipping_method"));
shipment.setStatus(resultSet.getString("status"));
shipment.setNotes(resultSet.getString("notes"));
// 设置时间戳
Timestamp createdTime = resultSet.getTimestamp("created_time");
if (createdTime != null) {
shipment.setCreatedTime(createdTime.toLocalDateTime());
}
Timestamp updatedTime = resultSet.getTimestamp("updated_time");
if (updatedTime != null) {
shipment.setUpdatedTime(updatedTime.toLocalDateTime());
}
shipmentsList.add(shipment);
}
return shipmentsList;
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "查询数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
return new ArrayList<>();
} finally {
DBUtils.closeAll(conn, pstmt, resultSet);
}
}
public static boolean isSearchMode() {
return searchMode;
}
/**
*
*/
private interface ParamsSetter {
void setParams(PreparedStatement preparedStatement) throws SQLException;
}
}

@ -1,142 +0,0 @@
package com.xky.ui.module.supplierManagement;
import com.xky.pojo.Supplier;
import com.xky.ui.main.MainView;
import com.xky.ui.module.supplierManagement.select.SelectSupplier;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
*
*
*/
public class SupplierInfo {
private static JTable supplierTable;
private static final String MODULE_NAME = "供应商信息";
/**
*
*/
public static void showSupplierInfoPage() {
try {
// 创建供应商信息面板
JPanel supplierInfoPanel = SupplierMassage.createWarehouseInfoPanel(SupplierInfo::refreshSupplierData);
// 获取表格组件
Component centerComponent = null;
if (supplierInfoPanel.getLayout() instanceof BorderLayout) {
// 遍历所有组件查找位于CENTER位置的组件
for (Component comp : supplierInfoPanel.getComponents()) {
Object constraints = ((BorderLayout)supplierInfoPanel.getLayout())
.getConstraints(comp);
if (BorderLayout.CENTER.equals(constraints)) {
centerComponent = comp;
break;
}
}
// 如果找不到尝试直接查找JScrollPane
if (centerComponent == null) {
for (Component comp : supplierInfoPanel.getComponents()) {
if (comp instanceof JScrollPane) {
centerComponent = comp;
break;
}
}
}
}
if (centerComponent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) centerComponent;
Component viewComponent = scrollPane.getViewport().getView();
if (viewComponent instanceof JTable) {
supplierTable = (JTable) viewComponent;
} else {
throw new IllegalStateException("无法找到表格组件: 视图组件不是表格");
}
} else {
throw new IllegalStateException("无法找到表格组件: 中心组件不是滚动面板");
}
// 更新右侧面板
MainView.rightPanel.removeAll();
MainView.rightPanel.add(supplierInfoPanel, BorderLayout.CENTER);
MainView.rightPanel.revalidate();
MainView.rightPanel.repaint();
// 注册刷新操作
MainView.registerRefreshAction(MODULE_NAME, SupplierInfo::refreshSupplierData);
// 立即刷新一次
refreshSupplierData();
// 更新状态消息
MainView.updateStatusMessage(MODULE_NAME + "页面已加载");
} catch (Exception e) {
handleException(e, "加载" + MODULE_NAME + "页面失败");
}
}
/**
*
*/
static void refreshSupplierData() {
// 显示加载指示器
MainView.updateStatusMessage("正在加载" + MODULE_NAME + "数据...");
new SwingWorker<List<Supplier>, Void>() {
@Override
protected List<Supplier> doInBackground() {
validateTable();
DefaultTableModel model = (DefaultTableModel) supplierTable.getModel();
model.setRowCount(0);
// 获取所有供应商数据
return SelectSupplier.selectAll();
}
@Override
protected void done() {
try {
List<Supplier> supplierList = get();
if (supplierTable != null) {
SupplierMassage.updateTableData(supplierTable, supplierList);
MainView.rightPanel.repaint();
MainView.updateStatusMessage("已加载 " + supplierList.size() + " 条" + MODULE_NAME + "数据");
}
} catch (InterruptedException | ExecutionException e) {
handleException(e, "刷新失败");
}
}
}.execute();
}
/**
*
* @throws IllegalStateException
*/
private static void validateTable() throws IllegalStateException {
if (supplierTable == null) {
throw new IllegalStateException("表格未初始化");
}
}
/**
*
* @param e
* @param message
*/
private static void handleException(Exception e, String message) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
message + ": " + e.getMessage(),
"错误", JOptionPane.ERROR_MESSAGE);
MainView.updateStatusMessage(MODULE_NAME + "数据加载失败");
}
}

@ -1,454 +0,0 @@
package com.xky.ui.module.supplierManagement;
import com.xky.pojo.Supplier;
import com.xky.ui.module.supplierManagement.select.SelectSupplier;
import com.xky.ui.module.supplierManagement.add.AddSuppliers;
import com.xky.ui.module.supplierManagement.delete.DeleteSupplier;
import com.xky.ui.module.supplierManagement.update.UpdateSupplier;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
/**
*
*/
public class SupplierMassage {
// 表格组件
private static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
// 日期时间格式化器
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
*
* @param refreshAction
* @return
*/
public static JPanel createWarehouseInfoPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("供应商基本信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createSupplierTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
new AddSuppliers();
if (refreshAction != null) {
refreshAction.run();
}
});
deleteButton.addActionListener(e -> {
new DeleteSupplier();
if (refreshAction != null) {
refreshAction.run();
}
});
updateButton.addActionListener(e -> {
new UpdateSupplier();
if (refreshAction != null) {
refreshAction.run();
}
});
queryButton.addActionListener(e -> showSearchDialog());
refreshButton.addActionListener(e -> {
SelectSupplier.resetSearchStatus();
if (refreshAction != null) {
refreshAction.run();
updateStatusMessage("供应商数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createSupplierTable() {
// 表格列名
String[] columnNames = {"供应商ID", "供应商编码", "供应商名称", "联系人姓名", "联系人电话", "联系人邮箱", "地址", "是否合作", "创建时间", "更新时间"};
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
// 创建表格
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(120);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(120);
table.getColumnModel().getColumn(5).setPreferredWidth(150);
table.getColumnModel().getColumn(6).setPreferredWidth(150);
table.getColumnModel().getColumn(7).setPreferredWidth(80);
table.getColumnModel().getColumn(8).setPreferredWidth(150);
table.getColumnModel().getColumn(9).setPreferredWidth(150);
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param supplierList
*/
public static void updateTableData(JTable table, List<Supplier> supplierList) {
if (table == null || supplierList == null) {
return;
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
// 清空表格中现有的数据
model.setRowCount(0);
for (Supplier supplier : supplierList) {
String createdTimeStr = supplier.getCreatedTime() != null ?
supplier.getCreatedTime().format(DATE_FORMATTER) : "";
String updatedTimeStr = supplier.getUpdatedTime() != null ?
supplier.getUpdatedTime().format(DATE_FORMATTER) : "";
model.addRow(new Object[]{
supplier.getSupplierId(),
supplier.getSupplierCode(),
supplier.getSupplierName(),
supplier.getContactName(),
supplier.getContactPhone(),
supplier.getContactEmail(),
supplier.getAddress(),
supplier.getIsActive() ? "是" : "否",
createdTimeStr,
updatedTimeStr
});
}
// 触发表格数据刷新
model.fireTableDataChanged();
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询供应商", true);
searchDialog.setSize(900, 550);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
topPanel.setBackground(SECONDARY_COLOR);
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.setOpaque(false);
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按供应商ID查询", true);
JRadioButton keywordRadio = new JRadioButton("关键字查询");
idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
keywordRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
idRadio.setOpaque(false);
keywordRadio.setOpaque(false);
buttonGroup.add(idRadio);
buttonGroup.add(keywordRadio);
radioPanel.add(idRadio);
radioPanel.add(keywordRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
searchPanel.setOpaque(false);
JLabel searchLabel = new JLabel("查询条件: ");
searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
JTextField searchField = new JTextField(20);
searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
searchField.setPreferredSize(new Dimension(200, 30));
JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);
JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
searchFieldPanel.setOpaque(false);
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 供应商编码/ 供应商名称/ 联系人姓名/ 联系人电话/ 联系人邮箱/ 地址/ 是否合作");
tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"供应商ID", "供应商编码", "供应商名称", "联系人姓名", "联系人电话", "联系人邮箱", "地址", "是否合作", "创建时间", "更新时间"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(30);
resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
resultTable.getTableHeader().setBackground(Color.lightGray);
resultTable.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
resultTable.getTableHeader().setOpaque(true);
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultTable.setShowGrid(true);
resultTable.setGridColor(new Color(230, 230, 230));
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
scrollPane.getViewport().setBackground(Color.WHITE);
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
buttonPanel.setBackground(SECONDARY_COLOR);
JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
JButton cancelButton = createStyledButton("取消", new Color(231, 76, 60));
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(_ -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<Supplier> resultList = new ArrayList<>();
try {
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
Supplier result = SelectSupplier.selectWarehousesById(id);
if (result != null) {
resultList.add(result);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (keywordRadio.isSelected()) {
// 获取关键字搜索结果
List<Supplier> suppliers = SelectSupplier.searchSupplierByKeyword(searchText);
if (suppliers != null && !suppliers.isEmpty()) {
resultList.addAll(suppliers);
}
}
// 更新表格数据
tableModel.setRowCount(0);
if (!resultList.isEmpty()) {
for (Supplier supplier : resultList) {
String createdTimeStr = supplier.getCreatedTime() != null ?
supplier.getCreatedTime().format(DATE_FORMATTER) : "";
String updatedTimeStr = supplier.getUpdatedTime() != null ?
supplier.getUpdatedTime().format(DATE_FORMATTER) : "";
tableModel.addRow(new Object[]{
supplier.getSupplierId(),
supplier.getSupplierCode(),
supplier.getSupplierName(),
supplier.getContactName(),
supplier.getContactPhone(),
supplier.getContactEmail(),
supplier.getAddress(),
supplier.getIsActive() ? "是" : "否",
createdTimeStr,
updatedTimeStr
});
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int supplierId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的供应商数据
Supplier supplier = SelectSupplier.selectWarehousesById(supplierId);
List<Supplier> supplierList = new ArrayList<>();
if (supplier != null) {
supplierList.add(supplier);
}
if (!supplierList.isEmpty()) {
// 清空主表格并只显示选中的供应商
updateTableData(table, supplierList);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
autoRefreshTimer.stop();
}
// 更新状态消息
updateStatusMessage("已选择供应商: " + supplierList.get(0).getSupplierName());
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
}

@ -1,299 +0,0 @@
package com.xky.ui.module.supplierManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class AddSuppliers extends JFrame {
private JPanel mainPanel;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
// 邮箱验证正则表达式
private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
public AddSuppliers() {
setTitle("添加供应商");
setSize(550, 650);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init() {
// 创建主面板并设置背景渐变
JPanel backgroundPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
backgroundPanel.setLayout(new BorderLayout(10, 10));
backgroundPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("添加供应商信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
JPanel headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
headerPanel.add(titlePanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
backgroundPanel.add(headerPanel, BorderLayout.NORTH);
// 表单面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
mainPanel = new JPanel(new GridBagLayout());
mainPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
JLabel[] labels = new JLabel[]{
new JLabel("供应商编码 *"),
new JLabel("供应商名称 *"),
new JLabel("联系人姓名 *"),
new JLabel("联系人电话 *"),
new JLabel("联系人邮箱 *"),
new JLabel("供应商地址 *"),
new JLabel("是否合作 *")
};
// 创建文本框
textFields = new JTextField[6]; // 只需要6个文本框另一个是下拉框
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 20, 10, 10);
labels[i].setFont(labelFont);
labels[i].setForeground(PRIMARY_COLOR);
mainPanel.add(labels[i], gbc);
gbc.gridx = 1;
gbc.weightx = 1.0;
if (i < 6) {
textFields[i] = new JTextField(20);
textFields[i].setFont(inputFont);
textFields[i].setPreferredSize(new Dimension(300, 35));
gbc.fill = GridBagConstraints.HORIZONTAL;
mainPanel.add(textFields[i], gbc);
} else {
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(inputFont);
isActiveComboBox.setPreferredSize(new Dimension(300, 35));
isActiveComboBox.setBackground(Color.WHITE);
gbc.fill = GridBagConstraints.HORIZONTAL;
mainPanel.add(isActiveComboBox, gbc);
}
}
// 添加字段说明标签
JLabel noteLabel = new JLabel("<html><body style='width: 350px'>" +
"<p style='color: #666666;'>注意:带 * 的字段为必填项</p>" +
"</body></html>");
noteLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
gbc.gridx = 0;
gbc.gridy = labels.length;
gbc.gridwidth = 2;
gbc.insets = new Insets(20, 20, 10, 10);
mainPanel.add(noteLabel, gbc);
formCard.add(mainPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
backgroundPanel.add(formCard, BorderLayout.CENTER);
// 按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
JButton submitButton = new JButton("提交");
submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
submitButton.setPreferredSize(new Dimension(120, 40));
submitButton.setBackground(BUTTON_COLOR);
submitButton.setForeground(Color.WHITE);
submitButton.setFocusPainted(false);
submitButton.setBorderPainted(false);
JButton cancelButton = new JButton("取消");
cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
cancelButton.setPreferredSize(new Dimension(120, 40));
cancelButton.setBackground(Color.LIGHT_GRAY);
cancelButton.setForeground(Color.WHITE);
cancelButton.setFocusPainted(false);
cancelButton.setBorderPainted(false);
buttonPanel.add(submitButton);
buttonPanel.add(cancelButton);
backgroundPanel.add(buttonPanel, BorderLayout.SOUTH);
add(backgroundPanel);
// 提交按钮事件
submitButton.addActionListener(_ -> {
String supplierCode = textFields[0].getText().trim();
String supplierName = textFields[1].getText().trim();
String contactName = textFields[2].getText().trim();
String contactPhone = textFields[3].getText().trim();
String contactEmail = textFields[4].getText().trim();
String address = textFields[5].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
// 验证所有字段是否已填写
if (supplierCode.isEmpty() || supplierName.isEmpty() || contactName.isEmpty() ||
contactPhone.isEmpty() || contactEmail.isEmpty() || address.isEmpty()) {
JOptionPane.showMessageDialog(AddSuppliers.this, "所有字段都为必填项,请完成表单", "输入提示", JOptionPane.WARNING_MESSAGE);
return;
}
// 验证邮箱格式
if (!contactEmail.matches(EMAIL_REGEX)) {
JOptionPane.showMessageDialog(AddSuppliers.this, "邮箱格式错误,请重新输入", "错误提示", JOptionPane.ERROR_MESSAGE);
textFields[4].setText("");
textFields[4].requestFocus();
return;
}
// 验证邮箱是否重复
if (selectByEmail(contactEmail)) {
JOptionPane.showMessageDialog(AddSuppliers.this, "邮箱号重复,请更换", "重复提示", JOptionPane.ERROR_MESSAGE);
textFields[4].setText("");
textFields[4].requestFocus();
return;
}
// 确认添加
if (JOptionPane.showConfirmDialog(AddSuppliers.this, "你确定要添加该信息吗?", "添加提示", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.YES_OPTION) {
addSupplier(supplierCode, supplierName, contactName, contactPhone, contactEmail, address, isActive);
JOptionPane.showMessageDialog(AddSuppliers.this, "信息添加成功", "成功提示", JOptionPane.INFORMATION_MESSAGE);
dispose();
}
});
// 取消按钮事件
cancelButton.addActionListener(_ -> dispose());
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
// 添加信息到数据库
public void addSupplier(String supplierCode, String supplierName, String contactName, String contactPhone, String contactEmail, String address, String isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"INSERT INTO suppliers(supplier_code, supplier_name, contact_name, contact_phone, contact_email, address, is_active, created_time, updated_time) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())",
Statement.RETURN_GENERATED_KEYS
);
preparedStatement.setString(1, supplierCode);
preparedStatement.setString(2, supplierName);
preparedStatement.setString(3, contactName);
preparedStatement.setString(4, contactPhone);
preparedStatement.setString(5, contactEmail);
preparedStatement.setString(6, address);
preparedStatement.setString(7, isActive);
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("受影响的行数为" + i + "添加成功!");
} else {
System.out.println("受影响的行数为" + i + "添加失败!");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
// 查询邮箱是否重复
public boolean selectByEmail(String email) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE contact_email = ?");
preparedStatement.setString(1, email);
resultSet = preparedStatement.executeQuery();
return resultSet.next();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
public static void main(String[] args) {
try {
// 尝试使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(AddSuppliers::new);
}
}

@ -1,282 +0,0 @@
package com.xky.ui.module.supplierManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DeleteSupplier extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteSupplier(){
setTitle("删除界面");
setSize(280,200); // 增加高度以容纳新按钮
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的供应商的ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(250, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有商品的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有供应商");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个商品删除按钮事件
jButton.addActionListener(e -> {
String id = jTextField.getText().trim();
System.out.println("你点击了确定按钮!");
if (id.isEmpty()){
JOptionPane.showMessageDialog(this, "请输入你要删除的供应商的ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
int i = JOptionPane.showConfirmDialog(this, "你确定要删除该供应商信息吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION){
if (selectById(id)){
deleteProduct(id);
JOptionPane.showMessageDialog(this, "该供应商信息删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "找不到该供应商ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有商品按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
this,
"警告:此操作将删除所有商品信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
this,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有商品的操作
if (deleteAllProducts()) {
JOptionPane.showMessageDialog(
this,
"所有供应商信息已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
this,
"删除所有供应商信息失败,请检查!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
this,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
*
* @param supplierId ID
* @return
*/
public boolean deleteProduct(String supplierId){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM suppliers WHERE supplier_id = ?");
preparedStatement.setString(1, supplierId);
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("影响行数为" + i + "删除成功!");
return true;
} else {
System.out.println("影响行数为" + i + "删除失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllProducts() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM suppliers");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("删除了" + rowsAffected + "条供应商记录");
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public Boolean selectById(String supplierId){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE supplier_id = ?");
preparedStatement.setString(1, supplierId);
resultSet = preparedStatement.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteSupplier::new);
}
}

@ -1,133 +0,0 @@
package com.xky.ui.module.supplierManagement.select;
import com.xky.pojo.Supplier;
import com.xky.pojo.Warehouses;
import com.xky.utils.DBUtils;
import lombok.Getter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SelectSupplier {
@Getter
private static Integer Id;
// 标记查询是否成功
@Getter
private static boolean searchSuccessful = false;
// 存储查询结果
@Getter
private static List<Warehouses> searchResults;
public static List<Supplier> searchSupplierByKeyword(String keyword){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Supplier> supplierList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
// 使用LIKE进行模糊查询
preparedStatement = connection.prepareStatement(
"SELECT * FROM suppliers WHERE supplier_code LIKE ? OR supplier_name LIKE ? OR contact_name LIKE ? OR contact_Phone LIKE ? OR contact_email LIKE ? OR address LIKE ? OR is_active LIKE ? ORDER BY supplier_id"
);
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
preparedStatement.setString(2, searchPattern);
preparedStatement.setString(3, searchPattern);
preparedStatement.setString(4, searchPattern);
preparedStatement.setString(5, searchPattern);
preparedStatement.setString(6, searchPattern);
preparedStatement.setString(7, searchPattern);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
supplierList.add(createSupplierFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return supplierList;
}
//查询所有的供应商信息
public static List<Supplier> selectAll(){
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Supplier> supplierList = new ArrayList<>();
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM suppliers");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
supplierList.add(createSupplierFromResultSet(resultSet));
}
return supplierList;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
public static Supplier selectWarehousesById(int supplierId) {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE supplier_id = ?");
preparedStatement.setInt(1, supplierId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
return createSupplierFromResultSet(resultSet);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return null;
}
private static Supplier createSupplierFromResultSet(ResultSet resultSet) throws SQLException {
Supplier supplier = new Supplier();
supplier.setSupplierId(resultSet.getInt("supplier_id"));
supplier.setSupplierCode(resultSet.getString("supplier_code"));
supplier.setSupplierName(resultSet.getString("supplier_name"));
supplier.setContactName(resultSet.getString("contact_name"));
supplier.setContactPhone(resultSet.getString("contact_phone"));
supplier.setContactEmail(resultSet.getString("contact_email"));
supplier.setAddress(resultSet.getString("address"));
supplier.setIsActive(resultSet.getBoolean("is_active"));
// 获取创建时间和更新时间
if (resultSet.getTimestamp("created_time") != null) {
supplier.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
}
if (resultSet.getTimestamp("updated_time") != null) {
supplier.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
}
return supplier;
}
/**
*
*/
public static void resetSearchStatus() {
searchSuccessful = false;
searchResults = null;
Id = null;
}
}

@ -1,457 +0,0 @@
package com.xky.ui.module.supplierManagement.update;
import com.xky.pojo.Supplier;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class UpdateSupplier extends JFrame {
private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
private JButton updateButton, queryButton;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
// 邮箱验证正则表达式
private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
public UpdateSupplier() {
initializeFrame();
initComponents();
setVisible(true);
}
private void initializeFrame() {
setTitle("供应商信息修改");
setSize(600, 680);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
private void initComponents() {
// 初始化textFields数组
textFields = new JTextField[8]; // 供应商ID + 7个字段
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField(20);
}
// 初始化按钮
updateButton = new JButton("修改");
queryButton = new JButton("查询");
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 1. 头部面板
createHeaderPanel();
// 2. 表单面板
createFormPanel();
// 3. 按钮面板
createButtonPanel();
// 添加事件监听
setupEventListeners();
add(mainPanel);
}
private void createHeaderPanel() {
headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("供应商信息修改");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入供应商ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
}
private void createFormPanel() {
// 创建查询面板
JPanel searchCard = createRoundedPanel();
searchCard.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
JLabel idLabel = new JLabel("供应商ID");
idLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
idLabel.setForeground(PRIMARY_COLOR);
searchCard.add(idLabel);
textFields[0].setFont(new Font("微软雅黑", Font.PLAIN, 16));
searchCard.add(textFields[0]);
styleButton(queryButton, QUERY_BUTTON_COLOR);
queryButton.setPreferredSize(new Dimension(80, 35));
searchCard.add(queryButton);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setOpaque(false);
topPanel.add(searchCard, BorderLayout.CENTER);
topPanel.setBorder(new EmptyBorder(0, 0, 15, 0));
mainPanel.add(topPanel, BorderLayout.NORTH);
// 创建表单面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
String[] labels = {
"供应商编码 *", "供应商名称 *", "联系人姓名 *", "联系人电话 *",
"联系人邮箱 *", "供应商地址 *", "是否合作 *"
};
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.weightx = 0.3;
JLabel label = new JLabel(labels[i]);
label.setFont(labelFont);
label.setForeground(PRIMARY_COLOR);
formPanel.add(label, gbc);
gbc.gridx = 1;
gbc.weightx = 0.7;
if (i < 6) {
// 使用已初始化的textFields[i+1]
textFields[i + 1].setFont(fieldFont);
textFields[i + 1].setPreferredSize(new Dimension(250, 35));
formPanel.add(textFields[i + 1], gbc);
} else {
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(fieldFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
formPanel.add(isActiveComboBox, gbc);
}
}
formCard.add(formPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
// 禁用表单字段,直到用户搜索到供应商
setFormFieldsEnabled(false);
}
private void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
styleButton(updateButton, BUTTON_COLOR);
updateButton.setEnabled(false);
buttonPanel.add(updateButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
/**
*
*/
private void setFormFieldsEnabled(boolean enabled) {
for (int i = 1; i < textFields.length; i++) {
textFields[i].setEnabled(enabled);
}
if (isActiveComboBox != null) {
isActiveComboBox.setEnabled(enabled);
}
updateButton.setEnabled(enabled);
}
private void setupEventListeners() {
// 查询按钮事件
queryButton.addActionListener(e -> {
try {
String idText = textFields[0].getText().trim();
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入供应商ID", "输入错误", JOptionPane.WARNING_MESSAGE);
return;
}
int supplierId = Integer.parseInt(idText);
Supplier supplier = findSupplierById(supplierId);
if (supplier != null) {
// 填充表单字段
textFields[1].setText(supplier.getSupplierCode());
textFields[2].setText(supplier.getSupplierName());
textFields[3].setText(supplier.getContactName());
textFields[4].setText(supplier.getContactPhone());
textFields[5].setText(supplier.getContactEmail());
textFields[6].setText(supplier.getAddress());
// 设置是否合作下拉框
isActiveComboBox.setSelectedIndex("1".equals(supplier.getIsActive()) ? 0 : 1);
// 启用表单字段
setFormFieldsEnabled(true);
} else {
JOptionPane.showMessageDialog(this, "未找到ID为 " + supplierId + " 的供应商记录",
"查找失败", JOptionPane.WARNING_MESSAGE);
clearFormFields();
setFormFieldsEnabled(false);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
// 修改按钮事件
updateButton.addActionListener(e -> {
try {
int supplierId = Integer.parseInt(textFields[0].getText().trim());
String supplierCode = textFields[1].getText().trim();
String supplierName = textFields[2].getText().trim();
String contactName = textFields[3].getText().trim();
String contactPhone = textFields[4].getText().trim();
String contactEmail = textFields[5].getText().trim();
String address = textFields[6].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
// 验证输入
if (!validateInputs(supplierCode, supplierName, contactName, contactPhone, contactEmail, address)) {
return;
}
// 更新供应商信息
if (updateSupplier(supplierId, supplierCode, supplierName, contactName, contactPhone, contactEmail, address, isActive)) {
JOptionPane.showMessageDialog(this, "供应商信息更新成功", "更新成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(this, "供应商信息更新失败", "更新失败", JOptionPane.ERROR_MESSAGE);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "供应商ID格式错误", "输入错误", JOptionPane.WARNING_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
// 为ID文本框添加回车键事件
textFields[0].addActionListener(e -> queryButton.doClick());
}
private void clearFormFields() {
for (int i = 1; i < textFields.length; i++) {
textFields[i].setText("");
}
if (isActiveComboBox != null) {
isActiveComboBox.setSelectedIndex(0);
}
}
private boolean validateInputs(String supplierCode, String supplierName, String contactName,
String contactPhone, String contactEmail, String address) {
// 1. 校验供应商编码
if (supplierCode.isEmpty()) {
showValidationError("供应商编码不能为空");
return false;
}
// 2. 校验供应商名称
if (supplierName.isEmpty()) {
showValidationError("供应商名称不能为空");
return false;
}
// 3. 校验联系人姓名
if (contactName.isEmpty()) {
showValidationError("联系人姓名不能为空");
return false;
}
// 4. 校验联系人电话
if (contactPhone.isEmpty()) {
showValidationError("联系人电话不能为空");
return false;
}
// 5. 校验联系人邮箱
if (contactEmail.isEmpty()) {
showValidationError("联系人邮箱不能为空");
return false;
}
// 验证邮箱格式
if (!contactEmail.matches(EMAIL_REGEX)) {
showValidationError("邮箱格式不正确");
return false;
}
// 6. 校验供应商地址
if (address.isEmpty()) {
showValidationError("供应商地址不能为空");
return false;
}
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
private Supplier findSupplierById(int supplierId) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE supplier_id = ?");
preparedStatement.setInt(1, supplierId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Supplier supplier = new Supplier();
supplier.setSupplierId(resultSet.getInt("supplier_id"));
supplier.setSupplierCode(resultSet.getString("supplier_code"));
supplier.setSupplierName(resultSet.getString("supplier_name"));
supplier.setContactName(resultSet.getString("contact_name"));
supplier.setContactPhone(resultSet.getString("contact_phone"));
supplier.setContactEmail(resultSet.getString("contact_email"));
supplier.setAddress(resultSet.getString("address"));
supplier.setIsActive(Boolean.valueOf(resultSet.getString("is_active")));
return supplier;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
private boolean updateSupplier(int supplierId, String supplierCode, String supplierName,
String contactName, String contactPhone, String contactEmail,
String address, String isActive) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"UPDATE suppliers SET supplier_code = ?, supplier_name = ?, contact_name = ?, " +
"contact_phone = ?, contact_email = ?, address = ?, is_active = ?, updated_time = NOW() " +
"WHERE supplier_id = ?");
preparedStatement.setString(1, supplierCode);
preparedStatement.setString(2, supplierName);
preparedStatement.setString(3, contactName);
preparedStatement.setString(4, contactPhone);
preparedStatement.setString(5, contactEmail);
preparedStatement.setString(6, address);
preparedStatement.setString(7, isActive);
preparedStatement.setInt(8, supplierId);
return preparedStatement.executeUpdate() > 0;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateSupplier::new);
}
}

@ -1,71 +0,0 @@
package com.xky.ui.module.warehouseManagement;
import com.xky.pojo.Warehouses;
import com.xky.ui.module.warehouseManagement.select.WarehouseService;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.xky.ui.main.MainView.*;
public class WarehouseInfo {
private static JTable warehouseTable;
/**
*
*/
public static void showWarehouseInfoPage() {
// 创建仓库信息面板
JPanel warehouseInfoPanel = WarehouseManage.createWarehouseInfoPanel(WarehouseInfo::refreshWarehouseData);
// 获取表格组件
Component[] components = ((JScrollPane)warehouseInfoPanel.getComponent(1)).getViewport().getComponents();
if (components.length > 0 && components[0] instanceof JTable) {
warehouseTable = (JTable) components[0];
}
// 更新右侧面板
rightPanel.removeAll();
rightPanel.add(warehouseInfoPanel, BorderLayout.CENTER);
rightPanel.revalidate();
rightPanel.repaint();
// 注册刷新操作
registerRefreshAction("仓库信息", WarehouseInfo::refreshWarehouseData);
// 立即刷新一次
refreshWarehouseData();
}
/**
*
*/
static void refreshWarehouseData() {
new SwingWorker<List<Warehouses>, Void>() {
@Override
protected List<Warehouses> doInBackground() {
return WarehouseService.selectAllWarehouses();
}
@Override
protected void done() {
try {
List<Warehouses> warehouses = get();
if (warehouseTable != null) {
// updateTableData方法会清空并更新表格数据
WarehouseManage.updateTableData(warehouseTable, warehouses);
rightPanel.revalidate();
rightPanel.repaint();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"刷新失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
}

@ -1,438 +0,0 @@
package com.xky.ui.module.warehouseManagement;
import com.xky.pojo.Warehouses;
import com.xky.ui.module.warehouseManagement.select.WarehouseService;
import com.xky.ui.module.warehouseManagement.add.AddWarehouse;
import com.xky.ui.module.warehouseManagement.delete.DeleteWarehouse;
import com.xky.ui.module.warehouseManagement.select.SelectWarehouse;
import com.xky.ui.module.warehouseManagement.update.UpdateWarehouse;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.format.DateTimeFormatter;
import java.util.List;
import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;
/**
*
*/
public class WarehouseManage {
static JTable table;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
/**
*
* @param refreshAction
* @return
*/
public static JPanel createWarehouseInfoPanel(Runnable refreshAction) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建顶部面板(标题和按钮)
JPanel topPanel = new JPanel(new BorderLayout());
// 标题面板
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel titleLabel = new JLabel("仓库基本信息");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
// 分割线
JSeparator separator = new JSeparator();
separator.setPreferredSize(new Dimension(1200, 2));
separator.setBackground(SEPARATOR_COLOR);
// 操作按钮面板
JPanel buttonPanel = createButtonPanel(refreshAction);
// 添加到顶部面板
topPanel.add(titlePanel, BorderLayout.NORTH);
topPanel.add(separator, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// 表格
JScrollPane scrollPane = createWarehouseTable();
// 添加到主面板
panel.add(topPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
*
* @param refreshAction
* @return
*/
private static JPanel createButtonPanel(Runnable refreshAction) {
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
buttonPanel.setBackground(SECONDARY_COLOR);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
// 创建按钮
JButton addButton = createStyledButton("添加", BUTTON_COLOR);
JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);
// 添加事件监听器
addButton.addActionListener(e -> {
AddWarehouse addWarehouse = new AddWarehouse();
addWarehouse.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (refreshAction != null) {
refreshAction.run();
}
}
});
});
deleteButton.addActionListener(e -> {
DeleteWarehouse deleteWarehouse = new DeleteWarehouse();
deleteWarehouse.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (refreshAction != null) {
refreshAction.run();
}
}
});
});
updateButton.addActionListener(e -> {
UpdateWarehouse updateWarehouse = new UpdateWarehouse();
updateWarehouse.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (refreshAction != null) {
refreshAction.run();
}
}
});
});
queryButton.addActionListener(e -> {
showSearchDialog();
});
refreshButton.addActionListener(e -> {
SelectWarehouse.resetSearchStatus();
if (refreshAction != null) {
refreshAction.run();
// 更新状态消息
updateStatusMessage("仓库数据已刷新");
// 启动自动刷新
if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
autoRefreshTimer.start();
}
}
});
// 添加按钮到面板
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(queryButton);
buttonPanel.add(refreshButton);
return buttonPanel;
}
/**
*
* @param text
* @param bgColor
* @return
*/
private static JButton createStyledButton(String text, Color bgColor) {
JButton button = new JButton(text);
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(100, 35));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
return button;
}
/**
*
* @return
*/
public static JScrollPane createWarehouseTable() {
// 表格列名
String[] columnNames = {"仓库ID", "仓库编码", "仓库名称", "仓库位置", "是否启用", "创建时间", "更新时间"};
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
// 创建表格
table = new JTable(model);
table.setRowHeight(30);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
table.getTableHeader().setBackground(PRIMARY_COLOR);
table.getTableHeader().setForeground(Color.BLACK);
// 确保表头文本可见
table.getTableHeader().setOpaque(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowGrid(true);
table.setGridColor(new Color(230, 230, 230));
// 设置表格列宽
table.getColumnModel().getColumn(0).setPreferredWidth(70); // 仓库ID
table.getColumnModel().getColumn(1).setPreferredWidth(100); // 仓库编码
table.getColumnModel().getColumn(2).setPreferredWidth(150); // 仓库名称
table.getColumnModel().getColumn(3).setPreferredWidth(200); // 仓库位置
table.getColumnModel().getColumn(4).setPreferredWidth(70); // 是否启用
table.getColumnModel().getColumn(5).setPreferredWidth(150); // 创建时间
table.getColumnModel().getColumn(6).setPreferredWidth(150); // 更新时间
// 创建滚动面板
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
scrollPane.getViewport().setBackground(Color.WHITE);
return scrollPane;
}
/**
*
* @param table
* @param warehouseList
*/
public static void updateTableData(JTable table, List<Warehouses> warehouseList) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
// 清空表格中现有的数据
model.setRowCount(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Warehouses warehouse : warehouseList) {
model.addRow(new Object[]{
warehouse.getWarehouseId(),
warehouse.getWarehouseCode(),
warehouse.getWarehouseName(),
warehouse.getLocation(),
warehouse.getIsActive() ? "是" : "否",
warehouse.getCreatedTime().format(formatter),
warehouse.getUpdatedTime().format(formatter)
});
}
// 触发表格数据刷新
model.fireTableDataChanged();
}
/**
*
*/
private static void showSearchDialog() {
// 创建对话框
JDialog searchDialog = new JDialog((Frame)null, "查询仓库", true);
searchDialog.setSize(550, 450);
searchDialog.setLocationRelativeTo(null);
searchDialog.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
// 创建单选按钮组
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton idRadio = new JRadioButton("按ID查询", true);
JRadioButton nameRadio = new JRadioButton("按名称查询");
JRadioButton codeRadio = new JRadioButton("按编码查询");
JRadioButton locationRadio = new JRadioButton("按位置查询");
JRadioButton keywordRadio = new JRadioButton("关键字查询");
buttonGroup.add(idRadio);
buttonGroup.add(nameRadio);
buttonGroup.add(codeRadio);
buttonGroup.add(locationRadio);
buttonGroup.add(keywordRadio);
radioPanel.add(idRadio);
radioPanel.add(nameRadio);
radioPanel.add(codeRadio);
radioPanel.add(locationRadio);
radioPanel.add(keywordRadio);
topPanel.add(radioPanel, BorderLayout.NORTH);
// 创建搜索条件面板
JPanel searchPanel = new JPanel(new BorderLayout());
JLabel searchLabel = new JLabel("查询条件: ");
JTextField searchField = new JTextField(20);
JButton searchButton = new JButton("搜索");
searchButton.setBackground(new Color(255, 175, 175)); // 浅粉色
JPanel searchFieldPanel = new JPanel(new BorderLayout());
searchFieldPanel.add(searchLabel, BorderLayout.WEST);
searchFieldPanel.add(searchField, BorderLayout.CENTER);
searchFieldPanel.add(searchButton, BorderLayout.EAST);
searchPanel.add(searchFieldPanel, BorderLayout.NORTH);
// 添加提示信息
JLabel tipLabel = new JLabel("提示: 关键字查询将搜索名称/编码/位置");
tipLabel.setForeground(Color.GRAY);
tipLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
searchPanel.add(tipLabel, BorderLayout.CENTER);
topPanel.add(searchPanel, BorderLayout.CENTER);
searchDialog.add(topPanel, BorderLayout.NORTH);
// 创建表格
String[] columnNames = {"仓库ID", "仓库编码", "仓库名称", "仓库位置", "是否启用", "创建时间", "更新时间"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 设置表格不可编辑
}
};
JTable resultTable = new JTable(tableModel);
resultTable.setRowHeight(25);
resultTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14));
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
searchDialog.add(scrollPane, BorderLayout.CENTER);
// 创建底部按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
JButton selectButton = new JButton("选择");
JButton cancelButton = new JButton("取消");
selectButton.setBackground(new Color(255, 175, 175)); // 浅粉色
cancelButton.setBackground(new Color(255, 175, 175)); // 浅粉色
selectButton.setPreferredSize(new Dimension(100, 30));
cancelButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(selectButton);
buttonPanel.add(cancelButton);
searchDialog.add(buttonPanel, BorderLayout.SOUTH);
// 设置按钮动作
searchButton.addActionListener(e -> {
String searchText = searchField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
List<Warehouses> results = null;
try {
if (idRadio.isSelected()) {
try {
int id = Integer.parseInt(searchText);
results = WarehouseService.selectWarehousesById(id);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if (nameRadio.isSelected()) {
results = WarehouseService.searchWarehousesByName(searchText);
} else if (codeRadio.isSelected()) {
results = WarehouseService.searchWarehousesByCode(searchText);
} else if (locationRadio.isSelected()) {
results = WarehouseService.searchWarehousesByLocation(searchText);
} else if (keywordRadio.isSelected()) {
results = WarehouseService.searchWarehousesByKeyword(searchText);
}
// 更新表格数据
tableModel.setRowCount(0);
if (results != null && !results.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Warehouses warehouse : results) {
tableModel.addRow(new Object[]{
warehouse.getWarehouseId(),
warehouse.getWarehouseCode(),
warehouse.getWarehouseName(),
warehouse.getLocation(),
warehouse.getIsActive() ? "是" : "否",
warehouse.getCreatedTime().format(formatter),
warehouse.getUpdatedTime().format(formatter)
});
}
} else {
JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
});
cancelButton.addActionListener(e -> searchDialog.dispose());
selectButton.addActionListener(e -> {
int selectedRow = resultTable.getSelectedRow();
if (selectedRow >= 0) {
// 获取选中的行数据
int warehouseId = (int) tableModel.getValueAt(selectedRow, 0);
// 获取选中的仓库数据
List<Warehouses> selectedWarehouse = WarehouseService.selectWarehousesById(warehouseId);
if (selectedWarehouse != null && !selectedWarehouse.isEmpty()) {
// 清空主表格并只显示选中的仓库
updateTableData(table, selectedWarehouse);
// 停止自动刷新
if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
System.out.println("停止自动刷新");
autoRefreshTimer.stop();
}
// 更新状态消息
updateStatusMessage("已选择仓库: " + selectedWarehouse.get(0).getWarehouseName());
}
searchDialog.dispose();
} else {
JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
}
});
// 设置回车键触发搜索按钮
searchDialog.getRootPane().setDefaultButton(searchButton);
// 显示对话框
searchDialog.setVisible(true);
}
}

@ -1,306 +0,0 @@
package com.xky.ui.module.warehouseManagement.add;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class AddWarehouse extends JFrame {
private JPanel jPanel1, jPanel2, jPanel3;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
// 定义颜色常量
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
public AddWarehouse() {
setTitle("添加仓库");
setSize(500, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init() {
setLayout(new BorderLayout()); // 设置主布局
// 创建主面板并设置背景渐变
JPanel mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 标题面板
jPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jPanel2.setOpaque(false);
JLabel jLabel = new JLabel("添加仓库信息");
jLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
jLabel.setForeground(PRIMARY_COLOR);
jPanel2.add(jLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setOpaque(false);
titlePanel.add(jPanel2, BorderLayout.CENTER);
titlePanel.add(separator, BorderLayout.SOUTH);
titlePanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(titlePanel, BorderLayout.NORTH);
// 表单面板
jPanel1 = new JPanel(new GridBagLayout());
jPanel1.setOpaque(false);
JLabel[] labels = new JLabel[]{
new JLabel("仓库编码 *"),
new JLabel("仓库名称 *"),
new JLabel("仓库位置 *"),
new JLabel("是否启用 *")
};
// 创建正确大小的文本框数组
textFields = new JTextField[3]; // 只需要3个文本框另一个是下拉框
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
gbc.insets = new Insets(10, 10, 10, 10);
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
// 创建圆角边框的文本框样式
for (int i = 0; i < labels.length; i++) {
gbc.gridx = 0;
gbc.gridy = i;
gbc.anchor = GridBagConstraints.WEST;
labels[i].setFont(labelFont);
labels[i].setForeground(PRIMARY_COLOR);
jPanel1.add(labels[i], gbc);
gbc.gridx = 1;
gbc.weightx = 1.0;
if (i < 3) {
// 前三个是文本框:仓库编码、仓库名称、仓库位置
textFields[i] = new JTextField(20);
textFields[i].setFont(inputFont);
textFields[i].setPreferredSize(new Dimension(250, 35));
jPanel1.add(textFields[i], gbc);
} else {
// 是否启用下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(inputFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
jPanel1.add(isActiveComboBox, gbc);
}
}
// 添加字段说明标签
JLabel noteLabel = new JLabel("<html><body style='width: 350px'>" +
"<p style='color: #666666;'>注意:带 * 的字段为必填项</p>" +
"</body></html>");
noteLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
gbc.gridx = 0;
gbc.gridy = labels.length;
gbc.gridwidth = 2;
gbc.insets = new Insets(20, 10, 10, 10);
jPanel1.add(noteLabel, gbc);
// 添加表单面板到卡片容器
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formCard.add(jPanel1, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
// 按钮面板
jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
jPanel3.setOpaque(false);
JButton submitButton = new JButton("提交");
submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
submitButton.setPreferredSize(new Dimension(120, 40));
submitButton.setBackground(BUTTON_COLOR);
submitButton.setForeground(Color.WHITE);
submitButton.setFocusPainted(false);
submitButton.setBorderPainted(false);
JButton resetButton = new JButton("重置");
resetButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
resetButton.setPreferredSize(new Dimension(120, 40));
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.setForeground(Color.WHITE);
resetButton.setFocusPainted(false);
resetButton.setBorderPainted(false);
jPanel3.add(submitButton);
jPanel3.add(resetButton);
mainPanel.add(jPanel3, BorderLayout.SOUTH);
add(mainPanel);
// 重置按钮事件
resetButton.addActionListener(_ -> {
for (JTextField field : textFields) {
field.setText("");
}
isActiveComboBox.setSelectedIndex(0);
});
// 提交按钮事件
submitButton.addActionListener(e -> {
try {
// 获取输入值
String warehouseCode = textFields[0].getText().trim();
String warehouseName = textFields[1].getText().trim();
String location = textFields[2].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
// 进行输入校验
if (!validateInputs(warehouseCode, warehouseName, location, isActive)) {
return; // 如果校验不通过,直接返回
}
if (addWarehouse(warehouseCode, warehouseName, location, isActive)) {
JOptionPane.showMessageDialog(AddWarehouse.this, "仓库信息添加成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(AddWarehouse.this, "仓库信息添加失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(AddWarehouse.this, "发生错误:" + ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
}
});
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
/**
*
* @return truefalse
*/
private boolean validateInputs(String warehouseCode, String warehouseName, String location, String isActive) {
// 1. 校验仓库编码
if (warehouseCode.isEmpty()) {
showValidationError("仓库编码不能为空");
return false;
}
// 2. 校验仓库名称
if (warehouseName.isEmpty()) {
showValidationError("仓库名称不能为空");
return false;
}
// 3. 校验仓库位置
if (location.isEmpty()) {
showValidationError("仓库位置不能为空");
return false;
}
// 4. 校验是否启用 - 现在使用下拉框,不需要额外校验
// 所有校验通过
return true;
}
/**
*
* @param message
*/
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
}
public boolean addWarehouse(String warehouseCode, String warehouseName, String location, String isActive) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"INSERT INTO warehouses(warehouse_code, warehouse_name, location, is_active, created_time, updated_time) VALUES (?, ?, ?, ?, NOW(), NOW())",
Statement.RETURN_GENERATED_KEYS
);
preparedStatement.setString(1, warehouseCode);
preparedStatement.setString(2, warehouseName);
preparedStatement.setString(3, location);
preparedStatement.setString(4, isActive);
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("影响行数为" + i + "添加成功!");
return true;
} else {
System.out.println("影响行数为" + i + "添加失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
try {
// 尝试使用系统外观
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(AddWarehouse::new);
}
}

@ -1,289 +0,0 @@
package com.xky.ui.module.warehouseManagement.delete;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DeleteWarehouse extends JFrame {
// 定义确认删除的安全字符串
private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
public DeleteWarehouse(){
setTitle("删除仓库");
setSize(320,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件
// 创建标题面板
JPanel titlePanel = new JPanel();
JLabel jLabel = new JLabel("请输入你要删除的仓库ID:", SwingConstants.CENTER);
jLabel.setFont(new Font("黑体", Font.BOLD, 20));
titlePanel.add(jLabel);
jPanel.add(titlePanel);
// 创建输入面板
JPanel inputPanel = new JPanel();
JTextField jTextField = new JTextField(20);
jTextField.setPreferredSize(new Dimension(300, 30));
inputPanel.add(jTextField);
jPanel.add(inputPanel);
// 创建按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
JButton jButton = new JButton("删除");
jButton.setFont(new Font("黑体", Font.BOLD, 20));
jButton.setBorderPainted(false);
jButton.setBackground(Color.PINK);
jButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton);
JButton jButton1 = new JButton("取消");
jButton1.setFont(new Font("黑体", Font.BOLD, 20));
jButton1.setBorderPainted(false);
jButton1.setBackground(Color.PINK);
jButton1.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(jButton1);
jPanel.add(buttonPanel);
// 创建删除所有仓库的按钮面板
JPanel deleteAllPanel = new JPanel();
JButton deleteAllButton = new JButton("删除所有仓库");
deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
deleteAllButton.setBorderPainted(false);
deleteAllButton.setBackground(Color.RED);
deleteAllButton.setForeground(Color.WHITE);
deleteAllButton.setPreferredSize(new Dimension(200, 30));
deleteAllPanel.add(deleteAllButton);
jPanel.add(deleteAllPanel);
add(jPanel, BorderLayout.CENTER);
// 单个仓库删除按钮事件
jButton.addActionListener(e -> {
String idText = jTextField.getText().trim();
if (idText.isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入你要删除的仓库ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
Integer id = Integer.valueOf(idText);
int i = JOptionPane.showConfirmDialog(null, "你确定要删除该仓库信息吗?", "删除提示", JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION){
if (selectWarehouseById(id)){
deleteWarehouse(id);
JOptionPane.showMessageDialog(null, "该仓库信息删除成功!", "成功提示", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "找不到该仓库ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
}
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
}
});
// 取消按钮事件
jButton1.addActionListener(e -> {
dispose();
});
// 删除所有仓库按钮事件
deleteAllButton.addActionListener(e -> {
// 显示警告对话框,要求用户确认
int option = JOptionPane.showConfirmDialog(
null,
"警告:此操作将删除所有仓库信息,且无法恢复!\n确定要继续吗",
"危险操作确认",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (option == JOptionPane.YES_OPTION) {
// 创建输入对话框,要求用户输入安全确认码
JPanel confirmPanel = new JPanel();
confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel instructionLabel = new JLabel("为确保安全,请输入以下确认码:");
instructionLabel.setForeground(Color.RED);
instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(instructionLabel);
confirmPanel.add(Box.createVerticalStrut(10));
// 使用JTextField显示确认码允许选择和复制
JTextField codeField = new JTextField(CONFIRM_CODE);
codeField.setEditable(false);
codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
codeField.setBackground(new Color(240, 240, 240));
codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(codeField);
// 添加复制按钮
JButton copyButton = new JButton("复制确认码");
copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
copyButton.addActionListener(evt -> {
StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
confirmPanel.add(Box.createVerticalStrut(5));
confirmPanel.add(copyButton);
confirmPanel.add(Box.createVerticalStrut(15));
JLabel inputLabel = new JLabel("请在下方输入确认码:");
inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(inputLabel);
confirmPanel.add(Box.createVerticalStrut(5));
JTextField confirmField = new JTextField(20);
confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(confirmField);
confirmPanel.add(Box.createVerticalStrut(10));
JLabel warningLabel = new JLabel("请注意:此操作不可撤销!");
warningLabel.setForeground(Color.RED);
warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
confirmPanel.add(warningLabel);
int result = JOptionPane.showConfirmDialog(
null,
confirmPanel,
"安全确认",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
// 如果用户点击确定,检查输入的确认码是否正确
if (result == JOptionPane.OK_OPTION) {
String userInput = confirmField.getText().trim();
if (CONFIRM_CODE.equals(userInput)) {
// 执行删除所有仓库的操作
if (deleteAllWarehouses()) {
JOptionPane.showMessageDialog(
null,
"所有仓库信息已成功删除!",
"操作成功",
JOptionPane.INFORMATION_MESSAGE
);
dispose();
} else {
JOptionPane.showMessageDialog(
null,
"删除所有仓库信息失败,请检查数据库连接或权限!",
"操作失败",
JOptionPane.ERROR_MESSAGE
);
}
} else {
JOptionPane.showMessageDialog(
null,
"确认码输入错误,操作已取消!",
"验证失败",
JOptionPane.ERROR_MESSAGE
);
}
}
}
});
}
/**
* ID
* @param id ID
* @return
*/
public boolean selectWarehouseById(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM warehouses WHERE warehouse_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
return resultSet.next(); // 如果有结果则返回true
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
/**
*
* @param id ID
* @return
*/
public boolean deleteWarehouse(Integer id){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM warehouses WHERE warehouse_id = ?");
preparedStatement.setInt(1, id);
int i = preparedStatement.executeUpdate();
if (i > 0){
System.out.println("影响行数为" + i + "删除成功!");
return true;
} else {
System.out.println("影响行数为" + i + "删除失败!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
/**
*
* @return
*/
public boolean deleteAllWarehouses() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM warehouses");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("删除了" + rowsAffected + "条仓库记录");
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DeleteWarehouse::new);
}
}

@ -1,220 +0,0 @@
package com.xky.ui.module.warehouseManagement.select;
import com.xky.pojo.Warehouses;
import lombok.*;
import javax.swing.*;
import java.awt.*;
import java.util.List;
@Setter
public class SelectWarehouse extends JFrame {
@Getter
private static Integer Id;
// 存储查询结果
@Getter
private static List<Warehouses> searchResults;
// 标记查询是否成功
@Getter
private static boolean searchSuccessful = false;
@Getter
private final WarehouseService warehouseService;
private JComboBox<String> searchTypeComboBox;
private JTextField searchTextField;
public SelectWarehouse(){
setTitle("查询仓库");
setSize(400, 220);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
warehouseService = new WarehouseService();
// 重置搜索状态
searchSuccessful = false;
searchResults = null;
init();
setVisible(true);
}
void init(){
setLayout(new BorderLayout());
// 创建主面板使用GridBagLayout以获得更好的布局控制
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
// 添加查询类型选择
JLabel searchTypeLabel = new JLabel("查询类型:");
searchTypeLabel.setFont(new Font("黑体", Font.BOLD, 16));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
mainPanel.add(searchTypeLabel, gbc);
// 查询类型下拉框
searchTypeComboBox = new JComboBox<>(new String[]{"仓库ID", "仓库名称", "仓库编码", "仓库位置", "关键字查询"});
searchTypeComboBox.setFont(new Font("宋体", Font.PLAIN, 14));
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 1;
mainPanel.add(searchTypeComboBox, gbc);
// 添加标签
JLabel searchLabel = new JLabel("查询内容:");
searchLabel.setFont(new Font("黑体", Font.BOLD, 16));
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
mainPanel.add(searchLabel, gbc);
// 添加文本框
searchTextField = new JTextField(20);
searchTextField.setPreferredSize(new Dimension(210, 30));
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1;
mainPanel.add(searchTextField, gbc);
// 添加提示信息
JLabel hintLabel = new JLabel("提示: 关键字查询将搜索名称/编码/位置");
hintLabel.setFont(new Font("宋体", Font.ITALIC, 12));
hintLabel.setForeground(Color.GRAY);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
mainPanel.add(hintLabel, gbc);
// 按钮面板
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
// 确定按钮
JButton searchButton = new JButton("查询");
searchButton.setFont(new Font("黑体", Font.BOLD, 16));
searchButton.setBackground(Color.PINK);
searchButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(searchButton);
// 取消按钮
JButton cancelButton = new JButton("取消");
cancelButton.setFont(new Font("黑体", Font.BOLD, 16));
cancelButton.setBackground(Color.PINK);
cancelButton.setPreferredSize(new Dimension(100, 30));
buttonPanel.add(cancelButton);
// 添加按钮面板
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
mainPanel.add(buttonPanel, gbc);
// 确定按钮事件处理
searchButton.addActionListener(e -> {
String searchText = searchTextField.getText().trim();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(SelectWarehouse.this,
"查询内容不能为空", "输入提示", JOptionPane.WARNING_MESSAGE);
return;
}
String searchType = (String) searchTypeComboBox.getSelectedItem();
List<Warehouses> warehouseList = null;
try {
if ("仓库ID".equals(searchType)) {
try {
Integer id = Integer.valueOf(searchText);
if (id <= 0) {
JOptionPane.showMessageDialog(SelectWarehouse.this,
"仓库ID必须为正整数", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
warehouseList = WarehouseService.selectWarehousesById(id);
Id = id; // 保存ID用于其他操作
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(SelectWarehouse.this,
"请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
return;
}
} else if ("仓库名称".equals(searchType)) {
warehouseList = WarehouseService.searchWarehousesByName(searchText);
} else if ("仓库编码".equals(searchType)) {
warehouseList = WarehouseService.searchWarehousesByCode(searchText);
} else if ("仓库位置".equals(searchType)) {
warehouseList = WarehouseService.searchWarehousesByLocation(searchText);
} else if ("关键字查询".equals(searchType)) {
warehouseList = WarehouseService.searchWarehousesByKeyword(searchText);
}
if (warehouseList != null && !warehouseList.isEmpty()) {
// 保存查询结果和成功状态
searchResults = warehouseList;
searchSuccessful = true;
StringBuilder resultMessage = new StringBuilder("查找到 " + warehouseList.size() + " 个匹配仓库:\n");
for (int i = 0; i < Math.min(warehouseList.size(), 5); i++) {
Warehouses warehouse = warehouseList.get(i);
resultMessage.append(String.format("ID: %d, 名称: %s, 编码: %s\n",
warehouse.getWarehouseId(),
warehouse.getWarehouseName(),
warehouse.getWarehouseCode()));
}
if (warehouseList.size() > 5) {
resultMessage.append("...(共 ").append(warehouseList.size()).append(" 条记录)");
}
JOptionPane.showMessageDialog(SelectWarehouse.this,
resultMessage.toString(), "查找成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(SelectWarehouse.this,
"未找到匹配的仓库记录", "查找失败", JOptionPane.ERROR_MESSAGE);
Id = null;
searchSuccessful = false;
searchResults = null;
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(SelectWarehouse.this,
"查询过程中发生错误: " + ex.getMessage(), "查询错误", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
searchSuccessful = false;
searchResults = null;
}
});
// 取消按钮事件处理
cancelButton.addActionListener(e -> {
Id = null;
searchSuccessful = false;
searchResults = null;
dispose();
});
// 设置回车键触发确定按钮
getRootPane().setDefaultButton(searchButton);
add(mainPanel, BorderLayout.CENTER);
}
/**
*
*/
public static void resetSearchStatus() {
searchSuccessful = false;
searchResults = null;
Id = null;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SelectWarehouse::new);
}
}

@ -1,216 +0,0 @@
package com.xky.ui.module.warehouseManagement.select;
import com.xky.pojo.Warehouses;
import com.xky.utils.DBUtils;
import lombok.Getter;
import lombok.Setter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Setter
@Getter
public class WarehouseService {
/**
*
* @param resultSet
* @return
* @throws SQLException SQL
*/
private static Warehouses createWarehouseFromResultSet(ResultSet resultSet) throws SQLException {
Warehouses warehouse = new Warehouses();
warehouse.setWarehouseId(resultSet.getInt("warehouse_id"));
warehouse.setWarehouseCode(resultSet.getString("warehouse_code"));
warehouse.setWarehouseName(resultSet.getString("warehouse_name"));
warehouse.setLocation(resultSet.getString("location"));
warehouse.setIsActive(resultSet.getBoolean("is_active"));
warehouse.setCreatedTime(resultSet.getTimestamp("created_time").toLocalDateTime());
warehouse.setUpdatedTime(resultSet.getTimestamp("updated_time").toLocalDateTime());
return warehouse;
}
/**
*
* @return
*/
public static List<Warehouses> selectAllWarehouses(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM warehouses ORDER BY warehouse_id");
resultSet = preparedStatement.executeQuery();
// 直接使用while循环处理结果集
while (resultSet.next()){
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
/**
* ID
* @param id ID
* @return
*/
public static List<Warehouses> selectWarehousesById(Integer id){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM warehouses WHERE warehouse_id = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
/**
*
* @param name
* @return
*/
public static List<Warehouses> searchWarehousesByName(String name) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"SELECT * FROM warehouses WHERE warehouse_name LIKE ? ORDER BY warehouse_id"
);
preparedStatement.setString(1, "%" + name + "%");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
/**
*
* @param code
* @return
*/
public static List<Warehouses> searchWarehousesByCode(String code) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"SELECT * FROM warehouses WHERE warehouse_code LIKE ? ORDER BY warehouse_id"
);
preparedStatement.setString(1, "%" + code + "%");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
/**
*
* @param location
* @return
*/
public static List<Warehouses> searchWarehousesByLocation(String location) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"SELECT * FROM warehouses WHERE location LIKE ? ORDER BY warehouse_id"
);
preparedStatement.setString(1, "%" + location + "%");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
/**
*
* @param keyword
* @return
*/
public static List<Warehouses> searchWarehousesByKeyword(String keyword) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Warehouses> warehousesList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
// 使用LIKE进行模糊查询支持仓库名称、编码和位置
preparedStatement = connection.prepareStatement(
"SELECT * FROM warehouses WHERE warehouse_name LIKE ? OR warehouse_code LIKE ? OR location LIKE ? ORDER BY warehouse_id"
);
String searchPattern = "%" + keyword + "%";
preparedStatement.setString(1, searchPattern);
preparedStatement.setString(2, searchPattern);
preparedStatement.setString(3, searchPattern);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
warehousesList.add(createWarehouseFromResultSet(resultSet));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
return warehousesList;
}
}

@ -1,426 +0,0 @@
package com.xky.ui.module.warehouseManagement.update;
import com.xky.pojo.Warehouses;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
public class UpdateWarehouse extends JFrame {
private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
private JTextField[] textFields;
private JComboBox<String> isActiveComboBox;
private JButton updateButton, queryButton;
private JLabel statusLabel;
private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
private static final Color BUTTON_COLOR = new Color(100, 149, 237);
private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
public UpdateWarehouse() {
initializeFrame();
initComponents();
setVisible(true);
}
private void initializeFrame() {
setTitle("仓库信息修改");
setSize(550, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
private void initComponents() {
// 创建主面板并设置背景渐变
mainPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
};
mainPanel.setLayout(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
// 1. 头部面板
createHeaderPanel();
// 2. 表单面板
createFormPanel();
// 3. 按钮面板
createButtonPanel();
// 4. 状态面板
createStatusPanel();
// 添加事件监听
setupEventListeners();
add(mainPanel);
}
private void createHeaderPanel() {
headerPanel = new JPanel(new BorderLayout());
headerPanel.setOpaque(false);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlePanel.setOpaque(false);
JLabel titleLabel = new JLabel("仓库信息修改");
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
titleLabel.setForeground(PRIMARY_COLOR);
titlePanel.add(titleLabel);
JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
hintPanel.setOpaque(false);
JLabel hintLabel = new JLabel("请输入仓库ID查询后再修改");
hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
hintLabel.setForeground(Color.GRAY);
hintPanel.add(hintLabel);
// 添加分隔线
JSeparator separator = new JSeparator();
separator.setForeground(PRIMARY_COLOR);
separator.setPreferredSize(new Dimension(450, 2));
headerPanel.add(titlePanel, BorderLayout.NORTH);
headerPanel.add(hintPanel, BorderLayout.CENTER);
headerPanel.add(separator, BorderLayout.SOUTH);
headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
mainPanel.add(headerPanel, BorderLayout.NORTH);
}
private void createFormPanel() {
// 创建带圆角和阴影的面板
JPanel formCard = createRoundedPanel();
formCard.setLayout(new BorderLayout());
formPanel = new JPanel(new GridBagLayout());
formPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
String[] labels = {"仓库ID *", "仓库编码 *", "仓库名称 *", "仓库位置 *", "是否启用 *"};
textFields = new JTextField[4]; // 只需要4个文本框另一个是下拉框
Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
for (int i = 0; i < labels.length; i++) {
// 添加标签
gbc.gridx = 0;
gbc.gridy = i;
gbc.weightx = 0.3;
JLabel label = new JLabel(labels[i]);
label.setFont(labelFont);
label.setForeground(PRIMARY_COLOR);
formPanel.add(label, gbc);
// 添加输入控件
gbc.gridx = 1;
gbc.weightx = 0.7;
if (i != 4) { // 不是是否启用
textFields[i] = new JTextField(20);
textFields[i].setFont(fieldFont);
textFields[i].setPreferredSize(new Dimension(250, 35));
formPanel.add(textFields[i], gbc);
} else { // 是否启用使用下拉框
isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
isActiveComboBox.setFont(fieldFont);
isActiveComboBox.setPreferredSize(new Dimension(250, 35));
isActiveComboBox.setBackground(Color.WHITE);
formPanel.add(isActiveComboBox, gbc);
}
}
formCard.add(formPanel, BorderLayout.CENTER);
formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(formCard, BorderLayout.CENTER);
}
private void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
buttonPanel.setOpaque(false);
queryButton = new JButton("查询");
styleButton(queryButton, QUERY_BUTTON_COLOR);
updateButton = new JButton("修改");
styleButton(updateButton, BUTTON_COLOR);
// 初始状态下修改按钮不可用
updateButton.setEnabled(false);
buttonPanel.add(queryButton);
buttonPanel.add(updateButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void styleButton(JButton button, Color bgColor) {
button.setFont(new Font("微软雅黑", Font.BOLD, 16));
button.setPreferredSize(new Dimension(120, 40));
button.setBackground(bgColor);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorderPainted(false);
}
private void createStatusPanel() {
JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
statusPanel.setOpaque(false);
statusPanel.setPreferredSize(new Dimension(Short.MAX_VALUE, 30));
statusLabel = new JLabel(" ");
statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
statusLabel.setForeground(Color.GRAY);
statusPanel.add(statusLabel);
}
/**
*
*/
private JPanel createRoundedPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
};
panel.setOpaque(false);
// 添加阴影边框
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
));
return panel;
}
private void setupEventListeners() {
// 查询按钮事件
queryButton.addActionListener(e -> {
String warehouseIdStr = textFields[0].getText().trim();
if (warehouseIdStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入仓库ID", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
try {
int warehouseId = Integer.parseInt(warehouseIdStr);
queryWarehouseInBackground(warehouseId);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
}
});
// 修改按钮事件
updateButton.addActionListener(e -> {
try {
// 首先进行输入校验
if (!validateInputs()) {
return; // 如果校验不通过,直接返回
}
Integer warehouseId = Integer.valueOf(textFields[0].getText().trim());
String warehouseCode = textFields[1].getText().trim();
String warehouseName = textFields[2].getText().trim();
String location = textFields[3].getText().trim();
String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1"否"对应0
updateWarehouseInBackground(warehouseId, warehouseCode, warehouseName, location, isActive.equals("1"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
private void queryWarehouseInBackground(int warehouseId) {
SwingWorker<Warehouses, Void> worker = new SwingWorker<Warehouses, Void>() {
@Override
protected Warehouses doInBackground() throws Exception {
statusLabel.setText("正在查询...");
return findWarehouseById(warehouseId);
}
@Override
protected void done() {
try {
Warehouses warehouse = get();
if (warehouse != null) {
// 填充表单数据
textFields[0].setText(String.valueOf(warehouse.getWarehouseId()));
textFields[1].setText(warehouse.getWarehouseCode());
textFields[2].setText(warehouse.getWarehouseName());
textFields[3].setText(warehouse.getLocation());
// 设置是否启用下拉框
isActiveComboBox.setSelectedIndex(warehouse.getIsActive() ? 0 : 1);
// 启用修改按钮
updateButton.setEnabled(true);
statusLabel.setText("查询成功");
} else {
JOptionPane.showMessageDialog(UpdateWarehouse.this, "未找到该仓库", "提示", JOptionPane.WARNING_MESSAGE);
updateButton.setEnabled(false);
statusLabel.setText("未找到仓库");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(UpdateWarehouse.this, "查询失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
statusLabel.setText("查询失败");
}
}
};
worker.execute();
}
private void updateWarehouseInBackground(Integer warehouseId, String warehouseCode, String warehouseName, String location, Boolean isActive) {
SwingWorker<Boolean, Void> worker = new SwingWorker<>() {
@Override
protected Boolean doInBackground() throws Exception {
statusLabel.setText("正在更新...");
return updateWarehouse(warehouseId, warehouseCode, warehouseName, location, isActive);
}
@Override
protected void done() {
try {
boolean success = get();
if (success) {
JOptionPane.showMessageDialog(UpdateWarehouse.this, "仓库信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
dispose();
} else {
JOptionPane.showMessageDialog(UpdateWarehouse.this, "仓库信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
statusLabel.setText("更新失败");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(UpdateWarehouse.this, "更新失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
statusLabel.setText("更新失败: " + e.getMessage());
}
}
};
worker.execute();
}
private boolean validateInputs() {
// 1. 校验仓库ID
if (textFields[0].getText().trim().isEmpty()) {
showValidationError("仓库ID不能为空");
return false;
}
try {
Integer.parseInt(textFields[0].getText().trim());
} catch (NumberFormatException e) {
showValidationError("仓库ID必须是数字");
return false;
}
// 2. 校验仓库编码
if (textFields[1].getText().trim().isEmpty()) {
showValidationError("仓库编码不能为空");
return false;
}
// 3. 校验仓库名称
if (textFields[2].getText().trim().isEmpty()) {
showValidationError("仓库名称不能为空");
return false;
}
// 4. 校验仓库位置
if (textFields[3].getText().trim().isEmpty()) {
showValidationError("仓库位置不能为空");
return false;
}
// 所有校验通过
return true;
}
private void showValidationError(String message) {
JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
statusLabel.setText("验证错误: " + message);
}
private Warehouses findWarehouseById(int warehouseId) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM warehouses WHERE warehouse_id = ?");
preparedStatement.setInt(1, warehouseId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Warehouses warehouse = new Warehouses();
warehouse.setWarehouseId(resultSet.getInt("warehouse_id"));
warehouse.setWarehouseCode(resultSet.getString("warehouse_code"));
warehouse.setWarehouseName(resultSet.getString("warehouse_name"));
warehouse.setLocation(resultSet.getString("location"));
warehouse.setIsActive("1".equals(resultSet.getString("is_active")));
return warehouse;
}
return null;
} finally {
DBUtils.closeAll(connection, preparedStatement, resultSet);
}
}
private boolean updateWarehouse(Integer warehouseId, String warehouseCode, String warehouseName, String location, Boolean isActive) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(
"UPDATE warehouses SET warehouse_code = ?, warehouse_name = ?, location = ?, is_active = ?, updated_time = NOW() WHERE warehouse_id = ?");
preparedStatement.setString(1, warehouseCode);
preparedStatement.setString(2, warehouseName);
preparedStatement.setString(3, location);
preparedStatement.setString(4, isActive ? "1" : "0");
preparedStatement.setInt(5, warehouseId);
return preparedStatement.executeUpdate() > 0;
} finally {
DBUtils.closeAll(connection, preparedStatement, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(UpdateWarehouse::new);
}
}

@ -1,73 +0,0 @@
package com.xky.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtils {
private static final Properties PROPERTIES = new Properties();
static {
InputStream resourceAsStream = DBUtils.class.getResourceAsStream("/application.properties");
if (resourceAsStream == null) {
throw new RuntimeException("无法加载数据库配置文件");
}
try {
PROPERTIES.load(resourceAsStream);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
System.err.println("加载数据库配置或驱动失败: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
*
* @return
*/
public static Connection getConnection(){
Connection connection;
try {
connection = DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
if (connection!=null){
System.out.println("数据库已连接成功,数据正在刷新!");
}else {
System.out.println("数据库连接失败!");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return connection;
}
/**
*
* @param connection
* @param preparedStatement
* @param resultSet
*/
public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
try {
if (resultSet!=null){
resultSet.close();
}
if (preparedStatement!=null){
preparedStatement.close();
}
if (connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
DBUtils.getConnection();
}
}

@ -1,26 +0,0 @@
package com.xky.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
public static String md5Encrypt(String text) {
try {
// 获取MD5实例
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算哈希值(返回字节数组)
byte[] messageDigest = md.digest(text.getBytes());
// 转为十六进制字符串
BigInteger no = new BigInteger(1, messageDigest);
String hashText = no.toString(16);
// 补全32位不足时前面补0
while (hashText.length() < 32) {
hashText = "0" + hashText;
}
return hashText;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}

@ -1,5 +0,0 @@
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/product?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username=root
password=123456

@ -1,140 +0,0 @@
-- 1. 商品分类表
CREATE TABLE product_categories (
category_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '分类ID主键自增',
category_name VARCHAR(100) NOT NULL COMMENT '分类名称',
parent_id INT COMMENT '父分类ID用于构建层级结构',
is_active BOOLEAN DEFAULT TRUE COMMENT '是否启用(1:启用,0:禁用)',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_parent_id (parent_id),
FOREIGN KEY (parent_id) REFERENCES product_categories(category_id) ON DELETE SET NULL ON UPDATE CASCADE
) COMMENT '商品分类表';
-- 2. 商品表
CREATE TABLE products (
product_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '商品ID主键自增',
product_code VARCHAR(50) UNIQUE NOT NULL COMMENT '商品编码(唯一)',
product_name VARCHAR(255) NOT NULL COMMENT '商品名称',
category_id INT COMMENT '所属分类ID',
unit_of_measure VARCHAR(20) COMMENT '计量单位(如:个,件,kg等)',
min_stock_level INT DEFAULT 0 COMMENT '最小库存量',
is_active BOOLEAN DEFAULT TRUE COMMENT '是否上架(1:是,0:否)',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_category_id (category_id),
FOREIGN KEY (category_id) REFERENCES product_categories(category_id) ON DELETE SET NULL ON UPDATE CASCADE
) COMMENT '商品基础信息表';
-- 3. 仓库表
CREATE TABLE warehouses (
warehouse_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '仓库ID主键自增',
warehouse_code VARCHAR(20) UNIQUE NOT NULL COMMENT '仓库编码',
warehouse_name VARCHAR(100) NOT NULL COMMENT '仓库名称',
location VARCHAR(255) COMMENT '仓库位置',
is_active BOOLEAN DEFAULT TRUE COMMENT '是否启用(1:是,0:否)',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) COMMENT '仓库信息表';
-- 4. 库存表
CREATE TABLE inventory (
inventory_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '库存记录ID',
product_id INT NOT NULL COMMENT '商品ID',
warehouse_id INT NOT NULL COMMENT '仓库ID',
quantity INT NOT NULL DEFAULT 0 COMMENT '当前库存数量',
allocated_quantity INT DEFAULT 0 COMMENT '已分配数量(预留)',
location_code VARCHAR(50) COMMENT '库位编码',
batch_number VARCHAR(50) COMMENT '批次号',
expiry_date DATE COMMENT '过期日期',
last_stock_update TIMESTAMP COMMENT '最后库存更新时间',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
UNIQUE KEY (product_id, warehouse_id, batch_number) COMMENT '商品+仓库+批次唯一约束',
INDEX idx_product_warehouse (product_id, warehouse_id),
FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (warehouse_id) REFERENCES warehouses(warehouse_id) ON DELETE CASCADE ON UPDATE CASCADE
) COMMENT '库存明细表';
-- 5. 客户表
CREATE TABLE customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '客户ID主键自增',
customer_code VARCHAR(50) UNIQUE COMMENT '客户编码',
customer_name VARCHAR(100) NOT NULL COMMENT '客户名称',
contact_person VARCHAR(50) COMMENT '联系人',
phone VARCHAR(20) COMMENT '联系电话',
email VARCHAR(100) COMMENT '电子邮箱',
address TEXT COMMENT '联系地址',
credit_limit DECIMAL(12,2) DEFAULT 0 COMMENT '信用额度',
is_active BOOLEAN DEFAULT TRUE COMMENT '是否有效(1:是,0:否)',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_customer_name (customer_name)
) COMMENT '客户信息表';
-- 6. 销售订单表(合并明细表字段)
CREATE TABLE sales_orders (
order_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '订单ID',
order_number VARCHAR(50) UNIQUE NOT NULL COMMENT '订单编号',
customer_id INT NOT NULL COMMENT '客户ID',
order_date DATETIME NOT NULL COMMENT '下单时间',
expected_ship_date DATE COMMENT '预计发货日期',
actual_ship_date DATE COMMENT '实际发货日期',
warehouse_id INT NOT NULL COMMENT '发货仓库ID',
order_status ENUM('draft','confirmed','processing','shipped','delivered','cancelled','returned') DEFAULT 'draft' COMMENT '订单状态',
payment_status ENUM('unpaid','partial','paid','refunded') DEFAULT 'unpaid' COMMENT '支付状态',
subtotal DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '商品总额',
tax_amount DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT'税额',
discoun_amount DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT'折扣金额',
total_amount DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '订单总金额',
paid_amount DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '已付金额',
notes VARCHAR(255) NOT NULL COMMENT'订单备注',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_customer_id (customer_id),
INDEX idx_order_date (order_date),
INDEX idx_order_status (order_status),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (warehouse_id) REFERENCES warehouses(warehouse_id) ON DELETE RESTRICT ON UPDATE CASCADE
) COMMENT '销售订单主表';
-- 7. 销售发货单表
CREATE TABLE sales_shipments (
shipment_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '发货单ID',
shipment_number VARCHAR(50) UNIQUE NOT NULL COMMENT '发货单号',
order_id INT NOT NULL COMMENT '关联订单ID',
warehouse_id INT NOT NULL COMMENT '发货仓库ID',
shipment_date DATE NOT NULL COMMENT '发货日期',
carrier VARCHAR(50) NOT NULL COMMENT'承运商',
tracking_number VARCHAR(50) NOT NULL COMMENT'物流单号',
shipping_method VARCHAR(50) NOT NULL COMMENT'运输方式',
`status` VARCHAR(10) not null COMMENT '状态',
notes VARCHAR(255) NOT NULL COMMENT'备注',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_order_id (order_id),
FOREIGN KEY (order_id) REFERENCES sales_orders(order_id) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (warehouse_id) REFERENCES warehouses(warehouse_id) ON DELETE RESTRICT ON UPDATE CASCADE
) COMMENT '销售发货单表';
-- 8. 供应商表
CREATE TABLE suppliers (
supplier_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '供应商ID主键自增',
supplier_code VARCHAR(50) UNIQUE COMMENT '供应商编码',
supplier_name VARCHAR(100) NOT NULL COMMENT '供应商名称',
contact_name VARCHAR(20) not null COMMENT'联系人姓名',
contact_phone VARCHAR(20) NOT NULL COMMENT '联系人电话',
contact_email VARCHAR(50) UNIQUE not NULL COMMENT '联系人邮箱',
address TEXT NOT NULL COMMENT '联系地址',
is_active BOOLEAN DEFAULT TRUE COMMENT '是否合作中(1:是,0:否)',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_supplier_name (supplier_name)
) COMMENT '供应商信息表';
-- 9 用户登录表
CREATE TABLE login (
username VARCHAR(20) NOT NULL UNIQUE COMMENT '用户名',
password VARCHAR(50) NOT NULL COMMENT '密码',
email VARCHAR(20) NOT NULL COMMENT '邮箱'
) COMMENT '用户登录表';
Loading…
Cancel
Save