package com.mes.component; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; public class QRCodeDialog extends JDialog { private static final int QR_CODE_SIZE = 400; // 二维码尺寸 public QRCodeDialog(JFrame owner, String title, String content){ super(owner, title, true); init(content, owner); } private void init(String content, JFrame owner){ Container container = this.getContentPane(); container.setLayout(new BorderLayout()); container.setBackground(Color.WHITE); // 生成二维码图片 BufferedImage qrImage = generateQRCode(content); if(qrImage != null){ // 显示二维码 JLabel imageLabel = new JLabel(new ImageIcon(qrImage)); imageLabel.setHorizontalAlignment(SwingConstants.CENTER); container.add(imageLabel, BorderLayout.CENTER); // 显示文本内容 JLabel textLabel = new JLabel(content); textLabel.setHorizontalAlignment(SwingConstants.CENTER); textLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18)); textLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); container.add(textLabel, BorderLayout.SOUTH); }else{ // 如果生成失败,显示错误信息 JLabel errorLabel = new JLabel("二维码生成失败"); errorLabel.setHorizontalAlignment(SwingConstants.CENTER); errorLabel.setForeground(Color.RED); errorLabel.setFont(new Font("微软雅黑", Font.PLAIN, 24)); container.add(errorLabel, BorderLayout.CENTER); } this.setSize(QR_CODE_SIZE + 50, QR_CODE_SIZE + 100); this.setLocationRelativeTo(owner); this.setResizable(false); this.setVisible(true); } /** * 生成二维码图片 * @param content 二维码内容 * @return BufferedImage */ private BufferedImage generateQRCode(String content) { try { // 设置二维码参数 Map hints = new HashMap<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错级别 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 字符编码 hints.put(EncodeHintType.MARGIN, 1); // 边距 // 生成二维码矩阵 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hints); // 转换为图片 BufferedImage image = new BufferedImage(QR_CODE_SIZE, QR_CODE_SIZE, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < QR_CODE_SIZE; x++) { for (int y = 0; y < QR_CODE_SIZE; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; } catch (WriterException e) { e.printStackTrace(); return null; } } }