Java Swing 打印条码界面
项目场景:
现在要完成Java程序,实现调用打印机打印条形码以及打印内容设置
使用的方法:
1.Java读取txt文件(数组格式)
2.Java读取打印机列表
3.Java生成图片二维码
4.JavaSwing界面
5.Java实现作画
package ccu.edu.com;
import java.awt.*;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.event.UndoableEditListener;
import javax.swing.plaf.FontUIResource;
import javax.swing.text.AbstractDocument.Content;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.StringContent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import javax.swing.border.LineBorder;
import com.alibaba.fastjson.JSON;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
public class PrintMain extends JFrame {
// 年月日字典
private static final Map<String, String> DICTIONARY = new HashMap<String, String>(128) {
{
put("2011","d");
}
};
// panel面板
private String date;
private String year;
private String month;
private String day;
private JPanel leftPanel;
private JPanel leftTopPanel;
private JPanel leftBottomPanel;
private JPanel rightPanel;
private JPanel rightTopPanel;
private JPanel rightBottomPanel;
private JPanel panel;
private JPanel panel_print;
// 菜单栏
private JMenuBar menuBar;
private JMenu[] menu;
// 图标
private ImageIcon[] icons;
// 文本框
private JTextField textField_date;
private JTextField textField;
private JTextField textField_serial;
private JTextField textField_print;
private JTextField textField_x;
private JTextField textField_y;
private JTextField textField_width;
private JTextField textField_height;
private JPasswordField textField_pwd;
// 标签
private JLabel lineOne;
private JLabel lineTwo;
private JLabel lineThree;
private JLabel init = new QRCodeImage("The init data", 85); // 初始二维码
private JLabel logo = new JLabel(new ImageIcon(new ImageIcon("src/icon/logo.png").getImage().getScaledInstance(100, 62, Image.SCALE_DEFAULT))); // 初始图标logo
// 下拉列表
private JComboBox<String> comboBox_class;
private JComboBox<String> comboBox_serial;
private JComboBox<String> comboBox_print;
private JComboBox<String> comboBox_factory;
//文件路径
String bcPath = "src/config/bc.txt";
String lbjPath = "src/config/lbj.txt";
String formPath = "src/config/form.txt";
String settingPath = "src/config/setting.txt";
String printerPath = "src/config/printer.txt";
String pwdPath = "src/config/pwd.txt";
String factoryPath = "src/config/factory_name.txt";
//读出来的文件
private static Map<String, Object> form;
private static Map<String, Object> setForm;
private static Map<String, Object> printForm;
//打印机数组
private static String[] printService;
private JTextField textField_font;
/**
* Create the frame.
*/
public PrintMain() {
leftPanel = new JPanel();
leftPanel.setForeground(Color.LIGHT_GRAY);
rightPanel = new JPanel();
rightTopPanel = new JPanel();
leftTopPanel = new JPanel();
rightBottomPanel = new JPanel();
leftBottomPanel = new JPanel();
menuBar = new JMenuBar();
menu = new JMenu[] { new JMenu() {
{
setToolTipText("打印");
}
}, new JMenu() {
{
setToolTipText("预览");
}
}, new JMenu() {
{
setToolTipText("选择打印机");
}
}, new JMenu() {
{
setToolTipText("退出");
}
} };
icons = new ImageIcon[] { new ImageIcon("src/icon/print.png"), new ImageIcon("src/icon/view.png"),
new ImageIcon("src/icon/setting.png"), new ImageIcon("src/icon/close.png"), };
for (int i = 0; i < menu.length; i++) {
icons[i].setImage(icons[i].getImage().getScaledInstance(30, 30, Image.SCALE_DEFAULT));
menu[i].setIcon(icons[i]);
menuBar.add(menu[i]);
}
// 样式
//设置页面布局
leftPanel.setLayout(new GridLayout(2,1));
rightPanel.setLayout(new GridLayout(2, 1));
//设置子面板布局
leftTopPanel.setLayout(null);
rightTopPanel.setLayout(null);
rightBottomPanel.setLayout(null);
leftBottomPanel.setLayout(null);
//设置面板标题
leftTopPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createTitledBorder("标签样本")));
leftBottomPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createTitledBorder("修改参数文件")));
rightTopPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createTitledBorder("标签内容设置")));
rightBottomPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createTitledBorder("页面布局设置")));
//添加子面板
leftPanel.add(leftTopPanel);
leftPanel.add(leftBottomPanel);
// 布局
getContentPane().add(leftPanel);
getContentPane().add(rightPanel);
setTitle("一汽解放零部件条码打印");
Toolkit tool=getToolkit(); //得到一个Toolkit对象
Image myimage=tool.getImage("src/icon/logo.png"); //由tool获取图像
setIconImage(myimage);
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(200, 200, 1200, 800);
getContentPane().setLayout(new GridLayout(1, 2));
//页面样式
JLabel lblNewLabel = new JLabel("\u65E5\u671F:");
lblNewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 17));
lblNewLabel.setToolTipText("");
lblNewLabel.setBounds(150, 60, 54, 18);
rightTopPanel.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("\u5236\u9020\u5546\u4EE3\u7801:");
lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 17));
lblNewLabel_1.setBounds(105, 100, 99, 18);
rightTopPanel.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("\u73ED\u6B21:");
lblNewLabel_2.setFont(new Font("微软雅黑", Font.PLAIN, 17));
lblNewLabel_2.setBounds(150, 145, 54, 18);
rightTopPanel.add(lblNewLabel_2);
JLabel label = new JLabel("\u6D41\u6C34\u53F7:");
label.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label.setBounds(135, 183, 69, 18);
rightTopPanel.add(label);
JLabel label_1 = new JLabel("\u96F6\u90E8\u4EF6\u53F7:");
label_1.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_1.setBounds(120, 229, 84, 18);
rightTopPanel.add(label_1);
JLabel label_2 = new JLabel("\u6253\u5370\u6570\u91CF:");
label_2.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_2.setBounds(120, 271, 93, 18);
rightTopPanel.add(label_2);
// 日期
Chooser ser = Chooser.getInstance();
String date = dateToString(new Date());
textField_date = new JTextField(date);
addLengthLimit(textField_date, 10);
textField_date.getDocument().addDocumentListener(new MyChangeListener());
textField_date.setFont(new Font("微软雅黑", Font.PLAIN, 17));
ser.register(textField_date);
textField_date.setBounds(218, 57, 224, 30);
rightTopPanel.add(textField_date);
// 制造商代码
comboBox_factory = new JComboBox(readTxtFile(factoryPath));
comboBox_factory.setSelectedIndex((Integer)form.get("factoryCode"));
comboBox_factory.setFont(new Font("微软雅黑", Font.PLAIN, 17));
comboBox_factory.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
refresh();
}
});
comboBox_factory.setBounds(218, 97, 224, 30);
rightTopPanel.add(comboBox_factory);
// 班次的下拉列表
comboBox_class = new JComboBox(readTxtFile(bcPath));
comboBox_class.setSelectedIndex((Integer)form.get("classNum"));
comboBox_class.setFont(new Font("微软雅黑", Font.PLAIN, 17));
comboBox_class.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
refresh();
}
});
comboBox_class.setBounds(218, 142, 224, 30);
rightTopPanel.add(comboBox_class);
// 流水号
textField_serial = new JTextField(form.get("serialNum").toString());
addLengthLimit(textField_serial, 7);
textField_serial.getDocument().addDocumentListener(new MyChangeListener());
textField_serial.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_serial.setBounds(218, 180, 224, 30);
textField_serial.setColumns(10);
rightTopPanel.add(textField_serial);
// 零部件的下拉列表
comboBox_serial = new JComboBox(readTxtFile(lbjPath));
comboBox_serial.setSelectedIndex((Integer)form.get("lbj"));
comboBox_serial.setFont(new Font("微软雅黑", Font.PLAIN, 17));
comboBox_serial.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
refresh();
}
});
comboBox_serial.setBounds(218, 226, 224, 30);
rightTopPanel.add(comboBox_serial);
// 打印数量
textField_print = new JTextField("1");
textField_print.setFont(new Font("微软雅黑", Font.PLAIN, 17));
addLengthLimit(textField_print, 7);
textField_print.setBounds(218, 268, 86, 30);
rightTopPanel.add(textField_print);
textField_print.setColumns(10);
// 右侧添加
rightPanel.add(rightBottomPanel);
// 编辑打印模块
JLabel label_3 = new JLabel("\u6A2A\u5750\u6807");
label_3.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_3.setBounds(112, 86, 72, 18);
rightBottomPanel.add(label_3);
JLabel label_4 = new JLabel("\u7EB5\u5750\u6807");
label_4.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_4.setBounds(322, 86, 72, 18);
rightBottomPanel.add(label_4);
JLabel label_5 = new JLabel("\u6807\u7B7E\u5BBD\u5EA6");
label_5.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_5.setBounds(112, 137, 72, 18);
rightBottomPanel.add(label_5);
JLabel label_6 = new JLabel("\u6807\u7B7E\u9AD8\u5EA6");
label_6.setFont(new Font("微软雅黑", Font.PLAIN, 17));
label_6.setBounds(322, 137, 72, 18);
rightBottomPanel.add(label_6);
String xx = parseFile(settingPath).get("x").toString();
String yy = parseFile(settingPath).get("y").toString();
String width = parseFile(settingPath).get("width").toString();
String heigth = parseFile(settingPath).get("heigth").toString();
String font = parseFile(settingPath).get("font").toString();
// 横坐标
textField_x = new JTextField(xx);
textField_x.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_x.setBounds(187, 85, 86, 24);
rightBottomPanel.add(textField_x);
textField_x.setColumns(10);
// 纵坐标
textField_y = new JTextField(yy);
textField_y.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_y.setBounds(403, 83, 86, 24);
rightBottomPanel.add(textField_y);
textField_y.setColumns(10);
// 标签宽度
textField_width = new JTextField(width);
textField_width.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_width.setBounds(187, 134, 86, 24);
rightBottomPanel.add(textField_width);
textField_width.setColumns(10);
// 标签高度
textField_height = new JTextField(heigth);
textField_height.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_height.setBounds(403, 134, 86, 24);
rightBottomPanel.add(textField_height);
textField_height.setColumns(10);
//不知道是啥
JLabel lblcmcm = new JLabel("\u9ED8\u8BA4\uFF1A8cm*3cm\u6807\u7B7E");
lblcmcm.setFont(new Font("等线", Font.PLAIN, 15));
lblcmcm.setBounds(14, 44, 161, 18);
rightBottomPanel.add(lblcmcm);
//字体
JLabel lable_font = new JLabel("字体大小");
lable_font.setFont(new Font("微软雅黑", Font.PLAIN, 17));
lable_font.setBounds(112, 189, 72, 18);
rightBottomPanel.add(lable_font);
textField_font = new JTextField(font);
textField_font.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_font.setBounds(187, 186, 86, 24);
rightBottomPanel.add(textField_font);
textField_font.setColumns(10);
//打印的面板
panel_print = new JPanel();
panel_print.setBorder(null);
panel_print.setBackground(Color.WHITE);
panel_print.setBounds(53, 80, 480, 180);
panel_print.setLayout(null);
leftTopPanel.add(panel_print);
// 标签内部组件集合
panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, 480, 180);
panel.setBackground(Color.WHITE);
// 二维码组件
init.setSize(100, 85);
init.setLocation(360, 43);
init.setBackground(Color.WHITE);
// logo组件
logo.setSize(100, 86);
logo.setBackground(Color.WHITE);
logo.setLocation(33, 43);
// 组件添加
panel.add(logo);
panel.add(init);
panel_print.add(panel);
// 三个数据标签
lineOne = new JLabel("XXXXX");
lineOne.setFont(new Font("黑体", Font.PLAIN, 19));
lineOne.setBounds(165, 45, 187, 18);
panel.add(lineOne);
lineTwo = new JLabel("XXXXXXXXXXXXXX");
lineTwo.setFont(new Font("黑体", Font.PLAIN, 19));
lineTwo.setBounds(165, 76, 187, 18);
panel.add(lineTwo);
lineThree = new JLabel("XXXXXXXXXXXXXXXXXX");
lineThree.setFont(new Font("黑体", Font.PLAIN, 19));
lineThree.setBounds(165, 110, 187, 18);
panel.add(lineThree);
JButton editLbj = new JButton("\u7F16\u8F91\u96F6\u90E8\u4EF6\u5217\u8868");
editLbj.setFont(new Font("微软雅黑", Font.PLAIN, 16));
editLbj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame jf = new JFrame("校验密码");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
checkPwd(jf, jf ,"lbj");
}
});
editLbj.setBounds(71, 90, 173, 35);
leftBottomPanel.add(editLbj);
JButton editFactory = new JButton("\u7F16\u8F91\u5236\u9020\u5546\u5217\u8868");
editFactory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame jf = new JFrame("校验密码");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
checkPwd(jf, jf ,"factory");
}
});
editFactory.setFont(new Font("微软雅黑", Font.PLAIN, 16));
editFactory.setBounds(345, 90, 173, 35);
leftBottomPanel.add(editFactory);
JButton editClass = new JButton("\u7F16\u8F91\u73ED\u6B21\u5217\u8868");
editClass.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame jf = new JFrame("校验密码");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
checkPwd(jf, jf ,"class");
}
});
editClass.setFont(new Font("微软雅黑", Font.PLAIN, 16));
editClass.setBounds(71, 186, 173, 35);
leftBottomPanel.add(editClass);
JButton editPwd = new JButton("\u4FEE\u6539\u5BC6\u7801");
editPwd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame jf = new JFrame("校验密码");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
checkPwd(jf, jf ,"pwd");
}
});
editPwd.setFont(new Font("微软雅黑", Font.PLAIN, 16));
editPwd.setBounds(345, 186, 173, 35);
leftBottomPanel.add(editPwd);
rightPanel.add(rightTopPanel);
rightPanel.add(rightBottomPanel);
// 保存设置按钮
JButton button = new JButton("\u4FDD\u5B58\u8BBE\u7F6E");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("点击按钮");
// 位置参数(设置位置)
if("".equals(textField_x.getText())||"".equals(textField_y.getText())||"".equals(textField_width.getText())||"".equals(textField_height.getText())||"".equals(textField_font.getText())) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"请将参数填写完整",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
}else {
if(!isInteger(textField_x.getText())||!isInteger(textField_y.getText())||!isInteger(textField_width.getText())||!isInteger(textField_height.getText())||!isInteger(textField_font.getText())) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"参数有误",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
}else {
int x = Integer.parseInt(textField_x.getText());
int y = Integer.parseInt(textField_y.getText());
int width = Integer.parseInt(textField_width.getText());
int height = Integer.parseInt(textField_height.getText());
int font = Integer.parseInt(textField_font.getText());
//将位置参数写入文件
updateFile(settingPath, new HashMap<String, Object>(4) {
{
put("x", x);
put("y", y);
put("width", width);
put("heigth", height);
put("font", font);
}
});
/*
* //按照表单设置组件 panel.setBounds(x, y, 414, 102); panel_print.setBounds(53, 80,
* width, height); // 刷新组件 panel.repaint(); panel_print.repaint();
*/
}
}
}
});
button.setFont(new Font("微软雅黑", Font.PLAIN, 15));
button.setBounds(441, 274, 120, 35);
rightBottomPanel.add(button);
JButton button_1 = new JButton("\u6062\u590D\u9ED8\u8BA4");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 横坐标
textField_x.setText("0");
textField_x.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_x.setBounds(187, 85, 86, 24);
rightBottomPanel.add(textField_x);
textField_x.setColumns(10);
// 纵坐标
textField_y.setText("0");
textField_y.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_y.setBounds(376, 85, 86, 24);
rightBottomPanel.add(textField_y);
textField_y.setColumns(10);
// 标签宽度
textField_width.setText("80");
textField_width.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_width.setBounds(187, 157, 86, 24);
rightBottomPanel.add(textField_width);
textField_width.setColumns(10);
// 标签高度
textField_height.setText("30");
textField_height.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_height.setBounds(376, 159, 86, 24);
rightBottomPanel.add(textField_height);
textField_height.setColumns(10);
//字体大小
textField_font = new JTextField("6");
textField_font.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_font.setBounds(187, 224, 86, 24);
rightBottomPanel.add(textField_font);
textField_font.setColumns(10);
//将位置参数写入文件
updateFile(settingPath, new HashMap<String, Object>(4) {
{
put("x", 0);
put("y", 0);
put("width", 80);
put("heigth", 30);
put("font", 6);
}
});
}
});
button_1.setFont(new Font("微软雅黑", Font.PLAIN, 15));
button_1.setBounds(301, 274, 120, 35);
rightBottomPanel.add(button_1);
/* 菜单点击事件 */
menu[0].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("触发打印事件");
refresh();
if(isFull()) {
if(textField_print.getText() != null) {
final JFrame jf = new JFrame("打印");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
showPrintDialog(jf, jf);
}
}
}
});
menu[1].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("预览");
refresh();
}
});
menu[2].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("配置默认打印机" + e);
//弹出框
final JFrame jf = new JFrame("配置默认打印机");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
showDefaultPrintDialog(jf, jf);
}
});
menu[3].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
}
/**
* 显示一个自定义的对话框
*
* @param owner 对话框的拥有者
* @param parentComponent 对话框的父级组件
*/
void showPrintDialog(Frame owner, Component parentComponent) {
// 创建一个模态对话框
final JDialog dialog = new JDialog(owner, "打印", true);
// 设置对话框的宽高
dialog.setSize(400, 150);
// 设置对话框大小不可改变
dialog.setResizable(false);
// 设置对话框相对显示的位置
dialog.setLocationRelativeTo(parentComponent);
//设置布局
dialog.getContentPane().setLayout(null);
// 创建一个标签显示消息内容
JLabel messageLabel = new JLabel("点击确定开始打印");
messageLabel.setBounds(10, 20, 400, 50);
// 创建一个按钮用于确定对话框
JButton okBtn = new JButton("确定");
okBtn.setBounds(200, 70, 90, 30);
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 关闭对话框
dialog.dispose();
//调用打印机进行打印
QrPrint pt = new QrPrint();
System.out.println(Integer.parseInt(textField_print.getText()));
for(int i=0;i<Integer.parseInt(textField_print.getText());i++) {
//刷新组件
if(isLegalDate(textField_date.getText())) {
date = textField_date.getText(); // 日期
year = DICTIONARY.get(date.split("-")[0]); // 年份
month = DICTIONARY.get(date.split("-")[1]); // 月份
day = date.split("-")[2]; // 天
}
String factoryCode = (String) comboBox_factory.getSelectedItem(); // 制造商代码
String classNum = (String) comboBox_class.getSelectedItem(); // 班次
int x= Integer.parseInt(textField_serial.getText())+i;
String serialNum = "0000000" + x;
serialNum = serialNum.substring(serialNum.length() - 7); // 处理之后的流水号
String lbj = (String) comboBox_serial.getSelectedItem(); // 零部件号
// 拼接的二维码所显示的字符串
String qrText = new StringBuilder().append(factoryCode).append(year).append(month).append(day)
.append(classNum).append(serialNum).append("A").append(lbj).toString();
// 更新label
String line1 = new StringBuilder().append(factoryCode).toString();
String line2 = new StringBuilder().append(year).append(month).append(day).append(classNum).append(serialNum)
.append("A").toString();
String line3 = new StringBuilder().append(lbj).toString();
//将line参数写入文件
updateFile("src/config/line.txt", new HashMap<String, Object>(4) {
{
put("lineOne", line1);
put("lineTwo", line2);
put("lineThree", line3);
}
});
//移除组件
panel.remove(lineOne);
panel.remove(lineTwo);
panel.remove(lineThree);
lineOne = new JLabel(line1);
lineTwo = new JLabel(line2);
lineThree = new JLabel(line3);
lineOne.setFont(new Font("黑体", Font.PLAIN, 19));
lineTwo.setFont(new Font("黑体", Font.PLAIN, 19));
lineThree.setFont(new Font("黑体", Font.PLAIN, 19));
lineOne.setBounds(165, 45, 174, 18);
lineTwo.setBounds(165, 76, 174, 18);
lineThree.setBounds(165, 107, 187, 18);
panel.add(lineOne);
panel.add(lineTwo);
panel.add(lineThree);
panel.add(lineTwo);
// 二维码
panel.remove(init); // 移除二维码
init = new QRCodeImage(qrText, 80); // 生成二维码
init.setBounds(360, 43, 85, 85);
init.setBackground(Color.WHITE); // 设置二维码背景
panel.add(init);
// 刷新组件
panel.repaint();
panel_print.repaint();
//打印
pt.isPrint();
}
if(true) {
//更新参数文件
updateFile(formPath, new HashMap<String, Object>(4) {
{
put("factoryCode", comboBox_factory.getSelectedIndex());
put("serialNum", Integer.parseInt(textField_serial.getText())+Integer.parseInt(textField_print.getText()));
put("classNum", comboBox_class.getSelectedIndex());
put("lbj", comboBox_serial.getSelectedIndex());
}
});
//刷新流水号
form = parseFile("src/config/form.txt");
rightTopPanel.remove(textField_serial);
textField_serial = new JTextField(form.get("serialNum").toString());
addLengthLimit(textField_serial, 7);
textField_serial.getDocument().addDocumentListener(new MyChangeListener());
textField_serial.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_serial.setBounds(218, 180, 224, 30);
textField_serial.setColumns(10);
rightTopPanel.add(textField_serial);
rightTopPanel.repaint();
refresh();
System.out.println("全部流程操作成功");
}else {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"打印失败",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
}
}
});
// 创建一个按钮用于关闭对话框
JButton cancelBtn = new JButton("取消");
cancelBtn.setBounds(300, 70, 90, 30);
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 关闭对话框
dialog.dispose();
}
});
// 创建对话框的内容面板, 在面板内可以根据自己的需要添加任何组件并做任意是布局
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(messageLabel);
panel.add(okBtn);
panel.add(cancelBtn);
// 设置对话框的内容面板
dialog.setContentPane(panel);
// 显示对话框
dialog.setVisible(true);
}
/* 设置默认打印机 */
void showDefaultPrintDialog(Frame owner, Component parentComponent) {
// 创建一个模态对话框
final JDialog dialog = new JDialog(owner, "配置默认打印机", true);
// 设置对话框的宽高
dialog.setSize(600, 160);
// 设置对话框大小不可改变
dialog.setResizable(false);
// 设置对话框相对显示的位置
dialog.setLocationRelativeTo(parentComponent);
//设置布局
dialog.getContentPane().setLayout(null);
// 创建一个标签显示消息内容
JLabel messageLabel = new JLabel("选择打印机");
messageLabel.setBounds(10, 0, 200, 50);
//打印机下拉列表
PrintService[] service = PrintServiceLookup.lookupPrintServices(null,null);
printService = new String[service.length];
for(int i=0;i<service.length;i++){
printService[i]=service[i].getName();
}
comboBox_print = new JComboBox(printService);
comboBox_print.setSelectedIndex((Integer)parseFile("src/config/printer.txt").get("printerIndex"));
comboBox_print.setFont(new Font("微软雅黑", Font.PLAIN, 17));
comboBox_print.setBounds(10, 60, 470, 30);
// 创建一个按钮用于确定对话框
JButton okBtn = new JButton("确定");
okBtn.setBounds(500, 60, 80, 30);
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//更新参数文件(将选择的打印机放置到表单参数中)
updateFile(printerPath, new HashMap<String, Object>(4) {
{
put("printer", comboBox_print.getSelectedItem());
put("printerIndex", comboBox_print.getSelectedIndex());
}
});
//关闭dialog
dialog.dispose();
}
});
// 创建对话框的内容面板, 在面板内可以根据自己的需要添加任何组件并做任意是布局
JPanel panel1 = new JPanel();
panel1.setLayout(null);
panel1.add(messageLabel);
panel1.add(okBtn);
panel1.add(comboBox_print);
// 设置对话框的内容面板
dialog.setContentPane(panel1);
// 显示对话框
dialog.setVisible(true);
}
/* 校验密码 */
void checkPwd(Frame owner, Component parentComponent ,String key) {
// 创建一个模态对话框
final JDialog dialog = new JDialog(owner, "请输入密码", true);
// 设置对话框的宽高
dialog.setSize(600, 160);
// 设置对话框大小不可改变
dialog.setResizable(false);
// 设置对话框相对显示的位置
dialog.setLocationRelativeTo(parentComponent);
//设置布局
dialog.getContentPane().setLayout(null);
// 创建一个标签显示消息内容
JLabel messageLabel = new JLabel("输入密码 : ");
messageLabel.setBounds(10, 30, 200, 50);
//密码输入框
textField_pwd = new JPasswordField ();
textField_pwd.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_pwd.setBounds(100, 40, 350, 30);
// 创建一个按钮用于确定对话框
JButton okBtn = new JButton("确定");
okBtn.setBounds(500, 40, 80, 30);
okBtn.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
//获取密码
String pwd = parseFile(pwdPath).get("pwd").toString();
if(textField_pwd.getText().equals(pwd)) {
System.out.println("密码正确");
//关闭dialog
dialog.dispose();
//判断打开什么文件
File f=new File("");
if(key.equals("lbj")) {
f=new File(lbjPath);
}
if(key.equals("factory")) {
f=new File(factoryPath);
}
if(key.equals("class")) {
f=new File(bcPath);
}
try {
if(f.exists()) {
Desktop.getDesktop().open(f);
}else {
System.out.println("文件不存在,,无法打开");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(key.equals("pwd")) {
System.out.println("进入修改旧密码");
final JFrame jf = new JFrame("校验密码");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
changePwd(jf, jf);
}
}else {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"密码错误",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
//密码错误后置为空
textField_pwd.setText("");
}
}
});
// 创建对话框的内容面板, 在面板内可以根据自己的需要添加任何组件并做任意是布局
JPanel panel1 = new JPanel();
panel1.setLayout(null);
panel1.add(messageLabel);
panel1.add(okBtn);
panel1.add(textField_pwd);
// 设置对话框的内容面板
dialog.setContentPane(panel1);
// 显示对话框
dialog.setVisible(true);
}
/* 修改密码 */
void changePwd(Frame owner, Component parentComponent) {
final JDialog dialog = new JDialog(owner, "请输入密码", true);
dialog.setSize(600, 200);
dialog.setResizable(false);
dialog.setLocationRelativeTo(parentComponent);
dialog.getContentPane().setLayout(null);
JLabel messageLabel1 = new JLabel("输入新密码 : ");
messageLabel1.setBounds(10, 20, 200, 50);
JLabel messageLabel2 = new JLabel("确认新密码 : ");
messageLabel2.setBounds(10, 70, 200, 50);
//密码输入框
JTextField textField_newPwd1 = new JTextField();
textField_newPwd1.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_newPwd1.setBounds(130, 30, 370, 30);
//密码输入框
JTextField textField_newPwd2 = new JTextField ();
textField_newPwd2.setFont(new Font("微软雅黑", Font.PLAIN, 17));
textField_newPwd2.setBounds(130, 80, 370, 30);
// 创建一个按钮用于确定对话框
JButton okBtn = new JButton("确定");
okBtn.setBounds(480, 120, 100, 30);
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取密码
String pwd = parseFile(pwdPath).get("pwd").toString();
//判断两次输入密码是否相同
if(textField_newPwd1.getText().toString().equals(textField_newPwd2.getText().toString())) {
System.out.println("新密码与旧密码相同");
//关闭dialog
dialog.dispose();
updateFile(pwdPath, new HashMap<String, Object>(1) {
{
put("pwd", textField_newPwd1.getText().toString());
}
});
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"修改密码成功",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
}else {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"两次输入密码布不一致",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
}
}
});
// 创建对话框的内容面板, 在面板内可以根据自己的需要添加任何组件并做任意是布局
JPanel panel1 = new JPanel();
panel1.setLayout(null);
panel1.add(messageLabel1);
panel1.add(messageLabel2);
panel1.add(okBtn);
panel1.add(textField_newPwd1);
panel1.add(textField_newPwd2);
// 设置对话框的内容面板
dialog.setContentPane(panel1);
// 显示对话框
dialog.setVisible(true);
}
/**
* 方法区
*/
/* 校验表单 */
boolean isFull() {
String date = textField_date.getText(); // 日期
String factoryCode = (String) comboBox_factory.getSelectedItem(); // 制造商代码
String classNum = (String) comboBox_class.getSelectedItem(); // 班次
String serialNum1 = textField_serial.getText();
String lbj = (String) comboBox_serial.getSelectedItem(); // 零部件号
String print = textField_print.getText();
//判断表单是否为空:日期,制造商代码,班次号,序列号,零部件号,打印数量
if("".equals(date)||"".equals(factoryCode)||"".equals(classNum)||"".equals(serialNum1)||"".equals(lbj)||"".equals(print)) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"请将参数填写完整",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
return false;
}else {
//判断是否含有中文: 日期,制造商代码,班次号,流水号,零部件,打印数量
if(isChineseChar(date)||isChineseChar(factoryCode)||isChineseChar(classNum)||isChineseChar(serialNum1)||isChineseChar(lbj)||isChineseChar(print)) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"参数中含有中文",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
return false;
}else {
//判断时间格式
if(!isLegalDate(textField_date.getText())) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"时间格式不正确(yyyy-mm-dd)",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
return false;
}else {
//判断打印数量,以及流水号是否为数字
if(!isInteger(textField_serial.getText())||!isInteger(textField_print.getText())) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"参数有误",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
return false;
}else {
//判断制造商代码是否为5位
if(factoryCode.length()!=5) {
final JFrame jf = new JFrame("警告");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(
jf,
"制造商代码有误",
"提示",
JOptionPane.INFORMATION_MESSAGE
);
return false;
}else {
return true;
}
}
}
}
}
}
// 封装文本
void refresh() {
System.out.println("刷新组件");
// 获取表单
try {
if(isLegalDate(textField_date.getText())) {
date = textField_date.getText(); // 日期
year = DICTIONARY.get(date.split("-")[0]); // 年份
month = DICTIONARY.get(date.split("-")[1]); // 月份
day = date.split("-")[2]; // 天
}
String factoryCode = (String) comboBox_factory.getSelectedItem(); // 制造商代码
String classNum = (String) comboBox_class.getSelectedItem(); // 班次
String serialNum = "0000000" + textField_serial.getText();
serialNum = serialNum.substring(serialNum.length() - 7); // 处理之后的流水号
String lbj = (String) comboBox_serial.getSelectedItem(); // 零部件号
// 拼接的二维码所显示的字符串
String qrText = new StringBuilder().append(factoryCode).append(year).append(month).append(day)
.append(classNum).append(serialNum).append("A").append(lbj).toString();
// 更新label
String line1 = new StringBuilder().append(factoryCode).toString();
String line2 = new StringBuilder().append(year).append(month).append(day).append(classNum).append(serialNum)
.append("A").toString();
String line3 = new StringBuilder().append(lbj).toString();
//移除组件
panel.remove(lineOne);
panel.remove(lineTwo);
panel.remove(lineThree);
lineOne = new JLabel(line1);
lineTwo = new JLabel(line2);
lineThree = new JLabel(line3);
lineOne.setFont(new Font("黑体", Font.PLAIN, 19));
lineTwo.setFont(new Font("黑体", Font.PLAIN, 19));
lineThree.setFont(new Font("黑体", Font.PLAIN, 19));
lineOne.setBounds(165, 45, 174, 18);
lineTwo.setBounds(165, 76, 174, 18);
lineThree.setBounds(165, 107, 187, 18);
panel.add(lineOne);
panel.add(lineTwo);
panel.add(lineThree);
panel.add(lineTwo);
// 二维码
panel.remove(init); // 移除二维码
init = new QRCodeImage(qrText, 80); // 生成二维码
init.setBounds(360, 43, 85, 85);
init.setBackground(Color.WHITE); // 设置二维码背景
panel.add(init);
// 刷新组件
panel.repaint();
panel_print.repaint();
} catch (Exception e) {
// TODO: handle exception
System.out.println("出错了" + e);
}
}
// 监听表单
class MyChangeListener implements DocumentListener {
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
System.out.println("更新事件");
refresh();
}
@Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
System.out.println("插入事件");
refresh();
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
System.out.println("删除事件");
// 获取表单
refresh();
}
}
// 限制输入长度
void addLengthLimit(JTextComponent component, int max) {
//refresh();
component.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
String s = component.getText();
if (s.length() >= max) {
e.consume();
}
}
@Override
public void keyPressed(KeyEvent e) {
// do nothing
refresh();
}
@Override
public void keyReleased(KeyEvent e) {
// do nothingvvv
refresh();
}
});
}
/* 输入框格式化(只能输入数字) */
class NumberTextField extends PlainDocument {
public NumberTextField() {
super();
}
public void insertString(int offset, String str, AttributeSet attr) throws javax.swing.text.BadLocationException {
if (str == null) {
return;
}
char[] s = str.toCharArray();
int length = 0;
// 过滤非数字
for (int i = 0; i < s.length; i++) {
if ((s[i] >= '0') && (s[i] <= '9')) {
s[length++] = s[i];
}
// 插入内容
super.insertString(offset, new String(s, 0, length), attr);
refresh();
}
}
}
//检测是否为数字
boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
//检测是否输入中文
public static boolean isChineseChar(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
/**
* 统一设置字体,父界面设置之后,所有由父界面进入的子界面都不需要再次设置字体
*/
private static void InitGlobalFont(Font font) {
FontUIResource fontRes = new FontUIResource(font);
for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
UIManager.put(key, fontRes);
}
}
}
/* 格式化时间 */
public static String dateToString(Date date) {
SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
String time = sformat.format(date);
return time;
}
/* 读取文件 */
public static String[] readTxtFile(String filePath) {
try {
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到文件编码问题
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
List<String> list = new LinkedList<>();
while ((lineTxt = bufferedReader.readLine()) != null) {
// System.out.println(lineTxt);
if (!lineTxt.trim().equals("")) {
list.add(lineTxt);
}
}
System.out.println(list.size());
read.close();
return list.toArray(new String[list.size()]);
} else {
System.out.println("找不到指定文件");
}
} catch (Exception e) {
System.out.println("文件内容读取错误");
e.printStackTrace();
}
return new String[] { "" };
}
/* 读文件(json) */
public static Map<String, Object> parseFile(String path) {
try {
File file = new File(path);
if (file.isFile() && file.exists() && file.canRead()) {
String encoding = "GBK";
InputStreamReader in;
in = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(in);
String lineTxt = "";
StringBuilder sb = new StringBuilder(lineTxt);
while ((lineTxt = bufferedReader.readLine()) != null) {
if (!lineTxt.trim().equals("")) {
sb.append(lineTxt);
}
}
lineTxt = sb.toString();
in.close();
return JSON.parseObject(lineTxt);
}else {
System.out.println("找不到指定文件");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/* 写入文件使用map */
public static void updateFile(String path, Map<String, Object> newContent) {
try {
File file = new File(path);
if (file.isFile() && file.canRead() && file.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
// 一次写一行
bw.write(JSON.toJSONString(newContent));
bw.newLine(); // 换行用
// 关闭流
bw.close();
}else {
System.out.println("文件新建成功");
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
// 一次写一行
bw.write(JSON.toJSONString(newContent));
bw.newLine(); // 换行用
// 关闭流
bw.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 写入文件
void write(String path, String str) throws IOException {
// 将写入转化为流的形式
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
// 一次写一行
bw.write(str);
bw.newLine(); // 换行用
// 关闭流
bw.close();
System.out.println("写入成功");
}
/* 判断时间格式 */
private static boolean isLegalDate(String sDate) {
int legalLen = 10;
if ((sDate == null) || (sDate.length() != legalLen)) {
return false;
}
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = formatter.parse(sDate);
return sDate.equals(formatter.format(date));
} catch (Exception e) {
return false;
}
}
/**
* main
*/
public static void main(String[] args) {
//获取form.txt中记录的表单值
form = parseFile("src/config/form.txt");
setForm = parseFile("src/config/setting.txt");
EventQueue.invokeLater(new Runnable() { public void run() {
try {
PrintMain frame = new PrintMain();
frame.setVisible(true);
InitGlobalFont(new Font(null, Font.PLAIN, 18));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}