WorkstationPanel.java 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644
  1. package com.mes.ui.component;
  2. import com.mes.core.StationContext;
  3. import com.mes.core.StationConfig;
  4. import com.mes.ui.layout.DraggableComponentWrapper;
  5. import com.mes.ui.layout.UILayoutConfig;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import javax.swing.*;
  9. import java.awt.*;
  10. import java.awt.event.ComponentAdapter;
  11. import java.awt.event.ComponentEvent;
  12. import java.io.InputStream;
  13. import java.nio.charset.StandardCharsets;
  14. import java.nio.file.Files;
  15. import java.nio.file.Path;
  16. import java.nio.file.Paths;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Objects;
  21. import javax.swing.filechooser.FileNameExtensionFilter;
  22. /**
  23. * 工位面板组件 - 与OP150版本UI保持一致
  24. */
  25. public class WorkstationPanel extends JPanel {
  26. private static final Logger log = LoggerFactory.getLogger(WorkstationPanel.class);
  27. // 工位信息
  28. private String stationCode;
  29. private String stationName;
  30. private final int stationIndex;
  31. // 配置
  32. private boolean showMaterialInput = false;
  33. private boolean showDeviceInfo = false;
  34. private String materialLabel = "底护板码";
  35. private boolean showHeader = true; // 是否显示工位号和状态栏(单工位时不显示)
  36. // UI组件 - 工件码
  37. private JTextField productSnInput;
  38. private JButton scanProductBtn;
  39. // UI组件 - 物料码
  40. private JTextField materialSnInput;
  41. private JButton scanMaterialBtn;
  42. private JButton unbindMaterialBtn;
  43. // UI组件 - 状态显示
  44. private JButton statusMenu;
  45. private JButton externalStatusMenu; // 外部状态组件引用(单工位模式使用)
  46. private JLabel stationLabel;
  47. // UI组件 - OK/NG按钮
  48. private JButton okButton;
  49. private JButton ngButton;
  50. private Image okIconImage;
  51. private Image ngIconImage;
  52. // UI组件 - 设备信息
  53. private JLabel presetCountLabel;
  54. private JTextField presetCountField;
  55. private JLabel finishedCountLabel;
  56. private JTextField finishedCountField;
  57. private JLabel deviceInfoLabel; // 第一行可选前置标签
  58. // UI组件 - 设备信息第二行
  59. private JLabel presetCountLabel2;
  60. private JTextField presetCountField2;
  61. private JLabel finishedCountLabel2;
  62. private JTextField finishedCountField2;
  63. private JLabel deviceInfoLabel2; // 第二行可选前置标签
  64. private boolean showDeviceInfo2 = false;
  65. // UI组件 - 物料标签
  66. private JLabel materialLabelUI;
  67. // 回调
  68. private WorkstationPanelListener listener;
  69. // 基准尺寸(用于计算缩放比例)
  70. private static final int BASE_WIDTH = 800;
  71. private static final int BASE_HEIGHT = 600;
  72. private double currentScale = 1.0;
  73. // 默认布局配置(相对坐标 0-1)
  74. // 单工位模式(showHeader=false)的默认布局
  75. private static final double[][] DEFAULT_LAYOUT_SINGLE = {
  76. // {x, y, width, height} - 相对于内容区域
  77. {0.005, 0.10, 0.75, 0.20}, // product_sn_input: 工件码输入框
  78. {0.76, 0.10, 0.23, 0.20}, // scan_product_btn: 扫码按钮
  79. {0.15, 0.55, 0.30, 0.25}, // ok_button: OK按钮
  80. {0.55, 0.55, 0.30, 0.25}, // ng_button: NG按钮
  81. };
  82. // 组件ID顺序(与DEFAULT_LAYOUT_SINGLE对应)
  83. private static final String[] COMPONENT_IDS = {
  84. "product_sn_input", "scan_product_btn", "ok_button", "ng_button"
  85. };
  86. // 编辑模式相关
  87. private boolean editMode = false;
  88. private UILayoutConfig uiLayoutConfig;
  89. private Map<String, DraggableComponentWrapper> componentWrappers = new HashMap<>();
  90. private JPanel gridOverlay; // 网格叠加层
  91. private Dimension capturedPanelSize; // 捕获时的面板大小
  92. private ComponentAdapter resizeListener; // 窗口大小变化监听器
  93. /**
  94. * 面板事件监听器
  95. */
  96. public interface WorkstationPanelListener {
  97. void onProductScanned(WorkstationPanel panel, String productSn);
  98. void onMaterialScanned(WorkstationPanel panel, String materialSn);
  99. void onOkClicked(WorkstationPanel panel);
  100. void onNgClicked(WorkstationPanel panel);
  101. void onUnbindClicked(WorkstationPanel panel);
  102. }
  103. public WorkstationPanel(String stationCode, int stationIndex, StationConfig config) {
  104. this(stationCode, stationIndex, config, true);
  105. }
  106. public WorkstationPanel(String stationCode, int stationIndex, StationConfig config, boolean showHeader) {
  107. this.stationCode = stationCode;
  108. this.stationName = stationCode;
  109. this.stationIndex = stationIndex;
  110. this.showHeader = showHeader;
  111. // 从配置读取显示选项
  112. if (config != null) {
  113. this.showMaterialInput = config.isEffectiveShowMaterialInput();
  114. this.showDeviceInfo = config.isShowDeviceInfo();
  115. this.showDeviceInfo2 = config.isShowDeviceInfo2();
  116. String effLabel = config.getEffectiveMaterialLabel();
  117. if (effLabel != null && !effLabel.isEmpty()) {
  118. this.materialLabel = effLabel;
  119. }
  120. }
  121. initUI();
  122. }
  123. /**
  124. * 从配置创建工位面板
  125. * @param stationInfo 工位信息
  126. * @param config 全局配置
  127. * @return 工位面板实例
  128. */
  129. public static WorkstationPanel fromConfig(StationConfig.StationInfo stationInfo, StationConfig config) {
  130. return new WorkstationPanel(
  131. stationInfo.getCode(),
  132. stationInfo.getIndex(),
  133. config
  134. );
  135. }
  136. /**
  137. * 初始化UI - 使用绝对定位 + 相对坐标,支持窗口缩放
  138. */
  139. private void initUI() {
  140. // 先确保所有组件已创建(统一入口)
  141. ensureComponentsCreated();
  142. // 使用绝对定位
  143. setLayout(null);
  144. // 设置边框
  145. if (showHeader) {
  146. setBorder(BorderFactory.createCompoundBorder(
  147. BorderFactory.createEtchedBorder(),
  148. BorderFactory.createEmptyBorder(10, 10, 10, 10)
  149. ));
  150. } else {
  151. setBorder(BorderFactory.createEmptyBorder(40, 10, 10, 10));
  152. }
  153. // 加载布局配置
  154. loadLayoutConfig();
  155. // 添加组件到面板(不使用嵌套容器)
  156. add(productSnInput);
  157. add(scanProductBtn);
  158. add(okButton);
  159. add(ngButton);
  160. // 可选组件
  161. if (showHeader) {
  162. add(stationLabel);
  163. add(statusMenu);
  164. }
  165. if (showMaterialInput) {
  166. add(materialLabelUI);
  167. add(materialSnInput);
  168. add(scanMaterialBtn);
  169. add(unbindMaterialBtn);
  170. }
  171. if (showDeviceInfo) {
  172. if (deviceInfoLabel != null) {
  173. add(deviceInfoLabel);
  174. }
  175. add(presetCountLabel);
  176. add(presetCountField);
  177. add(finishedCountLabel);
  178. add(finishedCountField);
  179. }
  180. if (showDeviceInfo2) {
  181. if (deviceInfoLabel2 != null) {
  182. add(deviceInfoLabel2);
  183. }
  184. add(presetCountLabel2);
  185. add(presetCountField2);
  186. add(finishedCountLabel2);
  187. add(finishedCountField2);
  188. }
  189. // 添加窗口大小变化监听器,实现按比例缩放
  190. resizeListener = new ComponentAdapter() {
  191. @Override
  192. public void componentResized(ComponentEvent e) {
  193. if (!editMode) {
  194. applyRuntimeLayout();
  195. }
  196. }
  197. };
  198. addComponentListener(resizeListener);
  199. // 确保面板显示后再应用布局
  200. addHierarchyListener(e -> {
  201. if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0
  202. && isShowing() && !editMode) {
  203. SwingUtilities.invokeLater(this::applyRuntimeLayout);
  204. }
  205. });
  206. // 初始应用布局(如果面板已有尺寸)
  207. if (getWidth() > 0 && getHeight() > 0) {
  208. applyRuntimeLayout();
  209. }
  210. }
  211. /**
  212. * 应用运行模式布局(相对坐标转绝对坐标)
  213. */
  214. private void applyRuntimeLayout() {
  215. int panelWidth = getWidth();
  216. int panelHeight = getHeight();
  217. // 首次有效调用时保存面板尺寸
  218. if (capturedPanelSize == null && panelWidth > 100 && panelHeight > 100) {
  219. capturedPanelSize = new Dimension(panelWidth, panelHeight);
  220. setPreferredSize(capturedPanelSize);
  221. setMinimumSize(capturedPanelSize);
  222. log.info("[{}] 首次保存面板尺寸: {}x{}", stationCode, panelWidth, panelHeight);
  223. }
  224. Insets insets = getInsets();
  225. int contentWidth = panelWidth - insets.left - insets.right;
  226. int contentHeight = panelHeight - insets.top - insets.bottom;
  227. if (contentWidth <= 0 || contentHeight <= 0) {
  228. return;
  229. }
  230. log.debug("[{}] applyRuntimeLayout: 面板={}x{}, 内容区域={}x{}",
  231. stationCode, panelWidth, panelHeight, contentWidth, contentHeight);
  232. // 根据布局模式选择布局方式
  233. if (uiLayoutConfig != null && uiLayoutConfig.isFlexMode()) {
  234. applyFlexLayout(insets, contentWidth, contentHeight);
  235. } else {
  236. applyFreeLayout(insets, contentWidth, contentHeight);
  237. }
  238. revalidate();
  239. repaint();
  240. }
  241. /**
  242. * 应用自由定位布局(Free模式)
  243. */
  244. private void applyFreeLayout(Insets insets, int contentWidth, int contentHeight) {
  245. // 应用每个组件的布局
  246. applyComponentLayout("product_sn_input", productSnInput, insets, contentWidth, contentHeight);
  247. applyComponentLayout("scan_product_btn", scanProductBtn, insets, contentWidth, contentHeight);
  248. applyComponentLayout("ok_button", okButton, insets, contentWidth, contentHeight);
  249. applyComponentLayout("ng_button", ngButton, insets, contentWidth, contentHeight);
  250. // 可选组件
  251. if (showHeader && stationLabel != null) {
  252. applyComponentLayout("station_label", stationLabel, insets, contentWidth, contentHeight);
  253. }
  254. if (showHeader && statusMenu != null) {
  255. applyComponentLayout("status_menu", statusMenu, insets, contentWidth, contentHeight);
  256. }
  257. if (showMaterialInput && materialLabelUI != null) {
  258. applyComponentLayout("material_label", materialLabelUI, insets, contentWidth, contentHeight);
  259. }
  260. if (showMaterialInput && materialSnInput != null) {
  261. applyComponentLayout("material_sn_input", materialSnInput, insets, contentWidth, contentHeight);
  262. }
  263. if (showMaterialInput && scanMaterialBtn != null) {
  264. applyComponentLayout("scan_material_btn", scanMaterialBtn, insets, contentWidth, contentHeight);
  265. }
  266. if (showMaterialInput && unbindMaterialBtn != null) {
  267. applyComponentLayout("unbind_material_btn", unbindMaterialBtn, insets, contentWidth, contentHeight);
  268. }
  269. if (showDeviceInfo && deviceInfoLabel != null) {
  270. applyComponentLayout("device_info_label", deviceInfoLabel, insets, contentWidth, contentHeight);
  271. }
  272. if (showDeviceInfo && presetCountLabel != null) {
  273. applyComponentLayout("preset_count_label", presetCountLabel, insets, contentWidth, contentHeight);
  274. }
  275. if (showDeviceInfo && presetCountField != null) {
  276. applyComponentLayout("preset_count_field", presetCountField, insets, contentWidth, contentHeight);
  277. }
  278. if (showDeviceInfo && finishedCountLabel != null) {
  279. applyComponentLayout("finished_count_label", finishedCountLabel, insets, contentWidth, contentHeight);
  280. }
  281. if (showDeviceInfo && finishedCountField != null) {
  282. applyComponentLayout("finished_count_field", finishedCountField, insets, contentWidth, contentHeight);
  283. }
  284. if (showDeviceInfo2 && deviceInfoLabel2 != null) {
  285. applyComponentLayout("device_info_label2", deviceInfoLabel2, insets, contentWidth, contentHeight);
  286. }
  287. if (showDeviceInfo2 && presetCountLabel2 != null) {
  288. applyComponentLayout("preset_count_label2", presetCountLabel2, insets, contentWidth, contentHeight);
  289. }
  290. if (showDeviceInfo2 && presetCountField2 != null) {
  291. applyComponentLayout("preset_count_field2", presetCountField2, insets, contentWidth, contentHeight);
  292. }
  293. if (showDeviceInfo2 && finishedCountLabel2 != null) {
  294. applyComponentLayout("finished_count_label2", finishedCountLabel2, insets, contentWidth, contentHeight);
  295. }
  296. if (showDeviceInfo2 && finishedCountField2 != null) {
  297. applyComponentLayout("finished_count_field2", finishedCountField2, insets, contentWidth, contentHeight);
  298. }
  299. }
  300. /**
  301. * 应用弹性行布局(Flex模式)
  302. * 行与行之间按 flex 比例分配高度
  303. * 隐藏某行时,其他行自动向中间靠拢填补空间
  304. * 组件大小保持不变,只调整 Y 坐标
  305. */
  306. private void applyFlexLayout(Insets insets, int contentWidth, int contentHeight) {
  307. boolean isSingleMode = !showHeader;
  308. List<UILayoutConfig.RowLayout> visibleRows = uiLayoutConfig.getVisibleRowsForMode(isSingleMode);
  309. if (visibleRows.isEmpty()) {
  310. log.warn("[{}] Flex布局没有可见行,回退到Free布局", stationCode);
  311. applyFreeLayout(insets, contentWidth, contentHeight);
  312. return;
  313. }
  314. // 先计算每行内组件的实际高度(从配置读取)
  315. Map<String, Integer> rowHeights = new HashMap<>();
  316. for (UILayoutConfig.RowLayout row : visibleRows) {
  317. int maxHeight = 0;
  318. for (UILayoutConfig.RowComponentLayout compLayout : row.getVisibleComponents()) {
  319. String compId = compLayout.getId();
  320. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(compId, isSingleMode);
  321. if (layout == null) layout = uiLayoutConfig.getComponent(compId);
  322. // 第二行组件回退到第一行组件布局
  323. if (layout == null && compId.endsWith("2")) {
  324. String fallbackId = compId.substring(0, compId.length() - 1);
  325. layout = uiLayoutConfig.getComponentForMode(fallbackId, isSingleMode);
  326. if (layout == null) layout = uiLayoutConfig.getComponent(fallbackId);
  327. }
  328. if (layout != null) {
  329. int h = (int)(layout.getSize().getHeight() * contentHeight);
  330. maxHeight = Math.max(maxHeight, h);
  331. }
  332. }
  333. rowHeights.put(row.getId(), Math.max(maxHeight, 50));
  334. }
  335. // 计算总高度和剩余空间
  336. int totalRowHeight = 0;
  337. for (Integer h : rowHeights.values()) {
  338. totalRowHeight += h;
  339. }
  340. // 剩余空间均匀分配给行间距
  341. int remainingSpace = contentHeight - totalRowHeight;
  342. int gapCount = visibleRows.size() + 1; // 上边距 + 行间距 + 下边距
  343. int gap = Math.max(remainingSpace / gapCount, 10);
  344. // 按顺序布局每行,均匀分布
  345. int currentY = insets.top + gap;
  346. for (UILayoutConfig.RowLayout row : visibleRows) {
  347. int rowHeight = rowHeights.get(row.getId());
  348. // 布局该行内的组件
  349. applyRowLayoutFromComponents(row, insets, contentWidth, currentY, rowHeight, isSingleMode);
  350. currentY += rowHeight + gap;
  351. }
  352. log.debug("[{}] Flex布局完成: {}行, 间距={}", stationCode, visibleRows.size(), gap);
  353. }
  354. /**
  355. * 布局单行内的组件
  356. * X 和宽度从 singleComponents/dualComponents 读取(保持编辑模式效果)
  357. * Y 坐标使用传入的行起始位置
  358. */
  359. private void applyRowLayoutFromComponents(UILayoutConfig.RowLayout row, Insets insets,
  360. int contentWidth, int rowStartY, int rowHeight, boolean isSingleMode) {
  361. List<UILayoutConfig.RowComponentLayout> rowComponents = row.getVisibleComponents();
  362. if (rowComponents.isEmpty()) return;
  363. int panelContentHeight = getHeight() - insets.top - insets.bottom;
  364. for (UILayoutConfig.RowComponentLayout compLayout : rowComponents) {
  365. String componentId = compLayout.getId();
  366. JComponent component = getComponentById(componentId);
  367. if (component == null) continue;
  368. // 从 singleComponents/dualComponents 读取组件配置
  369. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(componentId, isSingleMode);
  370. if (layout == null) {
  371. layout = uiLayoutConfig.getComponent(componentId);
  372. }
  373. // 第二行组件没有独立布局时,回退到对应的第一行组件布局
  374. if (layout == null && componentId.endsWith("2")) {
  375. String fallbackId = componentId.substring(0, componentId.length() - 1);
  376. layout = uiLayoutConfig.getComponentForMode(fallbackId, isSingleMode);
  377. if (layout == null) {
  378. layout = uiLayoutConfig.getComponent(fallbackId);
  379. }
  380. }
  381. int compX, compWidth, compHeight;
  382. if (layout != null) {
  383. // 从配置读取 X 和宽度(相对坐标转绝对坐标)
  384. compX = insets.left + (int)(layout.getPosition().getX() * contentWidth);
  385. compWidth = (int)(layout.getSize().getWidth() * contentWidth);
  386. compHeight = (int)(layout.getSize().getHeight() * panelContentHeight);
  387. } else {
  388. // 使用默认布局
  389. double[] defaultLayout = getDefaultLayout(componentId);
  390. compX = insets.left + (int)(defaultLayout[0] * contentWidth);
  391. compWidth = (int)(defaultLayout[2] * contentWidth);
  392. compHeight = (int)(defaultLayout[3] * panelContentHeight);
  393. }
  394. // 确保最小尺寸
  395. compWidth = Math.max(compWidth, 50);
  396. compHeight = Math.max(compHeight, 30);
  397. // Y 坐标:在行内垂直居中
  398. int compY = rowStartY + (rowHeight - compHeight) / 2;
  399. component.setBounds(compX, compY, compWidth, compHeight);
  400. component.setVisible(true);
  401. }
  402. }
  403. /**
  404. * 根据ID获取组件
  405. */
  406. private JComponent getComponentById(String id) {
  407. switch (id) {
  408. case "product_sn_input": return productSnInput;
  409. case "scan_product_btn": return scanProductBtn;
  410. case "ok_button": return okButton;
  411. case "ng_button": return ngButton;
  412. case "station_label": return stationLabel;
  413. case "status_menu": return statusMenu;
  414. case "material_label": return materialLabelUI;
  415. case "material_sn_input": return materialSnInput;
  416. case "scan_material_btn": return scanMaterialBtn;
  417. case "unbind_material_btn": return unbindMaterialBtn;
  418. case "preset_count_label": return presetCountLabel;
  419. case "preset_count_field": return presetCountField;
  420. case "finished_count_label": return finishedCountLabel;
  421. case "finished_count_field": return finishedCountField;
  422. case "device_info_label": return deviceInfoLabel;
  423. case "device_info_label2": return deviceInfoLabel2;
  424. case "preset_count_label2": return presetCountLabel2;
  425. case "preset_count_field2": return presetCountField2;
  426. case "finished_count_label2": return finishedCountLabel2;
  427. case "finished_count_field2": return finishedCountField2;
  428. default: return null;
  429. }
  430. }
  431. /**
  432. * 设置行可见性(运行时动态调整)
  433. * @param rowId 行ID
  434. * @param visible 是否可见
  435. */
  436. public void setRowVisible(String rowId, boolean visible) {
  437. if (uiLayoutConfig == null || !uiLayoutConfig.isFlexMode()) return;
  438. boolean isSingleMode = !showHeader;
  439. uiLayoutConfig.setRowVisibleForMode(rowId, visible, isSingleMode);
  440. // 重新应用布局
  441. if (getWidth() > 0 && getHeight() > 0) {
  442. applyRuntimeLayout();
  443. }
  444. }
  445. /**
  446. * 应用单个组件的布局
  447. */
  448. private void applyComponentLayout(String componentId, JComponent component,
  449. Insets insets, int contentWidth, int contentHeight) {
  450. if (component == null) return;
  451. // 从配置获取相对坐标
  452. double relX, relY, relW, relH;
  453. if (uiLayoutConfig != null) {
  454. // 根据模式获取组件配置 (showHeader=false 是单工位模式)
  455. boolean isSingleMode = !showHeader;
  456. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(componentId, isSingleMode);
  457. if (layout == null) {
  458. // 回退到通用配置
  459. layout = uiLayoutConfig.getComponent(componentId);
  460. }
  461. if (layout != null) {
  462. relX = layout.getPosition().getX();
  463. relY = layout.getPosition().getY();
  464. relW = layout.getSize().getWidth();
  465. relH = layout.getSize().getHeight();
  466. } else {
  467. // 使用默认布局
  468. double[] defaultLayout = getDefaultLayout(componentId);
  469. relX = defaultLayout[0];
  470. relY = defaultLayout[1];
  471. relW = defaultLayout[2];
  472. relH = defaultLayout[3];
  473. }
  474. } else {
  475. // 使用默认布局
  476. double[] defaultLayout = getDefaultLayout(componentId);
  477. relX = defaultLayout[0];
  478. relY = defaultLayout[1];
  479. relW = defaultLayout[2];
  480. relH = defaultLayout[3];
  481. }
  482. // 相对坐标转绝对坐标
  483. int x = insets.left + (int)(relX * contentWidth);
  484. int y = insets.top + (int)(relY * contentHeight);
  485. int width = (int)(relW * contentWidth);
  486. int height = (int)(relH * contentHeight);
  487. // 确保最小尺寸
  488. width = Math.max(width, 50);
  489. height = Math.max(height, 30);
  490. component.setBounds(x, y, width, height);
  491. }
  492. /**
  493. * 获取组件的默认布局
  494. */
  495. private double[] getDefaultLayout(String componentId) {
  496. switch (componentId) {
  497. case "product_sn_input":
  498. return new double[]{0.005, 0.10, 0.75, 0.18};
  499. case "scan_product_btn":
  500. return new double[]{0.76, 0.10, 0.23, 0.18};
  501. case "ok_button":
  502. return new double[]{0.15, 0.55, 0.30, 0.22};
  503. case "ng_button":
  504. return new double[]{0.55, 0.55, 0.30, 0.22};
  505. case "station_label":
  506. return new double[]{0.01, 0.02, 0.15, 0.08};
  507. case "status_menu":
  508. return new double[]{0.20, 0.02, 0.78, 0.08};
  509. case "material_label":
  510. return new double[]{0.005, 0.32, 0.10, 0.08};
  511. case "material_sn_input":
  512. return new double[]{0.12, 0.32, 0.50, 0.12};
  513. case "scan_material_btn":
  514. return new double[]{0.63, 0.32, 0.17, 0.12};
  515. case "unbind_material_btn":
  516. return new double[]{0.81, 0.32, 0.17, 0.12};
  517. case "preset_count_label":
  518. return new double[]{0.10, 0.75, 0.35, 0.08};
  519. case "preset_count_field":
  520. return new double[]{0.10, 0.83, 0.35, 0.10};
  521. case "finished_count_label":
  522. return new double[]{0.55, 0.75, 0.35, 0.08};
  523. case "finished_count_field":
  524. return new double[]{0.55, 0.83, 0.35, 0.10};
  525. default:
  526. return new double[]{0.0, 0.0, 0.1, 0.1};
  527. }
  528. }
  529. /**
  530. * 根据面板大小更新缩放比例
  531. */
  532. private void updateScale() {
  533. int width = getWidth();
  534. int height = getHeight();
  535. if (width <= 0 || height <= 0) return;
  536. // 计算缩放比例(取宽高中较小的缩放比)
  537. double scaleX = (double) width / BASE_WIDTH;
  538. double scaleY = (double) height / BASE_HEIGHT;
  539. double newScale = Math.min(scaleX, scaleY);
  540. // 限制缩放范围
  541. newScale = Math.max(0.8, Math.min(2.0, newScale));
  542. if (Math.abs(newScale - currentScale) > 0.05) {
  543. currentScale = newScale;
  544. applyScale();
  545. }
  546. }
  547. /**
  548. * 应用缩放到所有组件
  549. */
  550. private void applyScale() {
  551. // 计算缩放后的字体大小和尺寸,设置较小的最小值
  552. int productFontSize = Math.max(14, (int) (28 * currentScale));
  553. int normalFontSize = Math.max(12, (int) (20 * currentScale));
  554. int buttonFontSize = Math.max(10, (int) (32 * currentScale));
  555. int productHeight = (int) (70 * currentScale);
  556. int materialHeight = (int) (50 * currentScale);
  557. int deviceHeight = (int) (40 * currentScale);
  558. int buttonHeight = (int) (80 * currentScale);
  559. int statusHeight = Math.max(30, (int) (40 * currentScale));
  560. // 更新工位标签和状态栏(双工位时)
  561. if (showHeader && stationLabel != null) {
  562. stationLabel.setFont(new Font("微软雅黑", Font.PLAIN, normalFontSize));
  563. }
  564. if (showHeader && statusMenu != null) {
  565. statusMenu.setFont(new Font("微软雅黑", Font.PLAIN, normalFontSize));
  566. statusMenu.setPreferredSize(new Dimension((int)(400 * currentScale), statusHeight));
  567. }
  568. // 更新工件码输入框
  569. productSnInput.setFont(new Font("微软雅黑", Font.PLAIN, productFontSize));
  570. productSnInput.setPreferredSize(new Dimension((int)(602 * currentScale), productHeight));
  571. // 更新扫码按钮
  572. scanProductBtn.setFont(new Font("微软雅黑", Font.PLAIN, buttonFontSize));
  573. scanProductBtn.setPreferredSize(new Dimension((int)(198 * currentScale), productHeight));
  574. // 更新物料码区域 - 只设置高度,宽度由GridBagLayout控制
  575. if (materialSnInput != null) {
  576. materialSnInput.setFont(new Font("微软雅黑", Font.PLAIN, normalFontSize));
  577. // 不设置固定宽度,让weightx控制
  578. }
  579. if (scanMaterialBtn != null) {
  580. scanMaterialBtn.setPreferredSize(new Dimension((int)(50 * currentScale), materialHeight));
  581. }
  582. if (unbindMaterialBtn != null) {
  583. unbindMaterialBtn.setPreferredSize(new Dimension((int)(50 * currentScale), materialHeight));
  584. }
  585. // 更新设备信息
  586. if (presetCountField != null) {
  587. presetCountField.setFont(new Font("微软雅黑", Font.PLAIN, normalFontSize));
  588. presetCountField.setPreferredSize(new Dimension((int)(150 * currentScale), deviceHeight));
  589. }
  590. if (finishedCountField != null) {
  591. finishedCountField.setFont(new Font("微软雅黑", Font.PLAIN, normalFontSize));
  592. finishedCountField.setPreferredSize(new Dimension((int)(150 * currentScale), deviceHeight));
  593. }
  594. // 更新OK/NG按钮 - 图标大小根据缩放比例调整
  595. int iconSize = Math.max(16, (int)(32 * currentScale));
  596. okButton.setIcon(new ImageIcon(okIconImage.getScaledInstance(iconSize, iconSize, Image.SCALE_SMOOTH)));
  597. okButton.setFont(new Font("微软雅黑", Font.PLAIN, buttonFontSize));
  598. ngButton.setIcon(new ImageIcon(ngIconImage.getScaledInstance(iconSize, iconSize, Image.SCALE_SMOOTH)));
  599. ngButton.setFont(new Font("微软雅黑", Font.PLAIN, buttonFontSize));
  600. // 更新按钮面板大小
  601. Container buttonPanel = okButton.getParent();
  602. if (buttonPanel != null) {
  603. buttonPanel.setPreferredSize(new Dimension((int)(600 * currentScale), buttonHeight));
  604. }
  605. // 刷新布局
  606. revalidate();
  607. repaint();
  608. }
  609. // ========== 事件处理 ==========
  610. /**
  611. * 弹出工件码扫码对话框(供外部调用)
  612. */
  613. public void requestScan() {
  614. javax.swing.SwingUtilities.invokeLater(this::onScanProductClick);
  615. }
  616. /**
  617. * 弹出物料码扫码对话框(供外部调用)
  618. */
  619. public void requestMaterialScan() {
  620. javax.swing.SwingUtilities.invokeLater(this::onScanMaterialClick);
  621. }
  622. private void onScanProductClick() {
  623. // 防重入保护:如果对话框已经在显示,直接返回
  624. if (isScanDialogShowing) {
  625. log.warn("[{}] 扫码对话框已在显示中,忽略重复调用", stationCode);
  626. return;
  627. }
  628. try {
  629. isScanDialogShowing = true;
  630. log.info("[{}] 点击扫码按钮", stationCode);
  631. String sn = JOptionPane.showInputDialog(null, "请扫描工件二维码", "扫描工件码", JOptionPane.PLAIN_MESSAGE);
  632. if (sn != null && !sn.trim().isEmpty()) {
  633. productSnInput.setText(sn.trim());
  634. if (listener != null) {
  635. listener.onProductScanned(this, sn.trim());
  636. }
  637. }
  638. } finally {
  639. // 确保标志位被重置
  640. isScanDialogShowing = false;
  641. }
  642. }
  643. private void onScanMaterialClick() {
  644. // 防重入保护:如果对话框已经在显示,直接返回
  645. if (isMaterialScanDialogShowing) {
  646. log.warn("[{}] {}扫码对话框已在显示中,忽略重复调用", stationCode, materialLabel);
  647. return;
  648. }
  649. try {
  650. isMaterialScanDialogShowing = true;
  651. log.info("[{}] 点击{}扫码按钮", stationCode, materialLabel);
  652. String sn = JOptionPane.showInputDialog(null, "请扫描" + materialLabel + "二维码", "扫描" + materialLabel, JOptionPane.PLAIN_MESSAGE);
  653. if (sn != null && !sn.trim().isEmpty()) {
  654. materialSnInput.setText(sn.trim());
  655. if (listener != null) {
  656. listener.onMaterialScanned(this, sn.trim());
  657. }
  658. }
  659. } finally {
  660. // 确保标志位被重置
  661. isMaterialScanDialogShowing = false;
  662. }
  663. }
  664. private void onOkClick() {
  665. log.info("[{}] 点击OK", stationCode);
  666. if (listener != null) {
  667. listener.onOkClicked(this);
  668. }
  669. }
  670. private void onNgClick() {
  671. log.info("[{}] 点击NG", stationCode);
  672. if (listener != null) {
  673. listener.onNgClicked(this);
  674. }
  675. }
  676. private void onUnbindClick() {
  677. log.info("[{}] 点击解绑", stationCode);
  678. if (listener != null) {
  679. listener.onUnbindClicked(this);
  680. }
  681. }
  682. // ========== 公共方法 ==========
  683. /**
  684. * 更新状态显示
  685. */
  686. public void updateStatus(String message, int level) {
  687. if (statusMenu == null) return; // 单工位时statusMenu可能为null
  688. statusMenu.setText(message);
  689. switch (level) {
  690. case 0: // 正常
  691. statusMenu.setForeground(Color.GREEN);
  692. break;
  693. case 1: // 警告
  694. statusMenu.setForeground(Color.GREEN);
  695. break;
  696. case -1: // 错误
  697. statusMenu.setForeground(Color.RED);
  698. break;
  699. default:
  700. statusMenu.setForeground(Color.GREEN);
  701. }
  702. }
  703. /**
  704. * 获取状态菜单(供外部更新状态)
  705. */
  706. public JButton getStatusMenu() {
  707. return statusMenu;
  708. }
  709. /**
  710. * 设置外部状态组件(单工位时使用工具栏状态)
  711. */
  712. public void setExternalStatusMenu(JButton externalStatus) {
  713. this.statusMenu = externalStatus;
  714. this.externalStatusMenu = externalStatus; // 保存外部引用,编辑模式切换后恢复
  715. }
  716. /**
  717. * 从上下文刷新UI
  718. */
  719. public void refresh(StationContext context) {
  720. if (context == null) return;
  721. // 更新工件码
  722. productSnInput.setText(context.getProductSn() != null ? context.getProductSn() : "");
  723. // 更新物料码
  724. if (materialSnInput != null) {
  725. materialSnInput.setText(context.getMaterialSn() != null ? context.getMaterialSn() : "");
  726. }
  727. // 更新设备信息
  728. if (showDeviceInfo && presetCountField != null) {
  729. presetCountField.setText(String.valueOf(context.getPresetCount()));
  730. finishedCountField.setText(String.valueOf(context.getFinishedCount()));
  731. }
  732. if (showDeviceInfo2 && presetCountField2 != null) {
  733. // 检查第二行设备连接状态
  734. if (context.getPresetCount2() < 0 || context.getFinishedCount2() < 0) {
  735. // 设备未连接,显示"--"
  736. presetCountField2.setText("--");
  737. finishedCountField2.setText("--");
  738. } else {
  739. // 设备已连接,显示数值
  740. presetCountField2.setText(String.valueOf(context.getPresetCount2()));
  741. finishedCountField2.setText(String.valueOf(context.getFinishedCount2()));
  742. }
  743. }
  744. // 更新按钮状态
  745. // 手动模式:等待用户操作时启用OK/NG按钮
  746. // 自动模式:始终禁用,由流程自动提交
  747. boolean canSubmit;
  748. if (StationConfig.getInstance().isAutoSubmitMode()) {
  749. // 自动模式:始终禁用
  750. canSubmit = false;
  751. } else if (context.isWaitingForUserAction()) {
  752. // 手动模式:等待用户点击OK/NG
  753. canSubmit = context.isQualityPassed() && !context.isResultUploaded();
  754. } else {
  755. canSubmit = false;
  756. }
  757. // 手动提交菜单启用标志:无视模式强制亮起 OK/NG
  758. Boolean forceSubmit = context.getExtra("forceSubmitEnabled", Boolean.FALSE);
  759. if (Boolean.TRUE.equals(forceSubmit) && !context.isResultUploaded()) {
  760. canSubmit = true;
  761. }
  762. okButton.setEnabled(canSubmit);
  763. ngButton.setEnabled(canSubmit);
  764. // 更新物料扫码状态
  765. if (scanMaterialBtn != null) {
  766. boolean canScanMaterial = context.isQualityPassed() && !context.isMaterialValidated();
  767. scanMaterialBtn.setEnabled(canScanMaterial);
  768. if (unbindMaterialBtn != null) {
  769. unbindMaterialBtn.setEnabled(context.isMaterialBound());
  770. }
  771. }
  772. // 更新状态消息
  773. updateStatus(context.getStatusMessage(), context.getStatusLevel());
  774. }
  775. /**
  776. * 重置面板
  777. */
  778. public void reset() {
  779. productSnInput.setText("");
  780. if (materialSnInput != null) {
  781. materialSnInput.setText("");
  782. }
  783. if (scanMaterialBtn != null) {
  784. scanMaterialBtn.setEnabled(false);
  785. }
  786. if (unbindMaterialBtn != null) {
  787. unbindMaterialBtn.setEnabled(false);
  788. }
  789. okButton.setEnabled(false);
  790. ngButton.setEnabled(false);
  791. if (presetCountField != null) {
  792. presetCountField.setText("0");
  793. }
  794. if (finishedCountField != null) {
  795. finishedCountField.setText("0");
  796. }
  797. if (presetCountField2 != null) {
  798. presetCountField2.setText("0");
  799. }
  800. if (finishedCountField2 != null) {
  801. finishedCountField2.setText("0");
  802. }
  803. updateStatus("等待加工信号", 0);
  804. }
  805. // ========== Getters & Setters ==========
  806. public String getStationCode() {
  807. return stationCode;
  808. }
  809. /**
  810. * 运行时更新工位号(修改工位号菜单使用)
  811. * 会同步刷新 stationLabel 显示
  812. */
  813. public void updateStationCode(String newCode) {
  814. if (newCode == null || newCode.equals(this.stationCode)) return;
  815. this.stationCode = newCode;
  816. this.stationName = newCode;
  817. if (stationLabel != null) {
  818. stationLabel.setText(newCode);
  819. }
  820. }
  821. /**
  822. * 运行时更新物料码标签(冷板码 ↔ 底护板码切换时调用)
  823. */
  824. public void updateMaterialLabel(String newLabel) {
  825. if (newLabel == null || newLabel.isEmpty()) return;
  826. this.materialLabel = newLabel;
  827. if (materialLabelUI != null) {
  828. materialLabelUI.setText(newLabel + ":");
  829. }
  830. }
  831. /**
  832. * 重新从 StationConfig 读取 showDeviceInfo/showMaterialInput/label 等显示选项
  833. * 用于"设备信息显示""工艺流程配置"菜单改动后的热刷新
  834. */
  835. public void refreshDisplayFromConfig(StationConfig cfg) {
  836. if (cfg == null) return;
  837. this.showDeviceInfo = cfg.isShowDeviceInfo();
  838. this.showDeviceInfo2 = cfg.isShowDeviceInfo2();
  839. this.showMaterialInput = cfg.isEffectiveShowMaterialInput();
  840. String effLabel = cfg.getEffectiveMaterialLabel();
  841. if (effLabel != null && !effLabel.isEmpty()) {
  842. this.materialLabel = effLabel;
  843. }
  844. // 物料码相关组件:按 showMaterialInput 直接控制可见性
  845. if (materialLabelUI != null) materialLabelUI.setVisible(showMaterialInput);
  846. if (materialSnInput != null) materialSnInput.setVisible(showMaterialInput);
  847. if (scanMaterialBtn != null) scanMaterialBtn.setVisible(showMaterialInput);
  848. if (unbindMaterialBtn != null) unbindMaterialBtn.setVisible(showMaterialInput);
  849. if (showMaterialInput && materialLabelUI != null) {
  850. materialLabelUI.setText(this.materialLabel + ":");
  851. }
  852. // 设备信息第1行
  853. StationConfig.DeviceInfoRow row0 = cfg.getDeviceInfoRow(0);
  854. if (deviceInfoLabel != null) {
  855. if (row0 != null && row0.hasLabel()) {
  856. deviceInfoLabel.setText(row0.getLabel());
  857. deviceInfoLabel.setVisible(showDeviceInfo);
  858. } else {
  859. deviceInfoLabel.setVisible(false);
  860. }
  861. }
  862. if (presetCountLabel != null) presetCountLabel.setVisible(showDeviceInfo);
  863. if (presetCountField != null) presetCountField.setVisible(showDeviceInfo);
  864. if (finishedCountLabel != null) finishedCountLabel.setVisible(showDeviceInfo);
  865. if (finishedCountField != null) finishedCountField.setVisible(showDeviceInfo);
  866. // 设备信息第2行
  867. StationConfig.DeviceInfoRow row1 = cfg.getDeviceInfoRow(1);
  868. if (deviceInfoLabel2 != null) {
  869. if (row1 != null && row1.hasLabel()) {
  870. deviceInfoLabel2.setText(row1.getLabel());
  871. deviceInfoLabel2.setVisible(showDeviceInfo2);
  872. } else {
  873. deviceInfoLabel2.setVisible(false);
  874. }
  875. }
  876. if (presetCountLabel2 != null) presetCountLabel2.setVisible(showDeviceInfo2);
  877. if (presetCountField2 != null) presetCountField2.setVisible(showDeviceInfo2);
  878. if (finishedCountLabel2 != null) finishedCountLabel2.setVisible(showDeviceInfo2);
  879. if (finishedCountField2 != null) finishedCountField2.setVisible(showDeviceInfo2);
  880. revalidate();
  881. repaint();
  882. }
  883. public String getStationName() {
  884. return stationName;
  885. }
  886. public int getStationIndex() {
  887. return stationIndex;
  888. }
  889. public String getProductSn() {
  890. return productSnInput.getText().trim();
  891. }
  892. public void setProductSn(String sn) {
  893. productSnInput.setText(sn);
  894. }
  895. public String getMaterialSn() {
  896. return materialSnInput != null ? materialSnInput.getText().trim() : null;
  897. }
  898. public void setMaterialSn(String sn) {
  899. if (materialSnInput != null) {
  900. materialSnInput.setText(sn);
  901. }
  902. }
  903. public WorkstationPanelListener getListener() {
  904. return listener;
  905. }
  906. public void setListener(WorkstationPanelListener listener) {
  907. this.listener = listener;
  908. }
  909. public void setOkButtonEnabled(boolean enabled) {
  910. okButton.setEnabled(enabled);
  911. }
  912. public void setNgButtonEnabled(boolean enabled) {
  913. ngButton.setEnabled(enabled);
  914. }
  915. public void setMaterialInputEnabled(boolean enabled) {
  916. if (scanMaterialBtn != null) {
  917. scanMaterialBtn.setEnabled(enabled);
  918. }
  919. }
  920. // ========== 编辑模式相关方法 ==========
  921. /**
  922. * 切换编辑模式
  923. */
  924. public void setEditMode(boolean editMode) {
  925. if (this.editMode == editMode) return;
  926. // 保存当前面板大小
  927. if (editMode) {
  928. capturedPanelSize = new Dimension(getWidth(), getHeight());
  929. }
  930. this.editMode = editMode;
  931. // 清理当前状态
  932. cleanupCurrentMode();
  933. // 移除所有组件
  934. removeAll();
  935. // 重新初始化UI
  936. if (editMode) {
  937. initEditModeUI();
  938. } else {
  939. initRuntimeUI();
  940. }
  941. revalidate();
  942. repaint();
  943. log.info("[{}] 切换到{}模式", stationCode, editMode ? "编辑" : "运行");
  944. }
  945. /**
  946. * 捕获当前运行模式下的组件布局
  947. */
  948. private Map<String, Rectangle> captureCurrentLayout() {
  949. Map<String, Rectangle> bounds = new HashMap<>();
  950. // 保存当前面板大小(用于编辑模式)
  951. capturedPanelSize = new Dimension(getWidth(), getHeight());
  952. // 获取内容区域大小
  953. Insets insets = getInsets();
  954. int contentWidth = getWidth() - insets.left - insets.right;
  955. int contentHeight = getHeight() - insets.top - insets.bottom;
  956. log.info("[{}] 捕获面板大小: {}x{}, 内容区域: {}x{}, insets: top={},left={},bottom={},right={}",
  957. stationCode, getWidth(), getHeight(), contentWidth, contentHeight,
  958. insets.top, insets.left, insets.bottom, insets.right);
  959. if (contentWidth <= 0 || contentHeight <= 0) {
  960. return bounds;
  961. }
  962. // 捕获各组件的相对位置
  963. if (productSnInput != null && productSnInput.isVisible()) {
  964. bounds.put("product_sn_input", getRelativeBounds(productSnInput, insets, contentWidth, contentHeight));
  965. }
  966. if (scanProductBtn != null && scanProductBtn.isVisible()) {
  967. bounds.put("scan_product_btn", getRelativeBounds(scanProductBtn, insets, contentWidth, contentHeight));
  968. }
  969. if (okButton != null && okButton.isVisible()) {
  970. // OK按钮可能在buttonPanel中
  971. Container parent = okButton.getParent();
  972. if (parent != null && parent != this) {
  973. // 计算相对于面板的位置
  974. Point loc = SwingUtilities.convertPoint(parent, okButton.getLocation(), this);
  975. int x = loc.x - insets.left;
  976. int y = loc.y - insets.top;
  977. bounds.put("ok_button", new Rectangle(
  978. (int)((double)x / contentWidth * 1000),
  979. (int)((double)y / contentHeight * 1000),
  980. (int)((double)okButton.getWidth() / contentWidth * 1000),
  981. (int)((double)okButton.getHeight() / contentHeight * 1000)
  982. ));
  983. } else {
  984. bounds.put("ok_button", getRelativeBounds(okButton, insets, contentWidth, contentHeight));
  985. }
  986. }
  987. if (ngButton != null && ngButton.isVisible()) {
  988. Container parent = ngButton.getParent();
  989. if (parent != null && parent != this) {
  990. Point loc = SwingUtilities.convertPoint(parent, ngButton.getLocation(), this);
  991. int x = loc.x - insets.left;
  992. int y = loc.y - insets.top;
  993. bounds.put("ng_button", new Rectangle(
  994. (int)((double)x / contentWidth * 1000),
  995. (int)((double)y / contentHeight * 1000),
  996. (int)((double)ngButton.getWidth() / contentWidth * 1000),
  997. (int)((double)ngButton.getHeight() / contentHeight * 1000)
  998. ));
  999. } else {
  1000. bounds.put("ng_button", getRelativeBounds(ngButton, insets, contentWidth, contentHeight));
  1001. }
  1002. }
  1003. log.info("[{}] 捕获运行模式布局: {}", stationCode, bounds);
  1004. return bounds;
  1005. }
  1006. /**
  1007. * 获取组件相对于内容区域的边界(放大1000倍以保留精度)
  1008. */
  1009. private Rectangle getRelativeBounds(JComponent comp, Insets insets, int contentWidth, int contentHeight) {
  1010. int x = comp.getX() - insets.left;
  1011. int y = comp.getY() - insets.top;
  1012. return new Rectangle(
  1013. (int)((double)x / contentWidth * 1000),
  1014. (int)((double)y / contentHeight * 1000),
  1015. (int)((double)comp.getWidth() / contentWidth * 1000),
  1016. (int)((double)comp.getHeight() / contentHeight * 1000)
  1017. );
  1018. }
  1019. /**
  1020. * 清理当前模式的资源
  1021. */
  1022. private void cleanupCurrentMode() {
  1023. // 移除旧的监听器
  1024. if (resizeListener != null) {
  1025. removeComponentListener(resizeListener);
  1026. resizeListener = null;
  1027. }
  1028. // 清理组件包装器
  1029. if (componentWrappers != null) {
  1030. for (DraggableComponentWrapper wrapper : componentWrappers.values()) {
  1031. wrapper.setEditMode(false);
  1032. }
  1033. componentWrappers.clear();
  1034. }
  1035. // 清理网格叠加层
  1036. gridOverlay = null;
  1037. // 注意:不清除 preferredSize 和 capturedPanelSize
  1038. // 保持面板尺寸一致,避免布局跳动
  1039. // 重置组件引用(强制重新创建)
  1040. productSnInput = null;
  1041. scanProductBtn = null;
  1042. materialLabelUI = null;
  1043. materialSnInput = null;
  1044. scanMaterialBtn = null;
  1045. unbindMaterialBtn = null;
  1046. presetCountLabel = null;
  1047. presetCountField = null;
  1048. finishedCountLabel = null;
  1049. finishedCountField = null;
  1050. deviceInfoLabel = null;
  1051. presetCountLabel2 = null;
  1052. presetCountField2 = null;
  1053. finishedCountLabel2 = null;
  1054. finishedCountField2 = null;
  1055. deviceInfoLabel2 = null;
  1056. okButton = null;
  1057. ngButton = null;
  1058. statusMenu = null;
  1059. stationLabel = null;
  1060. }
  1061. /**
  1062. * 初始化运行模式UI - 使用绝对定位 + 相对坐标,支持窗口缩放
  1063. * 运行模式和编辑模式使用相同的布局逻辑,保证一致性
  1064. */
  1065. private void initRuntimeUI() {
  1066. log.info("[{}] 运行模式使用绝对定位", stationCode);
  1067. // 保持面板大小(从编辑模式切换回来时)
  1068. if (capturedPanelSize != null) {
  1069. setPreferredSize(capturedPanelSize);
  1070. setMinimumSize(capturedPanelSize);
  1071. }
  1072. // 先确保所有组件已创建(统一入口)
  1073. ensureComponentsCreated();
  1074. // 恢复外部状态组件引用(单工位模式)
  1075. if (!showHeader && externalStatusMenu != null) {
  1076. statusMenu = externalStatusMenu;
  1077. log.debug("[{}] 恢复外部状态组件引用", stationCode);
  1078. }
  1079. // 使用绝对定位
  1080. setLayout(null);
  1081. // 设置边框
  1082. if (showHeader) {
  1083. setBorder(BorderFactory.createCompoundBorder(
  1084. BorderFactory.createEtchedBorder(),
  1085. BorderFactory.createEmptyBorder(10, 10, 10, 10)
  1086. ));
  1087. } else {
  1088. setBorder(BorderFactory.createEmptyBorder(40, 10, 10, 10));
  1089. }
  1090. // 加载布局配置
  1091. loadLayoutConfig();
  1092. // 添加组件到面板(不使用嵌套容器)
  1093. add(productSnInput);
  1094. add(scanProductBtn);
  1095. add(okButton);
  1096. add(ngButton);
  1097. // 可选组件
  1098. if (showHeader) {
  1099. add(stationLabel);
  1100. add(statusMenu);
  1101. }
  1102. if (showMaterialInput) {
  1103. add(materialLabelUI);
  1104. add(materialSnInput);
  1105. add(scanMaterialBtn);
  1106. add(unbindMaterialBtn);
  1107. }
  1108. if (showDeviceInfo) {
  1109. if (deviceInfoLabel != null) {
  1110. add(deviceInfoLabel);
  1111. }
  1112. add(presetCountLabel);
  1113. add(presetCountField);
  1114. add(finishedCountLabel);
  1115. add(finishedCountField);
  1116. }
  1117. if (showDeviceInfo2) {
  1118. if (deviceInfoLabel2 != null) {
  1119. add(deviceInfoLabel2);
  1120. }
  1121. add(presetCountLabel2);
  1122. add(presetCountField2);
  1123. add(finishedCountLabel2);
  1124. add(finishedCountField2);
  1125. }
  1126. // 添加窗口大小变化监听器,实现按比例缩放
  1127. resizeListener = new ComponentAdapter() {
  1128. @Override
  1129. public void componentResized(ComponentEvent e) {
  1130. if (!editMode) {
  1131. applyRuntimeLayout();
  1132. }
  1133. }
  1134. };
  1135. addComponentListener(resizeListener);
  1136. // 确保面板显示后再应用布局
  1137. addHierarchyListener(e -> {
  1138. if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0
  1139. && isShowing() && !editMode) {
  1140. SwingUtilities.invokeLater(this::applyRuntimeLayout);
  1141. }
  1142. });
  1143. // 初始应用布局(如果面板已有尺寸)
  1144. if (getWidth() > 0 && getHeight() > 0) {
  1145. applyRuntimeLayout();
  1146. }
  1147. }
  1148. /**
  1149. * 初始化自定义布局UI(运行模式使用编辑器保存的配置)
  1150. * 注意:此方法已被 initCustomRuntimeUI() 替代,保留以备后用
  1151. */
  1152. private void initCustomLayoutUI() {
  1153. setLayout(null);
  1154. // 单工位不显示外边框,双工位显示边框
  1155. if (showHeader) {
  1156. setBorder(BorderFactory.createCompoundBorder(
  1157. BorderFactory.createEtchedBorder(),
  1158. BorderFactory.createEmptyBorder(10, 10, 10, 10)
  1159. ));
  1160. } else {
  1161. setBorder(BorderFactory.createEmptyBorder(40, 10, 10, 10));
  1162. }
  1163. // 确保组件已创建(统一入口)
  1164. ensureComponentsCreated();
  1165. // 添加组件到面板
  1166. add(productSnInput);
  1167. add(scanProductBtn);
  1168. if (showMaterialInput) {
  1169. add(materialLabelUI);
  1170. add(materialSnInput);
  1171. add(scanMaterialBtn);
  1172. add(unbindMaterialBtn);
  1173. }
  1174. if (showDeviceInfo) {
  1175. if (deviceInfoLabel != null) {
  1176. add(deviceInfoLabel);
  1177. }
  1178. add(presetCountLabel);
  1179. add(presetCountField);
  1180. add(finishedCountLabel);
  1181. add(finishedCountField);
  1182. }
  1183. if (showDeviceInfo2) {
  1184. if (deviceInfoLabel2 != null) {
  1185. add(deviceInfoLabel2);
  1186. }
  1187. add(presetCountLabel2);
  1188. add(presetCountField2);
  1189. add(finishedCountLabel2);
  1190. add(finishedCountField2);
  1191. }
  1192. add(okButton);
  1193. add(ngButton);
  1194. // 添加尺寸变化监听器,应用自定义布局
  1195. addComponentListener(new ComponentAdapter() {
  1196. @Override
  1197. public void componentResized(ComponentEvent e) {
  1198. if (!editMode) {
  1199. applyCustomLayout();
  1200. }
  1201. }
  1202. });
  1203. // 立即应用布局
  1204. applyCustomLayout();
  1205. }
  1206. /**
  1207. * 应用自定义布局配置(运行模式)
  1208. */
  1209. private void applyCustomLayout() {
  1210. if (uiLayoutConfig == null) return;
  1211. int panelWidth = getWidth();
  1212. int panelHeight = getHeight();
  1213. if (panelWidth == 0 || panelHeight == 0) {
  1214. // 使用基准尺寸
  1215. panelWidth = uiLayoutConfig.getGlobalSettings().getBaseWidth();
  1216. panelHeight = uiLayoutConfig.getGlobalSettings().getBaseHeight();
  1217. }
  1218. // 应用配置到各个组件
  1219. applyLayoutToComponent(productSnInput, "product_sn_input", panelWidth, panelHeight);
  1220. applyLayoutToComponent(scanProductBtn, "scan_product_btn", panelWidth, panelHeight);
  1221. if (showMaterialInput) {
  1222. applyLayoutToComponent(materialLabelUI, "material_label", panelWidth, panelHeight);
  1223. applyLayoutToComponent(materialSnInput, "material_sn_input", panelWidth, panelHeight);
  1224. applyLayoutToComponent(scanMaterialBtn, "scan_material_btn", panelWidth, panelHeight);
  1225. applyLayoutToComponent(unbindMaterialBtn, "unbind_material_btn", panelWidth, panelHeight);
  1226. }
  1227. if (showDeviceInfo) {
  1228. if (deviceInfoLabel != null) {
  1229. applyLayoutToComponent(deviceInfoLabel, "device_info_label", panelWidth, panelHeight);
  1230. }
  1231. applyLayoutToComponent(presetCountLabel, "preset_count_label", panelWidth, panelHeight);
  1232. applyLayoutToComponent(presetCountField, "preset_count_field", panelWidth, panelHeight);
  1233. applyLayoutToComponent(finishedCountLabel, "finished_count_label", panelWidth, panelHeight);
  1234. applyLayoutToComponent(finishedCountField, "finished_count_field", panelWidth, panelHeight);
  1235. }
  1236. if (showDeviceInfo2) {
  1237. if (deviceInfoLabel2 != null) {
  1238. applyLayoutToComponent(deviceInfoLabel2, "device_info_label2", panelWidth, panelHeight);
  1239. }
  1240. applyLayoutToComponent(presetCountLabel2, "preset_count_label2", panelWidth, panelHeight);
  1241. applyLayoutToComponent(presetCountField2, "preset_count_field2", panelWidth, panelHeight);
  1242. applyLayoutToComponent(finishedCountLabel2, "finished_count_label2", panelWidth, panelHeight);
  1243. applyLayoutToComponent(finishedCountField2, "finished_count_field2", panelWidth, panelHeight);
  1244. }
  1245. applyLayoutToComponent(okButton, "ok_button", panelWidth, panelHeight);
  1246. applyLayoutToComponent(ngButton, "ng_button", panelWidth, panelHeight);
  1247. }
  1248. /**
  1249. * 应用布局配置到单个组件
  1250. */
  1251. private void applyLayoutToComponent(JComponent component, String componentId, int panelWidth, int panelHeight) {
  1252. if (component == null) return;
  1253. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponent(componentId);
  1254. if (layout == null || !layout.isVisible()) {
  1255. component.setVisible(false);
  1256. return;
  1257. }
  1258. // 计算绝对位置和尺寸
  1259. int x = (int)(layout.getPosition().getX() * panelWidth);
  1260. int y = (int)(layout.getPosition().getY() * panelHeight);
  1261. int width = (int)(layout.getSize().getWidth() * panelWidth);
  1262. int height = (int)(layout.getSize().getHeight() * panelHeight);
  1263. // 应用最小尺寸限制
  1264. width = Math.max(width, layout.getSize().getMinWidth());
  1265. height = Math.max(height, layout.getSize().getMinHeight());
  1266. // 应用最大尺寸限制
  1267. width = Math.min(width, layout.getSize().getMaxWidth());
  1268. height = Math.min(height, layout.getSize().getMaxHeight());
  1269. // 设置组件位置和大小
  1270. component.setBounds(x, y, width, height);
  1271. component.setVisible(layout.isVisible());
  1272. // 应用样式配置
  1273. UILayoutConfig.Style style = layout.getStyle();
  1274. if (style != null) {
  1275. // 应用字体
  1276. Font currentFont = component.getFont();
  1277. Font newFont = new Font(
  1278. style.getFontName(),
  1279. style.getFontStyle(),
  1280. style.getFontSize()
  1281. );
  1282. component.setFont(newFont);
  1283. // 应用颜色(如果组件支持)
  1284. try {
  1285. if (style.getForeground() != null) {
  1286. component.setForeground(Color.decode(style.getForeground()));
  1287. }
  1288. if (style.getBackground() != null && component.isOpaque()) {
  1289. component.setBackground(Color.decode(style.getBackground()));
  1290. }
  1291. } catch (NumberFormatException e) {
  1292. log.warn("颜色格式错误: {}", e.getMessage());
  1293. }
  1294. }
  1295. }
  1296. /**
  1297. * 使用自定义布局初始化运行模式UI
  1298. */
  1299. private void initCustomRuntimeUI() {
  1300. setLayout(null);
  1301. // 设置边框(和默认运行模式一致)
  1302. if (showHeader) {
  1303. setBorder(BorderFactory.createCompoundBorder(
  1304. BorderFactory.createEtchedBorder(),
  1305. BorderFactory.createEmptyBorder(10, 10, 10, 10)
  1306. ));
  1307. } else {
  1308. setBorder(BorderFactory.createEmptyBorder(40, 10, 10, 10));
  1309. }
  1310. // 确保组件已创建
  1311. ensureComponentsCreated();
  1312. // 等待面板大小确定后应用布局
  1313. SwingUtilities.invokeLater(() -> {
  1314. applyLayoutConfigToRuntime();
  1315. });
  1316. }
  1317. /**
  1318. * 确保所有组件已创建(统一的组件创建入口)
  1319. * 所有组件的样式在这里统一定义,其他地方只做布局
  1320. */
  1321. private void ensureComponentsCreated() {
  1322. // === 工件码输入框 ===
  1323. if (productSnInput == null) {
  1324. productSnInput = new JTextField();
  1325. productSnInput.setHorizontalAlignment(SwingConstants.CENTER);
  1326. productSnInput.setEditable(false);
  1327. productSnInput.setFont(new Font("微软雅黑", Font.PLAIN, 28));
  1328. productSnInput.setPreferredSize(new Dimension(640, 70));
  1329. }
  1330. // === 扫码按钮 ===
  1331. if (scanProductBtn == null) {
  1332. scanProductBtn = new JButton("扫码");
  1333. scanProductBtn.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/resources/image/bg/scan_barcode.png"))));
  1334. scanProductBtn.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1335. scanProductBtn.setPreferredSize(new Dimension(160, 70));
  1336. scanProductBtn.addActionListener(e -> onScanProductClick());
  1337. }
  1338. // === OK按钮 ===
  1339. if (okButton == null) {
  1340. okIconImage = new ImageIcon(Objects.requireNonNull(getClass().getResource("/resources/image/bg/ok_bg.png"))).getImage();
  1341. okButton = new JButton("OK");
  1342. okButton.setIcon(new ImageIcon(okIconImage.getScaledInstance(24, 24, Image.SCALE_SMOOTH)));
  1343. okButton.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1344. okButton.setEnabled(false);
  1345. okButton.addActionListener(e -> onOkClick());
  1346. }
  1347. // === NG按钮 ===
  1348. if (ngButton == null) {
  1349. ngIconImage = new ImageIcon(Objects.requireNonNull(getClass().getResource("/resources/image/bg/ng_bg.png"))).getImage();
  1350. ngButton = new JButton("NG");
  1351. ngButton.setIcon(new ImageIcon(ngIconImage.getScaledInstance(24, 24, Image.SCALE_SMOOTH)));
  1352. ngButton.setFont(new Font("微软雅黑", Font.PLAIN, 32));
  1353. ngButton.setEnabled(false);
  1354. ngButton.addActionListener(e -> onNgClick());
  1355. }
  1356. // === 物料码标签(可选)===
  1357. if (showMaterialInput && materialLabelUI == null) {
  1358. materialLabelUI = new JLabel(this.materialLabel + ":");
  1359. materialLabelUI.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1360. materialLabelUI.setForeground(Color.BLACK);
  1361. }
  1362. // === 物料码输入框(可选)===
  1363. if (showMaterialInput && materialSnInput == null) {
  1364. materialSnInput = new JTextField();
  1365. materialSnInput.setHorizontalAlignment(SwingConstants.CENTER);
  1366. materialSnInput.setEditable(false);
  1367. materialSnInput.setFont(new Font("微软雅黑", Font.PLAIN, 28));
  1368. materialSnInput.setPreferredSize(new Dimension(400, 70));
  1369. }
  1370. // === 物料扫码按钮(可选)===
  1371. if (showMaterialInput && scanMaterialBtn == null) {
  1372. scanMaterialBtn = new JButton("");
  1373. scanMaterialBtn.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/resources/image/bg/scan_barcode.png"))));
  1374. scanMaterialBtn.setEnabled(false);
  1375. scanMaterialBtn.addActionListener(e -> onScanMaterialClick());
  1376. }
  1377. // === 解绑按钮(可选)===
  1378. if (showMaterialInput && unbindMaterialBtn == null) {
  1379. unbindMaterialBtn = new JButton("");
  1380. unbindMaterialBtn.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/resources/image/bg/delete.png"))));
  1381. unbindMaterialBtn.setEnabled(false);
  1382. unbindMaterialBtn.addActionListener(e -> onUnbindClick());
  1383. }
  1384. // === 工位标签(双工位时显示)===
  1385. if (showHeader && stationLabel == null) {
  1386. stationLabel = new JLabel(stationCode);
  1387. stationLabel.setForeground(Color.BLACK);
  1388. stationLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1389. }
  1390. // === 状态显示(双工位时显示)===
  1391. if (showHeader && statusMenu == null) {
  1392. statusMenu = new JButton("等待加工信号");
  1393. statusMenu.setForeground(Color.GREEN);
  1394. statusMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1395. statusMenu.setBackground(Color.BLACK);
  1396. statusMenu.setPreferredSize(new Dimension(400, 40));
  1397. }
  1398. // === 预设数量标签(可选)===
  1399. if (showDeviceInfo && presetCountLabel == null) {
  1400. presetCountLabel = new JLabel("预设数量");
  1401. presetCountLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1402. presetCountLabel.setForeground(Color.BLACK);
  1403. presetCountLabel.setHorizontalAlignment(SwingConstants.CENTER);
  1404. }
  1405. // === 预设数量(可选)===
  1406. if (showDeviceInfo && presetCountField == null) {
  1407. presetCountField = new JTextField("0");
  1408. presetCountField.setHorizontalAlignment(SwingConstants.CENTER);
  1409. presetCountField.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1410. presetCountField.setEditable(false);
  1411. presetCountField.setPreferredSize(new Dimension(150, 40));
  1412. }
  1413. // === 完成数量标签(可选)===
  1414. if (showDeviceInfo && finishedCountLabel == null) {
  1415. finishedCountLabel = new JLabel("完成数量");
  1416. finishedCountLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1417. finishedCountLabel.setForeground(Color.BLACK);
  1418. finishedCountLabel.setHorizontalAlignment(SwingConstants.CENTER);
  1419. }
  1420. // === 完成数量(可选)===
  1421. if (showDeviceInfo && finishedCountField == null) {
  1422. finishedCountField = new JTextField("0");
  1423. finishedCountField.setHorizontalAlignment(SwingConstants.CENTER);
  1424. finishedCountField.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1425. finishedCountField.setEditable(false);
  1426. finishedCountField.setPreferredSize(new Dimension(150, 40));
  1427. }
  1428. // === 第一行可选前置标签 ===
  1429. if (showDeviceInfo && deviceInfoLabel == null) {
  1430. StationConfig cfg = StationConfig.getInstance();
  1431. StationConfig.DeviceInfoRow row0 = cfg.getDeviceInfoRow(0);
  1432. if (row0 != null && row0.hasLabel()) {
  1433. deviceInfoLabel = new JLabel(row0.getLabel());
  1434. deviceInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1435. deviceInfoLabel.setForeground(Color.BLACK);
  1436. deviceInfoLabel.setHorizontalAlignment(SwingConstants.CENTER);
  1437. }
  1438. }
  1439. // === 第二行设备信息(可选)===
  1440. if (showDeviceInfo2 && presetCountLabel2 == null) {
  1441. StationConfig cfg = StationConfig.getInstance();
  1442. StationConfig.DeviceInfoRow row1 = cfg.getDeviceInfoRow(1);
  1443. // 第二行可选前置标签
  1444. if (row1 != null && row1.hasLabel()) {
  1445. deviceInfoLabel2 = new JLabel(row1.getLabel());
  1446. deviceInfoLabel2.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1447. deviceInfoLabel2.setForeground(Color.BLACK);
  1448. deviceInfoLabel2.setHorizontalAlignment(SwingConstants.CENTER);
  1449. }
  1450. presetCountLabel2 = new JLabel("预设数量");
  1451. presetCountLabel2.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1452. presetCountLabel2.setForeground(Color.BLACK);
  1453. presetCountLabel2.setHorizontalAlignment(SwingConstants.CENTER);
  1454. presetCountField2 = new JTextField("0");
  1455. presetCountField2.setHorizontalAlignment(SwingConstants.CENTER);
  1456. presetCountField2.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1457. presetCountField2.setEditable(false);
  1458. presetCountField2.setPreferredSize(new Dimension(150, 40));
  1459. finishedCountLabel2 = new JLabel("完成数量");
  1460. finishedCountLabel2.setFont(new Font("微软雅黑", Font.PLAIN, 18));
  1461. finishedCountLabel2.setForeground(Color.BLACK);
  1462. finishedCountLabel2.setHorizontalAlignment(SwingConstants.CENTER);
  1463. finishedCountField2 = new JTextField("0");
  1464. finishedCountField2.setHorizontalAlignment(SwingConstants.CENTER);
  1465. finishedCountField2.setFont(new Font("微软雅黑", Font.PLAIN, 20));
  1466. finishedCountField2.setEditable(false);
  1467. finishedCountField2.setPreferredSize(new Dimension(150, 40));
  1468. }
  1469. }
  1470. /**
  1471. * 将布局配置应用到运行模式
  1472. */
  1473. private void applyLayoutConfigToRuntime() {
  1474. Insets insets = getInsets();
  1475. int contentWidth = getWidth() - insets.left - insets.right;
  1476. int contentHeight = getHeight() - insets.top - insets.bottom;
  1477. if (contentWidth <= 0 || contentHeight <= 0) {
  1478. // 面板还没有大小,稍后重试
  1479. SwingUtilities.invokeLater(this::applyLayoutConfigToRuntime);
  1480. return;
  1481. }
  1482. log.debug("[{}] applyLayoutConfigToRuntime: 面板={}x{}, 内容={}x{}, insets=({},{},{},{})",
  1483. stationCode, getWidth(), getHeight(), contentWidth, contentHeight,
  1484. insets.top, insets.left, insets.bottom, insets.right);
  1485. Map<String, UILayoutConfig.ComponentLayout> components = uiLayoutConfig.getComponents();
  1486. // 应用每个组件的布局
  1487. for (Map.Entry<String, UILayoutConfig.ComponentLayout> entry : components.entrySet()) {
  1488. String id = entry.getKey();
  1489. UILayoutConfig.ComponentLayout layout = entry.getValue();
  1490. JComponent comp = getComponentById(id);
  1491. if (comp == null) continue;
  1492. // 计算绝对位置(相对坐标 * 内容区域大小 + 边距偏移)
  1493. int x = insets.left + (int)(layout.getPosition().getX() * contentWidth);
  1494. int y = insets.top + (int)(layout.getPosition().getY() * contentHeight);
  1495. int width = (int)(layout.getSize().getWidth() * contentWidth);
  1496. int height = (int)(layout.getSize().getHeight() * contentHeight);
  1497. comp.setBounds(x, y, width, height);
  1498. add(comp);
  1499. log.debug("[{}] 运行模式组件 {} 布局: ({},{},{},{})", stationCode, id, x, y, width, height);
  1500. }
  1501. revalidate();
  1502. repaint();
  1503. }
  1504. /**
  1505. * 初始化编辑模式UI - 使用与运行模式相同的布局配置
  1506. */
  1507. private void initEditModeUI() {
  1508. log.info("[{}] 初始化编辑模式", stationCode);
  1509. setLayout(null);
  1510. // 保持面板大小
  1511. if (capturedPanelSize != null) {
  1512. setPreferredSize(capturedPanelSize);
  1513. setMinimumSize(capturedPanelSize);
  1514. setSize(capturedPanelSize);
  1515. }
  1516. // 编辑模式不使用边框,橙色边框通过gridOverlay绘制
  1517. setBorder(null);
  1518. // 加载布局配置(与运行模式相同)
  1519. loadLayoutConfig();
  1520. // 确保组件已创建
  1521. ensureComponentsCreated();
  1522. // 添加网格叠加层(带橙色边框标识编辑模式)
  1523. gridOverlay = new JPanel() {
  1524. @Override
  1525. protected void paintComponent(Graphics g) {
  1526. super.paintComponent(g);
  1527. if (uiLayoutConfig != null && uiLayoutConfig.getGlobalSettings().isShowGrid()) {
  1528. drawGrid(g);
  1529. }
  1530. // 绘制 Flex 行边界(如果是 flex 模式)
  1531. if (uiLayoutConfig != null && uiLayoutConfig.isFlexMode()) {
  1532. drawFlexRowBounds(g);
  1533. }
  1534. // 绘制橙色边框标识编辑模式
  1535. Graphics2D g2 = (Graphics2D) g;
  1536. g2.setColor(new Color(255, 152, 0));
  1537. g2.setStroke(new BasicStroke(3));
  1538. g2.drawRect(1, 1, getWidth() - 3, getHeight() - 3);
  1539. }
  1540. };
  1541. gridOverlay.setOpaque(false);
  1542. gridOverlay.setLayout(null);
  1543. // 包装所有组件为可拖拽版本
  1544. wrapComponent("product_sn_input", productSnInput);
  1545. wrapComponent("scan_product_btn", scanProductBtn);
  1546. wrapComponent("ok_button", okButton);
  1547. wrapComponent("ng_button", ngButton);
  1548. if (showMaterialInput) {
  1549. wrapComponent("material_label", materialLabelUI);
  1550. wrapComponent("material_sn_input", materialSnInput);
  1551. wrapComponent("scan_material_btn", scanMaterialBtn);
  1552. wrapComponent("unbind_material_btn", unbindMaterialBtn);
  1553. }
  1554. if (showDeviceInfo) {
  1555. if (deviceInfoLabel != null) {
  1556. wrapComponent("device_info_label", deviceInfoLabel);
  1557. }
  1558. wrapComponent("preset_count_label", presetCountLabel);
  1559. wrapComponent("preset_count_field", presetCountField);
  1560. wrapComponent("finished_count_label", finishedCountLabel);
  1561. wrapComponent("finished_count_field", finishedCountField);
  1562. }
  1563. // 包装工位标签和状态栏(双工位模式或有这些组件时)
  1564. if (stationLabel != null) {
  1565. wrapComponent("station_label", stationLabel);
  1566. }
  1567. if (statusMenu != null) {
  1568. wrapComponent("status_menu", statusMenu);
  1569. }
  1570. add(gridOverlay);
  1571. gridOverlay.setBounds(0, 0, getWidth(), getHeight());
  1572. // 添加尺寸变化监听器
  1573. addComponentListener(new ComponentAdapter() {
  1574. @Override
  1575. public void componentResized(ComponentEvent e) {
  1576. if (editMode && gridOverlay != null) {
  1577. gridOverlay.setBounds(0, 0, getWidth(), getHeight());
  1578. applyEditModeLayout();
  1579. }
  1580. }
  1581. });
  1582. // 应用布局
  1583. SwingUtilities.invokeLater(this::applyEditModeLayout);
  1584. log.info("[{}] 编辑模式初始化完成,组件数: {}", stationCode, componentWrappers.size());
  1585. }
  1586. /**
  1587. * 应用编辑模式布局
  1588. * 如果是 flex 模式,组件会被约束在对应的行内
  1589. */
  1590. private void applyEditModeLayout() {
  1591. if (gridOverlay == null) return;
  1592. int panelWidth = getWidth();
  1593. int panelHeight = getHeight();
  1594. if (panelWidth <= 0 || panelHeight <= 0) return;
  1595. Insets insets = getInsets();
  1596. int contentWidth = panelWidth - insets.left - insets.right;
  1597. int contentHeight = panelHeight - insets.top - insets.bottom;
  1598. if (contentWidth <= 0 || contentHeight <= 0) return;
  1599. boolean isSingleMode = !showHeader;
  1600. log.debug("[{}] applyEditModeLayout: 面板={}x{}, 内容区域={}x{}, flex={}",
  1601. stationCode, panelWidth, panelHeight, contentWidth, contentHeight,
  1602. uiLayoutConfig != null && uiLayoutConfig.isFlexMode());
  1603. // 如果是 flex 模式,使用 flex 布局定位组件
  1604. if (uiLayoutConfig != null && uiLayoutConfig.isFlexMode()) {
  1605. applyEditModeFlexLayout(insets, contentWidth, contentHeight, isSingleMode);
  1606. } else {
  1607. applyEditModeFreeLayout(insets, contentWidth, contentHeight, isSingleMode);
  1608. }
  1609. gridOverlay.revalidate();
  1610. gridOverlay.repaint();
  1611. }
  1612. /**
  1613. * 编辑模式下应用 Flex 布局(组件约束在行内)
  1614. */
  1615. private void applyEditModeFlexLayout(Insets insets, int contentWidth, int contentHeight, boolean isSingleMode) {
  1616. List<UILayoutConfig.RowLayout> visibleRows = uiLayoutConfig.getVisibleRowsForMode(isSingleMode);
  1617. if (visibleRows.isEmpty()) {
  1618. applyEditModeFreeLayout(insets, contentWidth, contentHeight, isSingleMode);
  1619. return;
  1620. }
  1621. // 获取网格大小
  1622. int gridSize = uiLayoutConfig.getGlobalSettings().getGridSize();
  1623. // 计算每行的实际高度(对齐到网格)
  1624. Map<String, Integer> rowHeights = new HashMap<>();
  1625. for (UILayoutConfig.RowLayout row : visibleRows) {
  1626. int maxHeight = 0;
  1627. for (UILayoutConfig.RowComponentLayout compLayout : row.getVisibleComponents()) {
  1628. String compId = compLayout.getId();
  1629. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(compId, isSingleMode);
  1630. if (layout == null) layout = uiLayoutConfig.getComponent(compId);
  1631. if (layout == null && compId.endsWith("2")) {
  1632. String fallbackId = compId.substring(0, compId.length() - 1);
  1633. layout = uiLayoutConfig.getComponentForMode(fallbackId, isSingleMode);
  1634. if (layout == null) layout = uiLayoutConfig.getComponent(fallbackId);
  1635. }
  1636. if (layout != null) {
  1637. int h = (int)(layout.getSize().getHeight() * contentHeight);
  1638. h = snapToGrid(h, gridSize);
  1639. maxHeight = Math.max(maxHeight, h);
  1640. }
  1641. }
  1642. rowHeights.put(row.getId(), Math.max(maxHeight, snapToGrid(50, gridSize)));
  1643. }
  1644. // 计算总高度和间距
  1645. int totalRowHeight = 0;
  1646. for (Integer h : rowHeights.values()) {
  1647. totalRowHeight += h;
  1648. }
  1649. int remainingSpace = contentHeight - totalRowHeight;
  1650. int gapCount = visibleRows.size() + 1;
  1651. int gap = snapToGrid(Math.max(remainingSpace / gapCount, 10), gridSize);
  1652. // 计算每行的 Y 起始位置(对齐到网格)
  1653. Map<String, Integer> rowStartY = new HashMap<>();
  1654. int currentY = snapToGrid(insets.top + gap, gridSize);
  1655. for (UILayoutConfig.RowLayout row : visibleRows) {
  1656. rowStartY.put(row.getId(), currentY);
  1657. currentY += rowHeights.get(row.getId()) + gap;
  1658. }
  1659. // 布局每个组件,约束在对应的行内
  1660. for (UILayoutConfig.RowLayout row : visibleRows) {
  1661. int rowY = rowStartY.get(row.getId());
  1662. int rowHeight = rowHeights.get(row.getId());
  1663. for (UILayoutConfig.RowComponentLayout compLayout : row.getVisibleComponents()) {
  1664. String componentId = compLayout.getId();
  1665. DraggableComponentWrapper wrapper = componentWrappers.get(componentId);
  1666. if (wrapper == null) continue;
  1667. // 从配置读取 X 和宽度
  1668. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(componentId, isSingleMode);
  1669. if (layout == null) layout = uiLayoutConfig.getComponent(componentId);
  1670. if (layout == null && componentId.endsWith("2")) {
  1671. String fallbackId = componentId.substring(0, componentId.length() - 1);
  1672. layout = uiLayoutConfig.getComponentForMode(fallbackId, isSingleMode);
  1673. if (layout == null) layout = uiLayoutConfig.getComponent(fallbackId);
  1674. }
  1675. int compX, compWidth, compHeight;
  1676. if (layout != null) {
  1677. compX = insets.left + (int)(layout.getPosition().getX() * contentWidth);
  1678. compWidth = (int)(layout.getSize().getWidth() * contentWidth);
  1679. compHeight = (int)(layout.getSize().getHeight() * contentHeight);
  1680. } else {
  1681. double[] defaultLayout = getDefaultLayout(componentId);
  1682. compX = insets.left + (int)(defaultLayout[0] * contentWidth);
  1683. compWidth = (int)(defaultLayout[2] * contentWidth);
  1684. compHeight = (int)(defaultLayout[3] * contentHeight);
  1685. }
  1686. // 对齐到网格
  1687. compX = snapToGrid(compX, gridSize);
  1688. compWidth = snapToGrid(Math.max(compWidth, 50), gridSize);
  1689. compHeight = snapToGrid(Math.max(compHeight, 30), gridSize);
  1690. // Y 坐标:在行内垂直居中,对齐到网格
  1691. int compY = snapToGrid(rowY + (rowHeight - compHeight) / 2, gridSize);
  1692. wrapper.setBounds(compX, compY, compWidth, compHeight);
  1693. }
  1694. }
  1695. }
  1696. /**
  1697. * 编辑模式下应用 Free 布局(自由定位)
  1698. */
  1699. private void applyEditModeFreeLayout(Insets insets, int contentWidth, int contentHeight, boolean isSingleMode) {
  1700. // 获取网格大小
  1701. int gridSize = uiLayoutConfig.getGlobalSettings().getGridSize();
  1702. for (Map.Entry<String, DraggableComponentWrapper> entry : componentWrappers.entrySet()) {
  1703. String componentId = entry.getKey();
  1704. DraggableComponentWrapper wrapper = entry.getValue();
  1705. // 获取相对坐标
  1706. double relX, relY, relW, relH;
  1707. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(componentId, isSingleMode);
  1708. if (layout == null) {
  1709. layout = wrapper.getLayoutConfig();
  1710. }
  1711. if (layout != null) {
  1712. relX = layout.getPosition().getX();
  1713. relY = layout.getPosition().getY();
  1714. relW = layout.getSize().getWidth();
  1715. relH = layout.getSize().getHeight();
  1716. } else {
  1717. double[] defaultLayout = getDefaultLayout(componentId);
  1718. relX = defaultLayout[0];
  1719. relY = defaultLayout[1];
  1720. relW = defaultLayout[2];
  1721. relH = defaultLayout[3];
  1722. }
  1723. // 相对坐标转绝对坐标
  1724. int x = insets.left + (int)(relX * contentWidth);
  1725. int y = insets.top + (int)(relY * contentHeight);
  1726. int width = Math.max((int)(relW * contentWidth), 50);
  1727. int height = Math.max((int)(relH * contentHeight), 30);
  1728. // 对齐到网格
  1729. x = snapToGrid(x, gridSize);
  1730. y = snapToGrid(y, gridSize);
  1731. width = snapToGrid(width, gridSize);
  1732. height = snapToGrid(height, gridSize);
  1733. wrapper.setBounds(x, y, width, height);
  1734. }
  1735. }
  1736. /**
  1737. * 将值对齐到网格
  1738. */
  1739. private int snapToGrid(int value, int gridSize) {
  1740. if (gridSize <= 0) return value;
  1741. return Math.round(value / (float) gridSize) * gridSize;
  1742. }
  1743. /**
  1744. * 从捕获的运行模式布局更新配置
  1745. */
  1746. private void updateLayoutFromCaptured(Map<String, Rectangle> capturedBounds) {
  1747. for (Map.Entry<String, Rectangle> entry : capturedBounds.entrySet()) {
  1748. String componentId = entry.getKey();
  1749. Rectangle bounds = entry.getValue();
  1750. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponent(componentId);
  1751. if (layout == null) {
  1752. layout = new UILayoutConfig.ComponentLayout();
  1753. layout.setId(componentId);
  1754. uiLayoutConfig.addComponent(componentId, layout);
  1755. }
  1756. // 将放大1000倍的相对坐标转换回0-1范围
  1757. double relX = bounds.x / 1000.0;
  1758. double relY = bounds.y / 1000.0;
  1759. double relW = bounds.width / 1000.0;
  1760. double relH = bounds.height / 1000.0;
  1761. layout.getPosition().setX(relX);
  1762. layout.getPosition().setY(relY);
  1763. layout.getSize().setWidth(relW);
  1764. layout.getSize().setHeight(relH);
  1765. log.debug("[{}] 更新组件 {} 配置: raw=({},{},{},{}) -> rel=({},{},{},{})",
  1766. stationCode, componentId, bounds.x, bounds.y, bounds.width, bounds.height,
  1767. String.format("%.3f", relX), String.format("%.3f", relY),
  1768. String.format("%.3f", relW), String.format("%.3f", relH));
  1769. }
  1770. log.info("[{}] 已从运行模式布局更新配置,共{}个组件", stationCode, capturedBounds.size());
  1771. }
  1772. /**
  1773. * 获取布局配置文件名
  1774. * 统一使用 ui_layout_flex.yaml,单双工位差异由 station.yaml 控制
  1775. */
  1776. private String getLayoutConfigFileName() {
  1777. return "ui_layout_flex.yaml";
  1778. }
  1779. /**
  1780. * 加载布局配置
  1781. * @return true 如果从文件加载成功,false 如果使用默认布局
  1782. */
  1783. private boolean loadLayoutConfig() {
  1784. String configFileName = getLayoutConfigFileName();
  1785. try {
  1786. // 优先从文件系统加载(开发环境,可以实时更新)
  1787. Path filePath = Paths.get("src/resources/config/" + configFileName);
  1788. if (Files.exists(filePath)) {
  1789. log.info("从文件系统加载UI布局配置: {}", filePath);
  1790. StringBuilder sb = new StringBuilder();
  1791. java.io.BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8);
  1792. String line;
  1793. while ((line = reader.readLine()) != null) {
  1794. sb.append(line).append("\n");
  1795. }
  1796. reader.close();
  1797. String yaml = sb.toString();
  1798. uiLayoutConfig = UILayoutConfig.fromYaml(yaml);
  1799. log.info("UI布局配置从文件系统加载成功 ({})", configFileName);
  1800. // 根据 station.yaml 同步行可见性
  1801. syncLayoutWithStationConfig();
  1802. return true; // 从文件加载成功
  1803. }
  1804. // 从classpath加载(生产环境)
  1805. String configPath = "resources/config/" + configFileName;
  1806. InputStream is = getClass().getClassLoader().getResourceAsStream(configPath);
  1807. if (is != null) {
  1808. log.info("从classpath加载UI布局配置: {}", configFileName);
  1809. // Java 8 兼容方式读取流
  1810. StringBuilder sb = new StringBuilder();
  1811. java.io.BufferedReader reader = new java.io.BufferedReader(
  1812. new java.io.InputStreamReader(is, StandardCharsets.UTF_8));
  1813. String line;
  1814. while ((line = reader.readLine()) != null) {
  1815. sb.append(line).append("\n");
  1816. }
  1817. reader.close();
  1818. String yaml = sb.toString();
  1819. uiLayoutConfig = UILayoutConfig.fromYaml(yaml);
  1820. log.info("UI布局配置从classpath加载成功 ({})", configFileName);
  1821. // 根据 station.yaml 同步行可见性
  1822. syncLayoutWithStationConfig();
  1823. return true; // 从classpath加载成功
  1824. } else {
  1825. // 使用默认布局
  1826. uiLayoutConfig = createDefaultLayout();
  1827. log.info("使用默认UI布局 ({})", configFileName);
  1828. return false; // 使用默认布局
  1829. }
  1830. } catch (Exception e) {
  1831. log.error("加载UI布局配置失败 ({}): {}", configFileName, e.getMessage());
  1832. uiLayoutConfig = createDefaultLayout();
  1833. return false; // 加载失败,使用默认布局
  1834. }
  1835. }
  1836. /**
  1837. * 根据 station.yaml 配置同步布局的行可见性
  1838. * 这样只需要在 station.yaml 中配置开关,布局会自动调整
  1839. */
  1840. private void syncLayoutWithStationConfig() {
  1841. if (uiLayoutConfig == null || !uiLayoutConfig.isFlexMode()) {
  1842. return;
  1843. }
  1844. StationConfig stationConfig = StationConfig.getInstance();
  1845. boolean isSingleMode = !showHeader;
  1846. // 同步工位头行:单工位(showHeader=false)时隐藏
  1847. uiLayoutConfig.setRowVisibleForMode("row_header", showHeader, isSingleMode);
  1848. log.debug("[{}] 同步行可见性: row_header={}", stationCode, showHeader);
  1849. // 同步物料行:由 show_material_input 控制
  1850. boolean showMaterial = stationConfig.isShowMaterialInput();
  1851. uiLayoutConfig.setRowVisibleForMode("row_material", showMaterial, isSingleMode);
  1852. log.debug("[{}] 同步行可见性: row_material={}", stationCode, showMaterial);
  1853. // 同步设备信息行:由 show_device_info 控制
  1854. boolean showDevice = stationConfig.isShowDeviceInfo();
  1855. uiLayoutConfig.setRowVisibleForMode("row_device", showDevice, isSingleMode);
  1856. log.debug("[{}] 同步行可见性: row_device={}", stationCode, showDevice);
  1857. // 同步设备信息第二行:由 show_device_info2 控制
  1858. boolean showDevice2 = stationConfig.isShowDeviceInfo2();
  1859. uiLayoutConfig.setRowVisibleForMode("row_device2", showDevice2, isSingleMode);
  1860. log.debug("[{}] 同步行可见性: row_device2={}", stationCode, showDevice2);
  1861. log.info("[{}] Flex布局已同步 station.yaml 配置: mode={}, header={}, material={}, device={}, device2={}",
  1862. stationCode, isSingleMode ? "单工位" : "双工位", showHeader, showMaterial, showDevice, showDevice2);
  1863. }
  1864. /**
  1865. * 重新加载布局配置并刷新界面
  1866. * 用于双工位模式下,编辑完成后同步布局到另一个工位
  1867. * 同时支持 show_device_info / show_material_input 切换后的动态组件创建与添加
  1868. */
  1869. public void reloadLayoutConfig() {
  1870. log.info("[{}] 重新加载布局配置", stationCode);
  1871. // 1) 按当前 show_* 开关创建缺失的组件
  1872. ensureComponentsCreated();
  1873. // 2) 把尚未添加到面板的可选组件补加进去(幂等:已添加的不重复加)
  1874. ensureComponentsAdded();
  1875. loadLayoutConfig();
  1876. if (!editMode && getWidth() > 0 && getHeight() > 0) {
  1877. applyRuntimeLayout();
  1878. revalidate();
  1879. repaint();
  1880. }
  1881. }
  1882. /**
  1883. * 把当前 show_* 开关需要的可选组件补加到面板
  1884. * 幂等:若组件已在本面板中则跳过
  1885. */
  1886. private void ensureComponentsAdded() {
  1887. if (showDeviceInfo) {
  1888. addIfAbsent(deviceInfoLabel);
  1889. addIfAbsent(presetCountLabel);
  1890. addIfAbsent(presetCountField);
  1891. addIfAbsent(finishedCountLabel);
  1892. addIfAbsent(finishedCountField);
  1893. }
  1894. if (showDeviceInfo2) {
  1895. addIfAbsent(deviceInfoLabel2);
  1896. addIfAbsent(presetCountLabel2);
  1897. addIfAbsent(presetCountField2);
  1898. addIfAbsent(finishedCountLabel2);
  1899. addIfAbsent(finishedCountField2);
  1900. }
  1901. if (showMaterialInput) {
  1902. addIfAbsent(materialLabelUI);
  1903. addIfAbsent(materialSnInput);
  1904. addIfAbsent(scanMaterialBtn);
  1905. addIfAbsent(unbindMaterialBtn);
  1906. }
  1907. }
  1908. private void addIfAbsent(java.awt.Component c) {
  1909. if (c == null) return;
  1910. if (c.getParent() == this) return;
  1911. add(c);
  1912. }
  1913. /**
  1914. * 创建默认布局配置
  1915. */
  1916. private UILayoutConfig createDefaultLayout() {
  1917. UILayoutConfig config = new UILayoutConfig();
  1918. // 工件码输入框
  1919. UILayoutConfig.ComponentLayout productInput = new UILayoutConfig.ComponentLayout();
  1920. productInput.setId("product_sn_input");
  1921. productInput.setType("text_field");
  1922. productInput.getPosition().setX(0.0);
  1923. productInput.getPosition().setY(0.18);
  1924. productInput.getSize().setWidth(0.75);
  1925. productInput.getSize().setHeight(0.12);
  1926. productInput.getSize().setMinWidth(400);
  1927. productInput.getSize().setMinHeight(50);
  1928. productInput.getStyle().setFontSize(28);
  1929. config.addComponent("product_sn_input", productInput);
  1930. // 扫码按钮
  1931. UILayoutConfig.ComponentLayout scanBtn = new UILayoutConfig.ComponentLayout();
  1932. scanBtn.setId("scan_product_btn");
  1933. scanBtn.setType("button");
  1934. scanBtn.getPosition().setX(0.78);
  1935. scanBtn.getPosition().setY(0.18);
  1936. scanBtn.getSize().setWidth(0.20);
  1937. scanBtn.getSize().setHeight(0.12);
  1938. scanBtn.getSize().setMinWidth(100);
  1939. scanBtn.getSize().setMinHeight(50);
  1940. scanBtn.getStyle().setFontSize(32);
  1941. config.addComponent("scan_product_btn", scanBtn);
  1942. // OK按钮
  1943. UILayoutConfig.ComponentLayout okBtn = new UILayoutConfig.ComponentLayout();
  1944. okBtn.setId("ok_button");
  1945. okBtn.setType("button");
  1946. okBtn.getPosition().setX(0.25);
  1947. okBtn.getPosition().setY(0.70);
  1948. okBtn.getSize().setWidth(0.20);
  1949. okBtn.getSize().setHeight(0.13);
  1950. okBtn.getSize().setMinWidth(120);
  1951. okBtn.getSize().setMinHeight(60);
  1952. okBtn.getStyle().setFontSize(32);
  1953. config.addComponent("ok_button", okBtn);
  1954. // NG按钮
  1955. UILayoutConfig.ComponentLayout ngBtn = new UILayoutConfig.ComponentLayout();
  1956. ngBtn.setId("ng_button");
  1957. ngBtn.setType("button");
  1958. ngBtn.getPosition().setX(0.55);
  1959. ngBtn.getPosition().setY(0.70);
  1960. ngBtn.getSize().setWidth(0.20);
  1961. ngBtn.getSize().setHeight(0.13);
  1962. ngBtn.getSize().setMinWidth(120);
  1963. ngBtn.getSize().setMinHeight(60);
  1964. ngBtn.getStyle().setFontSize(32);
  1965. config.addComponent("ng_button", ngBtn);
  1966. return config;
  1967. }
  1968. /**
  1969. * 获取布局偏移量(供 DraggableComponentWrapper 使用)
  1970. * 返回值与运行模式下的 Insets 保持一致
  1971. */
  1972. public int[] getLayoutOffsets() {
  1973. // 使用与运行模式相同的边框 Insets 计算
  1974. // showHeader=true: CompoundBorder(EtchedBorder(2,2,2,2) + EmptyBorder(10,10,10,10)) = (12,12,12,12)
  1975. // showHeader=false: EmptyBorder(40,10,10,10) = top=40, left=10, bottom=10, right=10
  1976. int offsetLeft, offsetTop, offsetRight, offsetBottom;
  1977. if (showHeader) {
  1978. // EtchedBorder ~= 2 + EmptyBorder = 10, total = 12
  1979. offsetLeft = 12;
  1980. offsetTop = 12;
  1981. offsetRight = 12;
  1982. offsetBottom = 12;
  1983. } else {
  1984. // EmptyBorder(top=40, left=10, bottom=10, right=10)
  1985. offsetLeft = 10;
  1986. offsetTop = 40;
  1987. offsetRight = 10;
  1988. offsetBottom = 10;
  1989. }
  1990. return new int[]{offsetLeft, offsetTop, offsetRight, offsetBottom};
  1991. }
  1992. /**
  1993. * 包装组件为可拖拽版本
  1994. */
  1995. private void wrapComponent(String componentId, JComponent component) {
  1996. if (component == null) return;
  1997. // 根据模式获取组件配置 (showHeader=false 是单工位模式)
  1998. boolean isSingleMode = !showHeader;
  1999. UILayoutConfig.ComponentLayout layoutConfig = uiLayoutConfig.getComponentForMode(componentId, isSingleMode);
  2000. if (layoutConfig == null) {
  2001. // 尝试从通用配置获取
  2002. layoutConfig = uiLayoutConfig.getComponent(componentId);
  2003. }
  2004. if (layoutConfig == null) {
  2005. // 创建默认配置
  2006. layoutConfig = new UILayoutConfig.ComponentLayout();
  2007. layoutConfig.setId(componentId);
  2008. layoutConfig.setType(getComponentType(component));
  2009. // 保存到模式专用配置
  2010. uiLayoutConfig.setComponentForMode(componentId, layoutConfig, isSingleMode);
  2011. }
  2012. DraggableComponentWrapper wrapper = new DraggableComponentWrapper(
  2013. component, componentId, layoutConfig, this
  2014. );
  2015. wrapper.setEditMode(editMode);
  2016. wrapper.setSnapToGrid(uiLayoutConfig.getGlobalSettings().isEnableSnap());
  2017. wrapper.setGridSize(uiLayoutConfig.getGlobalSettings().getGridSize());
  2018. // 监听布局变更
  2019. wrapper.setLayoutChangeListener((id, layout) -> {
  2020. log.debug("组件 {} 布局已更改", id);
  2021. });
  2022. componentWrappers.put(componentId, wrapper);
  2023. gridOverlay.add(wrapper);
  2024. }
  2025. /**
  2026. * 应用布局配置(将相对坐标转换为绝对坐标)
  2027. */
  2028. private void applyLayoutConfig() {
  2029. // 使用捕获的面板大小(如果有),否则使用当前大小
  2030. int panelWidth = (capturedPanelSize != null) ? capturedPanelSize.width : getWidth();
  2031. int panelHeight = (capturedPanelSize != null) ? capturedPanelSize.height : getHeight();
  2032. log.debug("[{}] applyLayoutConfig: 使用大小={}x{} (捕获={}, 当前={}x{})",
  2033. stationCode, panelWidth, panelHeight,
  2034. capturedPanelSize != null,
  2035. getWidth(), getHeight());
  2036. if (panelWidth <= 0 || panelHeight <= 0) {
  2037. return;
  2038. }
  2039. // 同时更新 gridOverlay 大小
  2040. if (gridOverlay != null) {
  2041. gridOverlay.setBounds(0, 0, panelWidth, panelHeight);
  2042. }
  2043. // 使用 getLayoutOffsets() 获取与运行模式一致的偏移量
  2044. int[] offsets = getLayoutOffsets();
  2045. int offsetLeft = offsets[0];
  2046. int offsetTop = offsets[1];
  2047. int offsetRight = offsets[2];
  2048. int offsetBottom = offsets[3];
  2049. // 计算模拟的内容区域大小
  2050. int contentWidth = panelWidth - offsetLeft - offsetRight;
  2051. int contentHeight = panelHeight - offsetTop - offsetBottom;
  2052. log.debug("[{}] 内容区域: offset=({},{}) size={}x{}",
  2053. stationCode, offsetLeft, offsetTop, contentWidth, contentHeight);
  2054. if (contentWidth <= 0 || contentHeight <= 0) {
  2055. return;
  2056. }
  2057. for (Map.Entry<String, DraggableComponentWrapper> entry : componentWrappers.entrySet()) {
  2058. DraggableComponentWrapper wrapper = entry.getValue();
  2059. UILayoutConfig.ComponentLayout layout = wrapper.getLayoutConfig();
  2060. if (!layout.isVisible()) continue;
  2061. // 计算绝对位置和尺寸(基于模拟的内容区域)
  2062. int x = offsetLeft + (int)(layout.getPosition().getX() * contentWidth);
  2063. int y = offsetTop + (int)(layout.getPosition().getY() * contentHeight);
  2064. int width = (int)(layout.getSize().getWidth() * contentWidth);
  2065. int height = (int)(layout.getSize().getHeight() * contentHeight);
  2066. // 应用最小尺寸限制
  2067. width = Math.max(width, layout.getSize().getMinWidth());
  2068. height = Math.max(height, layout.getSize().getMinHeight());
  2069. log.debug("[{}] 组件 {} 布局: 相对pos=({},{}) size=({},{}) -> 绝对bounds=({},{},{},{})",
  2070. stationCode, entry.getKey(),
  2071. String.format("%.3f", layout.getPosition().getX()),
  2072. String.format("%.3f", layout.getPosition().getY()),
  2073. String.format("%.3f", layout.getSize().getWidth()),
  2074. String.format("%.3f", layout.getSize().getHeight()),
  2075. x, y, width, height);
  2076. wrapper.setBounds(x, y, width, height);
  2077. wrapper.setVisible(layout.isVisible());
  2078. }
  2079. }
  2080. /**
  2081. * 绘制网格
  2082. */
  2083. private void drawGrid(Graphics g) {
  2084. Graphics2D g2 = (Graphics2D) g;
  2085. g2.setColor(Color.decode(uiLayoutConfig.getGlobalSettings().getGridColor()));
  2086. g2.setStroke(new BasicStroke(1));
  2087. int gridSize = uiLayoutConfig.getGlobalSettings().getGridSize();
  2088. int width = getWidth();
  2089. int height = getHeight();
  2090. // 绘制垂直线
  2091. for (int x = 0; x <= width; x += gridSize) {
  2092. g2.drawLine(x, 0, x, height);
  2093. }
  2094. // 绘制水平线
  2095. for (int y = 0; y <= height; y += gridSize) {
  2096. g2.drawLine(0, y, width, y);
  2097. }
  2098. }
  2099. /**
  2100. * 绘制 Flex 行边界(编辑模式显示)
  2101. */
  2102. private void drawFlexRowBounds(Graphics g) {
  2103. Graphics2D g2 = (Graphics2D) g;
  2104. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  2105. boolean isSingleMode = !showHeader;
  2106. List<UILayoutConfig.RowLayout> visibleRows = uiLayoutConfig.getVisibleRowsForMode(isSingleMode);
  2107. if (visibleRows.isEmpty()) return;
  2108. Insets insets = getInsets();
  2109. int contentWidth = getWidth() - insets.left - insets.right;
  2110. int contentHeight = getHeight() - insets.top - insets.bottom;
  2111. // 计算每行的实际高度
  2112. Map<String, Integer> rowHeights = new HashMap<>();
  2113. for (UILayoutConfig.RowLayout row : visibleRows) {
  2114. int maxHeight = 0;
  2115. for (UILayoutConfig.RowComponentLayout compLayout : row.getVisibleComponents()) {
  2116. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponentForMode(compLayout.getId(), isSingleMode);
  2117. if (layout == null) layout = uiLayoutConfig.getComponent(compLayout.getId());
  2118. if (layout != null) {
  2119. int h = (int)(layout.getSize().getHeight() * contentHeight);
  2120. maxHeight = Math.max(maxHeight, h);
  2121. }
  2122. }
  2123. rowHeights.put(row.getId(), Math.max(maxHeight, 50));
  2124. }
  2125. // 计算总高度和间距
  2126. int totalRowHeight = 0;
  2127. for (Integer h : rowHeights.values()) {
  2128. totalRowHeight += h;
  2129. }
  2130. int remainingSpace = contentHeight - totalRowHeight;
  2131. int gapCount = visibleRows.size() + 1;
  2132. int gap = Math.max(remainingSpace / gapCount, 10);
  2133. // 定义行的颜色
  2134. Color[] rowColors = {
  2135. new Color(255, 100, 100, 60), // 红色半透明
  2136. new Color(100, 255, 100, 60), // 绿色半透明
  2137. new Color(100, 100, 255, 60), // 蓝色半透明
  2138. new Color(255, 255, 100, 60), // 黄色半透明
  2139. new Color(255, 100, 255, 60), // 紫色半透明
  2140. };
  2141. // 绘制每行的边界
  2142. int currentY = insets.top + gap;
  2143. int colorIndex = 0;
  2144. for (UILayoutConfig.RowLayout row : visibleRows) {
  2145. int rowHeight = rowHeights.get(row.getId());
  2146. // 填充行背景
  2147. g2.setColor(rowColors[colorIndex % rowColors.length]);
  2148. g2.fillRect(insets.left + 5, currentY, contentWidth - 10, rowHeight);
  2149. // 绘制行边框
  2150. g2.setColor(rowColors[colorIndex % rowColors.length].darker());
  2151. g2.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{5, 5}, 0));
  2152. g2.drawRect(insets.left + 5, currentY, contentWidth - 10, rowHeight);
  2153. // 绘制行标签
  2154. g2.setColor(new Color(50, 50, 50));
  2155. g2.setFont(new Font("微软雅黑", Font.BOLD, 12));
  2156. String label = row.getId() + " (h=" + rowHeight + ")";
  2157. g2.drawString(label, insets.left + 10, currentY + 15);
  2158. currentY += rowHeight + gap;
  2159. colorIndex++;
  2160. }
  2161. }
  2162. /**
  2163. * 获取组件类型
  2164. */
  2165. private String getComponentType(JComponent component) {
  2166. if (component instanceof JTextField) return "text_field";
  2167. if (component instanceof JButton) return "button";
  2168. if (component instanceof JLabel) return "label";
  2169. if (component instanceof JPanel) return "panel";
  2170. return "unknown";
  2171. }
  2172. /**
  2173. * 保存布局配置
  2174. */
  2175. public void saveLayoutConfig() {
  2176. String configFileName = getLayoutConfigFileName();
  2177. try {
  2178. // 先把当前编辑的组件位置更新到模式专用配置
  2179. boolean isSingleMode = !showHeader;
  2180. updateModeLayoutFromWrappers(isSingleMode);
  2181. String yaml = uiLayoutConfig.toYaml();
  2182. // 保存到文件 (Java 8 兼容方式)
  2183. Path configPath = Paths.get("src/resources/config/" + configFileName);
  2184. java.io.BufferedWriter writer = Files.newBufferedWriter(configPath, StandardCharsets.UTF_8);
  2185. writer.write(yaml);
  2186. writer.close();
  2187. String modeDesc = showHeader ? "双工位" : "单工位";
  2188. log.info("UI布局配置已保存 ({}, {})", modeDesc, configFileName);
  2189. JOptionPane.showMessageDialog(this, modeDesc + "布局配置保存成功!", "保存",
  2190. JOptionPane.INFORMATION_MESSAGE);
  2191. } catch (Exception e) {
  2192. log.error("保存UI布局配置失败 ({}): {}", configFileName, e.getMessage(), e);
  2193. JOptionPane.showMessageDialog(this, "布局配置保存失败: " + e.getMessage(),
  2194. "错误", JOptionPane.ERROR_MESSAGE);
  2195. }
  2196. }
  2197. /**
  2198. * 把当前wrapper的位置更新到模式专用配置
  2199. */
  2200. private void updateModeLayoutFromWrappers(boolean isSingleMode) {
  2201. for (Map.Entry<String, DraggableComponentWrapper> entry : componentWrappers.entrySet()) {
  2202. String componentId = entry.getKey();
  2203. DraggableComponentWrapper wrapper = entry.getValue();
  2204. UILayoutConfig.ComponentLayout layout = wrapper.getLayoutConfig();
  2205. if (layout != null) {
  2206. uiLayoutConfig.setComponentForMode(componentId, layout, isSingleMode);
  2207. }
  2208. }
  2209. log.debug("已更新{}布局到配置", isSingleMode ? "单工位" : "双工位");
  2210. }
  2211. /**
  2212. * 导出布局配置
  2213. */
  2214. public void exportLayoutConfig() {
  2215. JFileChooser fileChooser = new JFileChooser();
  2216. fileChooser.setDialogTitle("导出布局配置");
  2217. fileChooser.setFileFilter(new FileNameExtensionFilter("YAML文件 (*.yaml)", "yaml"));
  2218. if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
  2219. try {
  2220. java.io.File file = fileChooser.getSelectedFile();
  2221. if (!file.getName().endsWith(".yaml")) {
  2222. file = new java.io.File(file.getAbsolutePath() + ".yaml");
  2223. }
  2224. String yaml = uiLayoutConfig.toYaml();
  2225. // Java 8 兼容方式写入文件
  2226. java.io.BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);
  2227. writer.write(yaml);
  2228. writer.close();
  2229. JOptionPane.showMessageDialog(this, "导出成功!", "导出",
  2230. JOptionPane.INFORMATION_MESSAGE);
  2231. } catch (Exception e) {
  2232. log.error("导出失败: {}", e.getMessage(), e);
  2233. JOptionPane.showMessageDialog(this, "导出失败: " + e.getMessage(),
  2234. "错误", JOptionPane.ERROR_MESSAGE);
  2235. }
  2236. }
  2237. }
  2238. /**
  2239. * 导入布局配置
  2240. */
  2241. public void importLayoutConfig() {
  2242. JFileChooser fileChooser = new JFileChooser();
  2243. fileChooser.setDialogTitle("导入布局配置");
  2244. fileChooser.setFileFilter(new FileNameExtensionFilter("YAML文件 (*.yaml)", "yaml"));
  2245. if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
  2246. try {
  2247. java.io.File file = fileChooser.getSelectedFile();
  2248. // Java 8 兼容方式读取文件
  2249. StringBuilder sb = new StringBuilder();
  2250. java.io.BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);
  2251. String line;
  2252. while ((line = reader.readLine()) != null) {
  2253. sb.append(line).append("\n");
  2254. }
  2255. reader.close();
  2256. String yaml = sb.toString();
  2257. uiLayoutConfig = UILayoutConfig.fromYaml(yaml);
  2258. // 更新组件 wrapper 的配置引用并重新应用布局
  2259. if (editMode) {
  2260. for (Map.Entry<String, DraggableComponentWrapper> entry : componentWrappers.entrySet()) {
  2261. String id = entry.getKey();
  2262. DraggableComponentWrapper wrapper = entry.getValue();
  2263. UILayoutConfig.ComponentLayout layout = uiLayoutConfig.getComponent(id);
  2264. if (layout != null) {
  2265. wrapper.setLayoutConfig(layout);
  2266. }
  2267. }
  2268. applyEditModeLayout();
  2269. }
  2270. JOptionPane.showMessageDialog(this, "导入成功!", "导入",
  2271. JOptionPane.INFORMATION_MESSAGE);
  2272. } catch (Exception e) {
  2273. log.error("导入失败: {}", e.getMessage(), e);
  2274. JOptionPane.showMessageDialog(this, "导入失败: " + e.getMessage(),
  2275. "错误", JOptionPane.ERROR_MESSAGE);
  2276. }
  2277. }
  2278. }
  2279. /**
  2280. * 切换网格显示
  2281. */
  2282. public void toggleGrid(boolean show) {
  2283. if (uiLayoutConfig != null) {
  2284. uiLayoutConfig.getGlobalSettings().setShowGrid(show);
  2285. if (gridOverlay != null) {
  2286. gridOverlay.repaint();
  2287. }
  2288. }
  2289. }
  2290. // 防重入保护标志
  2291. private volatile boolean isScanDialogShowing = false;
  2292. private volatile boolean isMaterialScanDialogShowing = false;
  2293. }