panel.option

本文介绍了一个用于网页中管理页面标签的选项组件实现方法,包括显示、隐藏、重命名、删除等操作,支持不同浏览器环境。
/// 
/// 
//页面标签选项类
ND.Panel.Options = function(panelID)
{
    var panel = document.getElementById(panelID);
    var options = ND.Panel.Options.Create(panelID);
    //当前显示页面,则允许添加模块
    document.getElementById("panelAddModule").style.display = panelID == ND.Panel.ShowPanelID ? "block" : "none";
    document.getElementById("panelUpdateLayout").style.display = panelID == ND.Panel.ShowPanelID ? "block" : "none";
    options.style.display = "block";
    
    var panelEvt = document.getElementById(panelID + "_options");
    var left = ND.Offset.GetLeft(panelEvt);
    var top = ND.Offset.GetTop(panelEvt) + panelEvt.offsetHeight;

    if(left + options.offsetWidth >= document.body.offsetWidth - 20)
    {
        //防止超出浏览器右部
        left = document.body.offsetWidth  - options.offsetWidth - 20;
    }
    
    options.style.left = left + "px";
    options.style.top = top + "px";
    
    if(ND.Brower.IsIE)
    {
        document.attachEvent("onmouseup", ND.Panel.Options.Bound);
    }
    else
    {
        document.addEventListener("mouseup", ND.Panel.Options.Bound, false);
    }
    
    panelEvt = null;
    panel = null;
    options = null;
}


//创建选项
ND.Panel.Options.Create = function(panelID)
{
    var options = document.getElementById("panelOptions");
    if(options)
    {
        options.setAttribute("panel", panelID);
        return options;
    }
    
    options = document.createElement("div");
    options.id = "panelOptions";
    options.onselectstart = function() {return false};
    options.setAttribute("panel", panelID);
    var str = new ND.String();
    str.Append("
  • "); str.Append("
  • "); str.Append(""); str.Append(""); str.Append(""); str.Append(""); str.Append(""); var li = "
  • {2}"; str.AppendFormat(li, "panelRename", "ND.Panel.Options.Rename(this, event)", "重命名"); str.AppendFormat(li, "panelDelete", "ND.Panel.Options.Delete(this, event)", "删除"); str.AppendFormat(li, "panelAddModule", "var option=new ND.Option();option.Create('Module');ND.Panel.Options.Hidden()", "添加模块"); str.AppendFormat(li, "panelUpdateLayout", "var option=new ND.Option();option.Create('Layout');ND.Panel.Options.Hidden()", "布局设置"); str.AppendFormat(li, "panelIconChange", "ND.Panel.Options.ChangeIcon(this, event)", "更改图标"); str.AppendFormat(li, "panelOptionsClose", "ND.Panel.Options.Hidden()", "关闭选项组"); str.Append("
"); options.innerHTML = str.toString(); document.body.appendChild(options); try { return options; } finally { options = null; str = null; li = null; } } //改变颜色 ND.Panel.Options.ChangeStyle = function(styleType) { var options = document.getElementById("panelOptions"); var panel = document.getElementById(options.getAttribute("panel")); panel.setAttribute("styleType", styleType); var showState = panel.getAttribute("showState"); var className = "panelTabs " + ND.Panel.GetClass(styleType, showState); if(className != panel.className) { panel.className = className; var data = {}; data.panelCode = panel.getAttribute("panelCode"); data.styleType = styleType; ND.Ajax.Request({ url: "Handle/panel.aspx?action=ChangeStyle", success: ND.Panel.Options.ChangeStyle.Success, param: data }); } options = null; panel = null; } //变更颜色样式成功 ND.Panel.Options.ChangeStyle.Success = function(result) { result = result.responseXML; ND.Success.Check(result); } //重命名 ND.Panel.Options.Rename = function(el, evt) { ND.Panel.ChangeText(el.parentNode.parentNode.getAttribute('panel'), evt); ND.Panel.Options.Hidden(); } //删除 ND.Panel.Options.Delete = function() { if(document.getElementById("panelTabs").childNodes.length <= 2) { //只剩一个标签页 alert("您不能删除唯一的标签页"); return; } var panelID = document.getElementById("panelOptions").getAttribute("panel"); var title = document.getElementById(panelID + "_title").firstChild; var confirmText = title.tagName == "INPUT" ? title.value : title.innerHTML; title = null; if(confirm("您确认要删除 {0} 标签页吗?".Format(confirmText)) == 0) { return; } var panel = document.getElementById(panelID); panel.parentNode.removeChild(panel); //标签对应页存在,删除页 var page = document.getElementById(panelID.replace("panel", "page")); if(page) { page.parentNode.removeChild(page); } //删除页为当前显示页,变更第一页为当前显示页 if(panelID == ND.Panel.ShowPanelID) { ND.Panel.ShowPanelID = null; ND.Panel.ChangePanel(document.getElementById("panelTabs").firstChild.id); } var data = {}; data.panelCode = panel.getAttribute("panelCode"); ND.Ajax.Request({ url: "Handle/panel.aspx?action=Delete", success: ND.Panel.Options.Delete.Success, param: data }); ND.Panel.Options.Hidden(); panel = null; page = null; } //删除成功 ND.Panel.Options.Delete.Success = function(result) { result = result.responseXML; ND.Success.Check(result); } //创建图标集 ND.Panel.Options.ChangeIcon = function() { var changeIcon = document.getElementById("panelIconChangeBar"); if(changeIcon) { changeIcon.style.display = changeIcon.style.display == "none" ? "block" : "none"; return; } var div = document.createElement("div"); div.id = "panelIconChangeBar"; div.innerHTML = "读取中,请稍后..."; document.getElementById("panelOptions").appendChild(div); changeIcon = null; div = null; function success(result) { document.getElementById("panelIconChangeBar").innerHTML = result.responseText; } ND.Ajax.Request({url: "icon.aspx", param: {size: 9, type: 'panel'}, success: success}); } //更改图标 ND.Panel.Options.ChangeIcon.Change = function(el) { var panelID = document.getElementById("panelOptions").getAttribute("panel"); var icon = document.getElementById(panelID + "_icon"); var iconLink = el.getAttribute("icon"); if(icon.getAttribute("oldIcon") != iconLink) { icon.setAttribute("oldIcon", iconLink); icon.style.backgroundImage = "url(" + iconLink + ")"; var data = {}; data.panelCode = document.getElementById(panelID).getAttribute("panelCode"); data.icon = iconLink; ND.Ajax.Request({ url: "Handle/panel.aspx?action=ChangeIcon", success: ND.Panel.Options.ChangeIcon.Success, param: data }); } } //更改图标成功 ND.Panel.Options.ChangeIcon.Success = function(result) { result = result.responseXML; ND.Success.Check(result); } //判断范围 ND.Panel.Options.Bound = function(evt) { evt = evt || window.event; var x = evt.x ? evt.x + document.documentElement.scrollLeft : evt.pageX; var y = evt.y ? evt.y + document.documentElement.scrollTop : evt.pageY; var options = document.getElementById("panelOptions"); var left = ND.Offset.GetLeft(options); var right = left + options.offsetWidth; var top = ND.Offset.GetTop(options); var bottom = top + options.offsetHeight; if(x < left || x > right || y < top || y > bottom) { ND.Panel.Options.Hidden(); } options = null; } //隐藏 ND.Panel.Options.Hidden = function() { var options = document.getElementById("panelOptions"); if(options) { options.style.display = "none"; if(ND.Brower.IsIE) { document.detachEvent("onmouseup", ND.Panel.Options.Bound); } else { document.removeEventListener("mouseup", ND.Panel.Options.Bound, false); } options = null; } }
 
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class StudentRegistrationForm extends JFrame { // 定义各个组件 private JTextField nameField; private JRadioButton maleRadio, femaleRadio; private JTextField birthDateField; private JTextField schoolField; private JComboBox<String> majorComboBox; private JCheckBox basketballCheckBox, volleyballCheckBox, footballCheckBox, swimmingCheckBox; private JFileChooser fileChooser; private JButton uploadButton; private JTextField passwordField; private JTextArea introTextArea; private JButton submitButton, cancelButton; public StudentRegistrationForm() { // 设置窗口标题 setTitle("学生信息注册"); // 设置窗口大小 setSize(600, 500); // 设置窗口关闭操作 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗口居中显示 setLocationRelativeTo(null); // 创建一个面板,使用网格布局 JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; // 添加姓名标签和文本框 gbc.gridx = 0; gbc.gridy = 0; panel.add(new JLabel("姓名:"), gbc); gbc.gridx = 1; nameField = new JTextField(20); nameField.setText("Your name..."); panel.add(nameField, gbc); // 添加性别标签和单选按钮 gbc.gridx = 0; gbc.gridy = 1; panel.add(new JLabel("性别:"), gbc); gbc.gridx = 1; ButtonGroup genderGroup = new ButtonGroup(); maleRadio = new JRadioButton("男"); femaleRadio = new JRadioButton("女"); genderGroup.add(maleRadio); genderGroup.add(femaleRadio); JPanel genderPanel = new JPanel(); genderPanel.add(maleRadio); genderPanel.add(femaleRadio); panel.add(genderPanel, gbc); // 添加出生日期标签和文本框 gbc.gridx = 0; gbc.gridy = 2; panel.add(new JLabel("出生日期:"), gbc); gbc.gridx = 1; birthDateField = new JTextField("2000-01-01", 20); panel.add(birthDateField, gbc); // 添加学校标签和文本框 gbc.gridx = 0; gbc.gridy = 3; panel.add(new JLabel("学校:"), gbc); gbc.gridx = 1; schoolField = new JTextField(20); panel.add(schoolField, gbc); // 添加专业标签和下拉框 gbc.gridx = 0; gbc.gridy = 4; panel.add(new JLabel("专业:"), gbc); gbc.gridx = 1; String[] majors = {"计算机科学与技术", "软件工程", "电子信息工程", "通信工程"}; majorComboBox = new JComboBox<>(majors); panel.add(majorComboBox, gbc); // 添加体育特长标签和复选框 gbc.gridx = 0; gbc.gridy = 5; panel.add(new JLabel("体育特长:"), gbc); gbc.gridx = 1; basketballCheckBox = new JCheckBox("篮球"); volleyballCheckBox = new JCheckBox("排球"); footballCheckBox = new JCheckBox("足球"); swimmingCheckBox = new JCheckBox("游泳"); JPanel sportsPanel = new JPanel(); sportsPanel.add(basketballCheckBox); sportsPanel.add(volleyballCheckBox); sportsPanel.add(footballCheckBox); sportsPanel.add(swimmingCheckBox); panel.add(sportsPanel, gbc); // 添加上传照片标签和按钮 gbc.gridx = 0; gbc.gridy = 6; panel.add(new JLabel("上传照片:"), gbc); gbc.gridx = 1; uploadButton = new JButton("选择文件"); fileChooser = new JFileChooser(); uploadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog(StudentRegistrationForm.this); if (returnVal == JFileChooser.APPROVE_OPTION) { // 这里可以处理文件上传逻辑 System.out.println("已选择文件: " + fileChooser.getSelectedFile().getName()); } } }); panel.add(uploadButton, gbc); // 添加密码标签和文本框 gbc.gridx = 0; gbc.gridy = 7; panel.add(new JLabel("密码:"), gbc); gbc.gridx = 1; passwordField = new JTextField(20); panel.add(passwordField, gbc); // 添加个人介绍标签和文本域 gbc.gridx = 0; gbc.gridy = 8; panel.add(new JLabel("个人介绍:"), gbc); gbc.gridx = 1; introTextArea = new JTextArea(5, 20); introTextArea.setText("..."); JScrollPane scrollPane = new JScrollPane(introTextArea); panel.add(scrollPane, gbc); // 添加提交和取消按钮 gbc.gridx = 0; gbc.gridy = 9; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.CENTER; JPanel buttonPanel = new JPanel(); submitButton = new JButton("提交"); cancelButton = new JButton("取消"); submitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 这里可以处理提交逻辑 System.out.println("提交按钮被点击"); } }); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 这里可以处理取消逻辑 System.out.println("取消按钮被点击"); } }); buttonPanel.add(submitButton); buttonPanel.add(cancelButton); panel.add(buttonPanel, gbc); // 将面板添加到窗口 add(panel); } public static void main(String[] args) { // 使用 SwingUtilities 确保在事件调度线程中创建和显示 GUI SwingUtilities.invokeLater(new Runnable() { @Override public void run() { StudentRegistrationForm form = new StudentRegistrationForm(); form.setVisible(true); } }); } } 以上代码结果是怎样的
最新发布
10-16
// 单词信息修改 - GUI实现 private void updateWord() { String targetWord = searchField.getText().trim(); if (targetWord.isEmpty()) { JOptionPane.showMessageDialog(this, "请输入要修改的单词"); return; } WordNode current = head.next; WordNode foundNode = null; // 遍历链表查单词 while (current != null) { if (current.word.equalsIgnoreCase(targetWord)) { foundNode = current; break; } current = current.next; } if (foundNode == null) { JOptionPane.showMessageDialog(this, "未到单词: " + targetWord); return; } // 创建修改对话框 JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5)); JTextField wordField = new JTextField(foundNode.word); JTextField pronField = new JTextField(foundNode.pronunciation); JTextField meaningField = new JTextField(foundNode.meaning); JTextField categoryField = new JTextField(foundNode.category); panel.add(new JLabel("单词:")); panel.add(wordField); panel.add(new JLabel("音标:")); panel.add(pronField); panel.add(new JLabel("释义:")); panel.add(meaningField); panel.add(new JLabel("分类:")); panel.add(categoryField); int result = JOptionPane.showConfirmDialog(this, panel, "修改单词信息", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { // 更新节点信息 foundNode.word = wordField.getText(); foundNode.pronunciation = pronField.getText(); foundNode.meaning = meaningField.getText(); foundNode.category = categoryField.getText(); saveToFile(); // 自动保存 refreshWordList(); // 刷新显示 JOptionPane.showMessageDialog(this, "单词修改成功!"); } }需生成功能图
06-07
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class MyFrame extends JFrame { private JTable table; private DefaultTableModel model; private JTextField searchField; private List<Transaction> transactions = new ArrayList<>(); // 用于存储进出库记录 public MyFrame() { setTitle("商品管理系统"); setSize(900, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // 创建顶部搜索面板 createTopPanel(); // 创建中间表格面板 createCenterPanel(); // 创建右侧按钮面板 createEastPanel(); // 创建底部状态栏 add(createStatusBar(), BorderLayout.SOUTH); } private void createTopPanel() { JPanel topPanel = new JPanel(new BorderLayout()); topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JLabel searchLabel = new JLabel("按商品编号搜索:"); searchField = new JTextField(15); JButton searchButton = new JButton("搜索"); searchButton.addActionListener(e -> searchProduct()); JPanel searchPanel = new JPanel(); searchPanel.add(searchLabel); searchPanel.add(searchField); searchPanel.add(searchButton); topPanel.add(searchPanel, BorderLayout.WEST); add(topPanel, BorderLayout.NORTH); } private void createCenterPanel() { // 表格列名 String[] columnNames = {"商品编号", "商品名称", "建议单价", "一般成本价", "当前库存", "备注"}; // 表格数据 Object[][] data = { {"P001", "苹果手机", 6999.0, 5500.0, 77, "除掉商品"}, {"P002", "智能手机端", 6500.0, 1200.0, 13, "总订单"}, {"P003", "无线耳机", 299.0, 180.0, 56, "蓝牙5.0"}, {"P005", "耳机", 99.0, 88.0, 10, ""} }; // 创建表格模型(除特定列外不可编辑) model = new DefaultTableModel(data, columnNames) { @Override public boolean isCellEditable(int row, int column) { // 仅允许编辑备注列 return column == 5; } }; table = new JTable(model); table.setRowHeight(25); table.getTableHeader().setFont(new Font("SimSun", Font.BOLD, 14)); table.setFont(new Font("SimSun", Font.PLAIN, 14)); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); } private void createEastPanel() { JPanel eastPanel = new JPanel(); eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); eastPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 创建按钮 JButton addButton = createButton("添加商品"); JButton editButton = createButton("编辑商品"); JButton deleteButton = createButton("删除商品"); JButton inButton = createButton("入库"); JButton outButton = createButton("出库"); JButton detailButton = createButton("查看详情"); JButton exitButton = createButton("退出系统"); // 添加动作监听器 addButton.addActionListener(e -> addProduct()); editButton.addActionListener(e -> editProduct()); deleteButton.addActionListener(e -> deleteProduct()); inButton.addActionListener(e -> stockIn()); outButton.addActionListener(e -> stockOut()); detailButton.addActionListener(e -> viewProductDetails()); exitButton.addActionListener(e -> System.exit(0)); // 添加按钮到面板并设置间距 eastPanel.add(addButton); eastPanel.add(Box.createVerticalStrut(10)); eastPanel.add(editButton); eastPanel.add(Box.createVerticalStrut(10)); eastPanel.add(deleteButton); eastPanel.add(Box.createVerticalStrut(10)); eastPanel.add(detailButton); eastPanel.add(Box.createVerticalStrut(20)); // 库存按钮前的额外间距 eastPanel.add(inButton); eastPanel.add(Box.createVerticalStrut(10)); eastPanel.add(outButton); eastPanel.add(Box.createVerticalStrut(20)); // 退出按钮前的额外间距 eastPanel.add(exitButton); add(eastPanel, BorderLayout.EAST); } private JButton createButton(String text) { JButton button = new JButton(text); button.setFont(new Font("SimSun", Font.PLAIN, 14)); button.setPreferredSize(new Dimension(120, 40)); button.setMaximumSize(new Dimension(120, 40)); button.setAlignmentX(Component.CENTER_ALIGNMENT); return button; } private JPanel createStatusBar() { JPanel statusPanel = new JPanel(); statusPanel.setBorder(BorderFactory.createEtchedBorder()); statusPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel statusLabel = new JLabel("当前模式:商品管理"); statusLabel.setFont(new Font("SimSun", Font.PLAIN, 12)); statusPanel.add(statusLabel); return statusPanel; } // 检查商品编号是否已存在 private boolean isProductIdExists(String id) { for (int i = 0; i < model.getRowCount(); i++) { if (model.getValueAt(i, 0).toString().equals(id)) { return true; } } return false; } // 按商品编号搜索 private void searchProduct() { String searchId = searchField.getText().trim(); if (searchId.isEmpty()) { JOptionPane.showMessageDialog(this, "请输入商品编号", "提示", JOptionPane.WARNING_MESSAGE); return; } int rowIndex = -1; for (int i = 0; i < model.getRowCount(); i++) { if (model.getValueAt(i, 0).toString().equals(searchId)) { rowIndex = i; break; } } if (rowIndex == -1) { JOptionPane.showMessageDialog(this, "未到商品编号为 " + searchId + " 的商品", "提示", JOptionPane.INFORMATION_MESSAGE); } else { table.setRowSelectionInterval(rowIndex, rowIndex); viewProductDetails(); // 直接查看详情 } } // 查看商品详情 private void viewProductDetails() { int selectedRow = table.getSelectedRow(); if (selectedRow == -1) { JOptionPane.showMessageDialog(this, "请先选择要查看的商品", "提示", JOptionPane.WARNING_MESSAGE); return; } String productId = model.getValueAt(selectedRow, 0).toString(); // 创建详情面板 JPanel detailPanel = new JPanel(new GridLayout(7, 2, 5, 5)); detailPanel.add(new JLabel("商品编号:")); detailPanel.add(new JLabel(productId)); detailPanel.add(new JLabel("商品名称:")); detailPanel.add(new JLabel(model.getValueAt(selectedRow, 1).toString())); detailPanel.add(new JLabel("建议单价:")); detailPanel.add(new JLabel(model.getValueAt(selectedRow, 2).toString())); detailPanel.add(new JLabel("一般成本价:")); detailPanel.add(new JLabel(model.getValueAt(selectedRow, 3).toString())); detailPanel.add(new JLabel("当前库存:")); detailPanel.add(new JLabel(model.getValueAt(selectedRow, 4).toString())); detailPanel.add(new JLabel("备注:")); detailPanel.add(new JLabel(model.getValueAt(selectedRow, 5).toString())); // 添加进出库记录 detailPanel.add(new JLabel("进出库记录:")); // 创建记录表格 String[] columns = {"操作", "数量", "日期"}; DefaultTableModel recordModel = new DefaultTableModel(columns, 0); // 添加该商品的所有记录 for (Transaction transaction : transactions) { if (transaction.getProductId().equals(productId)) { recordModel.addRow(new Object[]{ transaction.isStockIn() ? "入库" : "出库", transaction.getQuantity(), transaction.getDate() }); } } JTable recordTable = new JTable(recordModel); recordTable.setRowHeight(20); JScrollPane recordScrollPane = new JScrollPane(recordTable); // 创建一个面板来容纳详情和记录 JPanel mainPanel = new JPanel(new BorderLayout()); mainPanel.add(detailPanel, BorderLayout.NORTH); mainPanel.add(recordScrollPane, BorderLayout.CENTER); JOptionPane.showMessageDialog(this, mainPanel, "商品详情", JOptionPane.PLAIN_MESSAGE); } private void addProduct() { JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5)); JTextField idField = new JTextField(); JTextField nameField = new JTextField(); JTextField priceField = new JTextField(); JTextField costField = new JTextField(); JTextField stockField = new JTextField("0"); JTextField noteField = new JTextField(); panel.add(new JLabel("商品编号:")); panel.add(idField); panel.add(new JLabel("商品名称:")); panel.add(nameField); panel.add(new JLabel("建议单价:")); panel.add(priceField); panel.add(new JLabel("一般成本价:")); panel.add(costField); panel.add(new JLabel("当前库存:")); panel.add(stockField); panel.add(new JLabel("备注:")); panel.add(noteField); int result = JOptionPane.showConfirmDialog(this, panel, "添加新商品", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { try { String id = idField.getText().trim(); if (id.isEmpty()) { JOptionPane.showMessageDialog(this, "商品编号不能为空", "错误", JOptionPane.ERROR_MESSAGE); return; } if (isProductIdExists(id)) { JOptionPane.showMessageDialog(this, "商品编号已存在,请使用其他编号", "错误", JOptionPane.ERROR_MESSAGE); return; } Object[] rowData = { id, nameField.getText(), Double.parseDouble(priceField.getText()), Double.parseDouble(costField.getText()), Integer.parseInt(stockField.getText()), noteField.getText() }; model.addRow(rowData); JOptionPane.showMessageDialog(this, "商品添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } } } private void editProduct() { int selectedRow = table.getSelectedRow(); if (selectedRow == -1) { JOptionPane.showMessageDialog(this, "请先选择要编辑的商品", "提示", JOptionPane.WARNING_MESSAGE); return; } JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5)); JTextField idField = new JTextField(model.getValueAt(selectedRow, 0).toString()); JTextField nameField = new JTextField(model.getValueAt(selectedRow, 1).toString()); JTextField priceField = new JTextField(model.getValueAt(selectedRow, 2).toString()); JTextField costField = new JTextField(model.getValueAt(selectedRow, 3).toString()); JTextField stockField = new JTextField(model.getValueAt(selectedRow, 4).toString()); JTextField noteField = new JTextField(model.getValueAt(selectedRow, 5).toString()); // 使ID和库存字段不可编辑 idField.setEditable(false); stockField.setEditable(false); panel.add(new JLabel("商品编号:")); panel.add(idField); panel.add(new JLabel("商品名称:")); panel.add(nameField); panel.add(new JLabel("建议单价:")); panel.add(priceField); panel.add(new JLabel("一般成本价:")); panel.add(costField); panel.add(new JLabel("当前库存:")); panel.add(stockField); panel.add(new JLabel("备注:")); panel.add(noteField); int result = JOptionPane.showConfirmDialog(this, panel, "编辑商品信息", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { try { model.setValueAt(nameField.getText(), selectedRow, 1); model.setValueAt(Double.parseDouble(priceField.getText()), selectedRow, 2); model.setValueAt(Double.parseDouble(costField.getText()), selectedRow, 3); // 不修改库存 model.setValueAt(noteField.getText(), selectedRow, 5); JOptionPane.showMessageDialog(this, "商品信息更新成功!", "成功", JOptionPane.INFORMATION_MESSAGE); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } } } private void deleteProduct() { int selectedRow = table.getSelectedRow(); if (selectedRow == -1) { JOptionPane.showMessageDialog(this, "请先选择要删除的商品", "提示", JOptionPane.WARNING_MESSAGE); return; } // 检查库存是否为0 int currentStock = Integer.parseInt(model.getValueAt(selectedRow, 4).toString()); if (currentStock > 0) { JOptionPane.showMessageDialog(this, "库存不为0,不能删除该商品", "错误", JOptionPane.ERROR_MESSAGE); return; } int confirm = JOptionPane.showConfirmDialog(this, "确定要删除选中的商品吗?", "确认删除", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.YES_OPTION) { model.removeRow(selectedRow); JOptionPane.showMessageDialog(this, "商品删除成功!", "成功", JOptionPane.INFORMATION_MESSAGE); } } private void stockIn() { int selectedRow = table.getSelectedRow(); if (selectedRow == -1) { JOptionPane.showMessageDialog(this, "请先选择要入库的商品", "提示", JOptionPane.WARNING_MESSAGE); return; } String input = JOptionPane.showInputDialog(this, "请输入入库数量:", "入库操作", JOptionPane.PLAIN_MESSAGE); if (input == null || input.trim().isEmpty()) return; try { int quantity = Integer.parseInt(input); if (quantity <= 0) { JOptionPane.showMessageDialog(this, "入库数量必须大于0", "错误", JOptionPane.ERROR_MESSAGE); return; } int currentStock = Integer.parseInt(model.getValueAt(selectedRow, 4).toString()); model.setValueAt(currentStock + quantity, selectedRow, 4); // 记录入库操作 String productId = model.getValueAt(selectedRow, 0).toString(); transactions.add(new Transaction(productId, quantity, true)); JOptionPane.showMessageDialog(this, "入库成功! 当前库存: " + (currentStock + quantity), "成功", JOptionPane.INFORMATION_MESSAGE); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } } private void stockOut() { int selectedRow = table.getSelectedRow(); if (selectedRow == -1) { JOptionPane.showMessageDialog(this, "请先选择要出库的商品", "提示", JOptionPane.WARNING_MESSAGE); return; } String input = JOptionPane.showInputDialog(this, "请输入出库数量:", "出库操作", JOptionPane.PLAIN_MESSAGE); if (input == null || input.trim().isEmpty()) return; try { int quantity = Integer.parseInt(input); if (quantity <= 0) { JOptionPane.showMessageDialog(this, "出库数量必须大于0", "错误", JOptionPane.ERROR_MESSAGE); return; } int currentStock = Integer.parseInt(model.getValueAt(selectedRow, 4).toString()); if (quantity > currentStock) { JOptionPane.showMessageDialog(this, "出库数量不能超过当前库存", "错误", JOptionPane.ERROR_MESSAGE); return; } model.setValueAt(currentStock - quantity, selectedRow, 4); // 记录出库操作 String productId = model.getValueAt(selectedRow, 0).toString(); transactions.add(new Transaction(productId, quantity, false)); JOptionPane.showMessageDialog(this, "出库成功! 当前库存: " + (currentStock - quantity), "成功", JOptionPane.INFORMATION_MESSAGE); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } } // 进出库记录类 private class Transaction { private String productId; private int quantity; private boolean stockIn; private String date; public Transaction(String productId, int quantity, boolean stockIn) { this.productId = productId; this.quantity = quantity; this.stockIn = stockIn; this.date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()); } public String getProductId() { return productId; } public int getQuantity() { return quantity; } public boolean isStockIn() { return stockIn; } public String getDate() { return date; } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { MyFrame frame = new MyFrame(); frame.setVisible(true); }); } } 补充:删除某商品信息,库存不为0时不可删除;提供补充后的代码
06-13
package demo1; import com.fazecast.jSerialComm.SerialPort; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.Map; public class TemperatureMonitorGUI extends JFrame { private JLabel temperatureLabel; private JLabel statusLabel; private JLabel pidOutputLabel; private JButton connectButton; private JButton readButton; private JButton startControlButton; private JButton refreshPortButton; private JComboBox<String> portComboBox; private JComboBox<String> baudRateComboBox; private JComboBox<String> dateBitComboBox; private JComboBox<String> stopBitsComboBox; private JComboBox<String> parityComboBox; private JComboBox<String> modeComboBox; private TemperatureController controller; // 输入组件 private JTextField waitTimeField; private JLabel setTemperatureLabel; private JTextField transitionTimeField; private JTextField constantTempField; private Map<String, Component> modeComponents = new HashMap<>(); // 曲线模式字段 private JTextField[] curveTempFields = new JTextField[3]; private JTextField[] curveDurationFields = new JTextField[3]; private JTextField[] curveHoldFields = new JTextField[3]; private JTextField finalTempField; private JTextField finalTransitionField; // 阶段标签 private JLabel[] stageLabels = new JLabel[3]; // 成员变量:将 rightPanel 提升为类成员变量 private JPanel rightPanel; public TemperatureMonitorGUI() { setTitle("MODBUS RTU 温控系统"); setSize(1100, 700); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setBackground(new Color(240, 245, 250)); JPanel mainPanel = new JPanel(new BorderLayout(15, 15)); mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); add(mainPanel); JPanel topPanel = createTopPanel(); mainPanel.add(topPanel, BorderLayout.NORTH); JPanel centerPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(8, 8, 8, 8); gbc.fill = GridBagConstraints.BOTH; JPanel inputPanel = createInputPanel(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0.3; gbc.weighty = 1.0; centerPanel.add(inputPanel, gbc); JPanel buttonPanel = createButtonPanel(); gbc.gridx = 1; gbc.weightx = 0.2; centerPanel.add(buttonPanel, gbc); this.rightPanel = createRightPanel(); // 修改为成员变量 gbc.gridx = 2; gbc.weightx = 0.4; centerPanel.add(this.rightPanel, gbc); mainPanel.add(centerPanel, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); bottomPanel.setBorder(BorderFactory.createEtchedBorder()); bottomPanel.setBackground(new Color(230, 240, 255)); statusLabel = new JLabel("状态: 未连接"); bottomPanel.add(statusLabel); mainPanel.add(bottomPanel, BorderLayout.SOUTH); } private JPanel createTopPanel() { JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); topPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 15, 0)); topPanel.setBackground(new Color(70, 130, 180)); temperatureLabel = new JLabel("当前温度: -- °C"); setTemperatureLabel = new JLabel("当前设定温度: -- °C"); temperatureLabel.setFont(new Font("微软雅黑", Font.BOLD, 28)); temperatureLabel.setForeground(Color.WHITE); setTemperatureLabel.setFont(new Font("微软雅黑", Font.BOLD, 28)); setTemperatureLabel.setForeground(Color.WHITE); topPanel.add(temperatureLabel); topPanel.add(Box.createRigidArea(new Dimension(30, 0))); topPanel.add(setTemperatureLabel); pidOutputLabel = new JLabel("PID 输出: --%"); pidOutputLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); pidOutputLabel.setForeground(Color.YELLOW); topPanel.add(Box.createRigidArea(new Dimension(30, 0))); topPanel.add(pidOutputLabel); return topPanel; } private JPanel createInputPanel() { JPanel inputPanel = new JPanel(new GridBagLayout()); inputPanel.setBorder(BorderFactory.createTitledBorder("通信配置")); inputPanel.setBackground(Color.WHITE); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; int row = 0; gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("串口:"), gbc); gbc.gridx = 1; JPanel portPanel = new JPanel(new BorderLayout(5, 0)); portComboBox = new JComboBox<>(); portComboBox.setPreferredSize(new Dimension(180, 25)); refreshPortList(); portPanel.add(portComboBox, BorderLayout.CENTER); refreshPortButton = new JButton("刷新"); refreshPortButton.addActionListener(e -> refreshPortList()); portPanel.add(refreshPortButton, BorderLayout.EAST); inputPanel.add(portPanel, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("波特率:"), gbc); gbc.gridx = 1; baudRateComboBox = new JComboBox<>(new String[]{"1200", "2400", "4800", "9600","19200"}); baudRateComboBox.setSelectedItem("9600"); inputPanel.add(baudRateComboBox, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("数据位"), gbc); gbc.gridx = 1; dateBitComboBox = new JComboBox<>(new String[]{"6", "7", "8"}); dateBitComboBox.setSelectedItem("8"); inputPanel.add(dateBitComboBox, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("停止位:"), gbc); gbc.gridx = 1; stopBitsComboBox = new JComboBox<>(new String[]{"1", "1.5", "2"}); stopBitsComboBox.setSelectedIndex(0); inputPanel.add(stopBitsComboBox, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("校验方式:"), gbc); gbc.gridx = 1; parityComboBox = new JComboBox<>(new String[]{"None", "Even", "Odd"}); parityComboBox.setSelectedIndex(0); inputPanel.add(parityComboBox, gbc); gbc.gridx = 0; gbc.gridy = row++; gbc.gridwidth = 2; inputPanel.add(new JSeparator(), gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("初始温度:"), gbc); gbc.gridx = 1; JTextField initialTempField = new JTextField("25.5", 10); inputPanel.add(initialTempField, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("等待时间:"), gbc); gbc.gridx = 1; waitTimeField = new JTextField("60", 10); inputPanel.add(waitTimeField, gbc); gbc.gridx = 0; gbc.gridy = row++; gbc.gridwidth = 2; inputPanel.add(new JSeparator(), gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("模式选择:"), gbc); gbc.gridx = 1; modeComboBox = new JComboBox<>(new String[]{"定值模式", "曲线模式", "PID 设置"}); modeComboBox.setSelectedIndex(0); inputPanel.add(modeComboBox, gbc); gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("启动控制:"), gbc); gbc.gridx = 1; startControlButton = new JButton("启动"); startControlButton.setPreferredSize(new Dimension(100, 30)); startControlButton.setBackground(new Color(50, 150, 50)); startControlButton.setForeground(Color.WHITE); startControlButton.addActionListener(this::startControl); inputPanel.add(startControlButton, gbc); // 添加 PID 设置按钮 gbc.gridx = 0; gbc.gridy = row++; inputPanel.add(new JLabel("PID 设置:"), gbc); gbc.gridx = 1; JButton pidSettingButton = new JButton("打开 PID 设置"); pidSettingButton.addActionListener(e -> { modeComboBox.setSelectedItem("PID 设置"); rightPanel.removeAll(); rightPanel.add(modeComponents.get("PID 设置"), BorderLayout.CENTER); rightPanel.revalidate(); rightPanel.repaint(); }); inputPanel.add(pidSettingButton, gbc); return inputPanel; } private JPanel createButtonPanel() { JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.setBorder(BorderFactory.createTitledBorder("操作")); buttonPanel.setBackground(Color.WHITE); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(15, 10, 15, 10); gbc.fill = GridBagConstraints.HORIZONTAL; connectButton = new JButton("连接串口"); connectButton.setPreferredSize(new Dimension(150, 40)); connectButton.setFont(new Font("微软雅黑", Font.BOLD, 14)); connectButton.setBackground(new Color(70, 130, 180)); connectButton.setForeground(Color.WHITE); connectButton.addActionListener(this::connectSerialPort); gbc.gridy = 0; buttonPanel.add(connectButton, gbc); readButton = new JButton("读取温度"); readButton.setPreferredSize(new Dimension(150, 40)); readButton.setFont(new Font("微软雅黑", Font.BOLD, 14)); readButton.setBackground(new Color(60, 179, 113)); readButton.setForeground(Color.WHITE); readButton.addActionListener(this::readTemperature); gbc.gridy = 1; buttonPanel.add(readButton, gbc); return buttonPanel; } private JPanel createPIDSettingsPanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(BorderFactory.createTitledBorder("PID 参数设置")); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; // Kp gbc.gridx = 0; gbc.gridy = 0; panel.add(new JLabel("Kp:"), gbc); gbc.gridx = 1; JTextField kpField = new JTextField("2.0", 10); panel.add(kpField, gbc); // Ki gbc.gridx = 0; gbc.gridy = 1; panel.add(new JLabel("Ki:"), gbc); gbc.gridx = 1; JTextField kiField = new JTextField("0.5", 10); panel.add(kiField, gbc); // Kd gbc.gridx = 0; gbc.gridy = 2; panel.add(new JLabel("Kd:"), gbc); gbc.gridx = 1; JTextField kdField = new JTextField("1.0", 10); panel.add(kdField, gbc); // 按钮 gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.CENTER; JButton applyPIDButton = new JButton("应用 PID 参数"); applyPIDButton.addActionListener(e -> { try { double Kp = Double.parseDouble(kpField.getText()); double Ki = Double.parseDouble(kiField.getText()); double Kd = Double.parseDouble(kdField.getText()); if (controller != null) { controller.setPIDParameters(Kp, Ki, Kd); JOptionPane.showMessageDialog(this, "PID 参数已更新"); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } }); panel.add(applyPIDButton, gbc); return panel; } private JPanel createRightPanel() { JPanel rightPanel = new JPanel(new BorderLayout()); rightPanel.setBorder(BorderFactory.createTitledBorder("模式配置")); rightPanel.setBackground(Color.WHITE); JPanel constantModePanel = createConstantModePanel(); modeComponents.put("定值模式", constantModePanel); JPanel curveModePanel = createCurveModePanel(); modeComponents.put("曲线模式", curveModePanel); JPanel pidPanel = createPIDSettingsPanel(); modeComponents.put("PID 设置", pidPanel); rightPanel.add(modeComponents.get("定值模式"), BorderLayout.CENTER); modeComboBox.addActionListener(e -> { String selectedMode = (String) modeComboBox.getSelectedItem(); rightPanel.removeAll(); rightPanel.add(modeComponents.get(selectedMode), BorderLayout.CENTER); rightPanel.revalidate(); rightPanel.repaint(); }); return rightPanel; } private JPanel createConstantModePanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setBackground(Color.WHITE); panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(new JLabel("目标温度 (°C):"), gbc); gbc.gridx = 1; constantTempField = new JTextField(10); constantTempField.setText("25.5"); panel.add(constantTempField, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; JLabel infoLabel = new JLabel("<html><div style='width:250px;'>定值模式将温度稳定在设定值</div></html>"); infoLabel.setForeground(new Color(100, 100, 100)); panel.add(infoLabel, gbc); return panel; } private JPanel createCurveModePanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setBackground(Color.WHITE); panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; panel.add(new JLabel("阶段"), gbc); gbc.gridx = 1; panel.add(new JLabel("目标温度 (°C)"), gbc); gbc.gridx = 2; panel.add(new JLabel("等待时间 (秒)"), gbc); gbc.gridx = 3; panel.add(new JLabel("保持时间 (秒)"), gbc); for (int i = 0; i < 3; i++) { gbc.gridx = 0; gbc.gridy = i + 1; gbc.anchor = GridBagConstraints.WEST; JLabel stageLabel = new JLabel("阶段 " + (i + 1) + ":"); stageLabels[i] = stageLabel; panel.add(stageLabel, gbc); gbc.gridx = 1; curveTempFields[i] = new JTextField("0.0"); curveTempFields[i].setColumns(8); panel.add(curveTempFields[i], gbc); gbc.gridx = 2; curveDurationFields[i] = new JTextField("30"); curveDurationFields[i].setColumns(8); panel.add(curveDurationFields[i], gbc); gbc.gridx = 3; curveHoldFields[i] = new JTextField("60"); curveHoldFields[i].setColumns(8); panel.add(curveHoldFields[i], gbc); if (i > 0) { stageLabel.setVisible(false); curveTempFields[i].setVisible(false); curveDurationFields[i].setVisible(false); curveHoldFields[i].setVisible(false); } } gbc.gridy = 4; gbc.gridx = 0; gbc.gridwidth = 4; gbc.anchor = GridBagConstraints.CENTER; JPanel controlButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0)); JButton addStageButton = new JButton("+"); JButton removeStageButton = new JButton("-"); controlButtonPanel.add(addStageButton); controlButtonPanel.add(removeStageButton); panel.add(controlButtonPanel, gbc); gbc.gridy = 5; gbc.gridx = 0; gbc.gridwidth = 1; gbc.anchor = GridBagConstraints.WEST; panel.add(new JLabel("最终目标:"), gbc); gbc.gridx = 1; finalTempField = new JTextField("30.0", 8); panel.add(finalTempField, gbc); gbc.gridx = 2; finalTransitionField = new JTextField("30", 8); panel.add(finalTransitionField, gbc); gbc.gridy = 6; gbc.gridx = 0; gbc.gridwidth = 4; gbc.anchor = GridBagConstraints.WEST; JLabel infoLabel = new JLabel("<html><div style='width:350px;'>点击 '+' 增加阶段,'-' 减少阶段。未填写的阶段将被跳过</div></html>"); infoLabel.setForeground(new Color(100, 100, 100)); panel.add(infoLabel, gbc); final int[] maxVisibleStages = {1}; addStageButton.addActionListener(e -> { if (maxVisibleStages[0] < 3) { maxVisibleStages[0]++; for (int i = 0; i < 3; i++) { boolean visible = i < maxVisibleStages[0]; stageLabels[i].setVisible(visible); curveTempFields[i].setVisible(visible); curveDurationFields[i].setVisible(visible); curveHoldFields[i].setVisible(visible); } panel.revalidate(); panel.repaint(); } }); removeStageButton.addActionListener(e -> { if (maxVisibleStages[0] > 1) { maxVisibleStages[0]--; for (int i = 0; i < 3; i++) { boolean visible = i < maxVisibleStages[0]; stageLabels[i].setVisible(visible); curveTempFields[i].setVisible(visible); curveDurationFields[i].setVisible(visible); curveHoldFields[i].setVisible(visible); } panel.revalidate(); panel.repaint(); } }); return panel; } private void connectSerialPort(ActionEvent e) { String selectedPort = (String) portComboBox.getSelectedItem(); if (selectedPort != null && controller == null) { int baudRate = Integer.parseInt((String) baudRateComboBox.getSelectedItem()); int dateBit = Integer.parseInt((String) dateBitComboBox.getSelectedItem()); int stopBits = getStopBitsValue(); int parity = getParityValue(); controller = new TemperatureController(this, selectedPort, baudRate, dateBit, stopBits, parity); controller.start(); connectButton.setText("断开连接"); connectButton.setBackground(new Color(246, 115, 115)); } else if (controller != null) { controller.stop(); controller = null; setStatus("已断开连接"); connectButton.setText("连接串口"); connectButton.setBackground(new Color(70, 130, 180)); } } private int getStopBitsValue() { String stopBits = (String) stopBitsComboBox.getSelectedItem(); switch (stopBits) { case "1": return SerialPort.ONE_STOP_BIT; case "1.5": return SerialPort.ONE_POINT_FIVE_STOP_BITS; case "2": return SerialPort.TWO_STOP_BITS; default: return SerialPort.ONE_STOP_BIT; } } private int getParityValue() { String parity = (String) parityComboBox.getSelectedItem(); switch (parity) { case "None": return SerialPort.NO_PARITY; case "Even": return SerialPort.EVEN_PARITY; case "Odd": return SerialPort.ODD_PARITY; default: return SerialPort.NO_PARITY; } } private void readTemperature(ActionEvent e) { if (controller != null) { try { byte slaveId = 0x01; controller.readActualTemperature(slaveId); } catch (Exception ex) { showError("读取温度时发生错误: " + ex.getMessage()); } } else { showError("请先连接串口"); } } private void queryCurrentTemperature(ActionEvent e) { if (controller != null) { try { byte slaveId = 0x01; controller.readActualTemperature(slaveId); } catch (Exception ex) { showError("查询当前温度时发生错误: " + ex.getMessage()); } } else { showError("请先连接串口"); } } private void querySetTemperature(ActionEvent e) { if (controller != null) { try { byte slaveId = 0x01; controller.readSetTemperature(slaveId); } catch (Exception ex) { showError("查询设定温度时发生错误: " + ex.getMessage()); } } else { showError("请先连接串口"); } } private void startControl(ActionEvent e) { String selectedModeLabel = (String) modeComboBox.getSelectedItem(); ControlMode selectedMode = ControlMode.fromLabel(selectedModeLabel); if (selectedMode == ControlMode.FIXED_VALUE_MODE) { try { float targetTemp = Float.parseFloat(constantTempField.getText()); controller.setConstantTemperature(targetTemp); showInfo("定值模式启动: " + targetTemp + "°C"); } catch (NumberFormatException ex) { showError("请输入有效的温度值"); } } else if (selectedMode == ControlMode.CURVE_MODE) { controller.handleCurveMode(curveTempFields, curveDurationFields, curveHoldFields, finalTempField, finalTransitionField); } } public void refreshPortList() { portComboBox.removeAllItems(); for (SerialPort port : SerialPort.getCommPorts()) { portComboBox.addItem(port.getSystemPortName()); } } public void updateTemperature(double temperature) { SwingUtilities.invokeLater(() -> { temperatureLabel.setText(String.format("当前温度: %.1f°C", temperature)); if (temperature > 35) { temperatureLabel.setForeground(new Color(220, 20, 60)); } else if (temperature < 10) { temperatureLabel.setForeground(new Color(30, 144, 255)); } else { temperatureLabel.setForeground(Color.WHITE); } }); } public void updateSetTemperature(double temperature) { SwingUtilities.invokeLater(() -> { setTemperatureLabel.setText(String.format("当前设定温度: %.1f°C", temperature)); if (temperature > 35) { setTemperatureLabel.setForeground(new Color(220, 20, 60)); } else if (temperature < 10) { setTemperatureLabel.setForeground(new Color(30, 144, 255)); } else { setTemperatureLabel.setForeground(Color.WHITE); } }); } public void setStatus(String status) { SwingUtilities.invokeLater(() -> statusLabel.setText("状态: " + status) ); } public void showError(String message) { SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE) ); } public void showInfo(String message) { SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(this, message, "信息", JOptionPane.INFORMATION_MESSAGE) ); } public void updatePIDOutput(int power) { SwingUtilities.invokeLater(() -> { pidOutputLabel.setText("PID 输出: " + power + "%"); }); } private void showPIDSettingsDialog() { JPanel panel = createPIDSettingsPanel(); int result = JOptionPane.showConfirmDialog( this, panel, "PID 参数设置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE ); if (result == JOptionPane.OK_OPTION) { try { double Kp = Double.parseDouble(((JTextField) panel.getComponent(1)).getText()); double Ki = Double.parseDouble(((JTextField) panel.getComponent(3)).getText()); double Kd = Double.parseDouble(((JTextField) panel.getComponent(5)).getText()); if (controller != null) { controller.setPIDParameters(Kp, Ki, Kd); JOptionPane.showMessageDialog(this, "PID 参数已更新"); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE); } } } private void createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu settingsMenu = new JMenu("设置"); JMenuItem pidDialogItem = new JMenuItem("PID 参数设置 (弹窗)"); pidDialogItem.addActionListener(e -> showPIDSettingsDialog()); settingsMenu.add(pidDialogItem); menuBar.add(settingsMenu); setJMenuBar(menuBar); } } 帮我补齐在构造函数中调用的代码
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值