新功能
打开和保存是序列化与反序列化
保存bmp图片
打印
待加入功能
条形码
二维码
问题:如何调它的参数? 比如宽度高度 位置 类型 内容
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import java.util.ArrayList;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PageFormat;
public class LabelDesignTool extends JFrame {
private LabelData labelData=new LabelData();
private ImagePanel imagePanel;
private boolean addTextMode = false; // 标记是否处于添加文字模式
private transient Clipboard clipboard;
private JButton addTextButton;
private boolean EnableAuxiliary=true; //辅助显示
// 设置字体样式、大小和样式
private Font font = new Font("黑体", Font.BOLD, 48);
public LabelDesignTool() {
super("标签设计工具V1.1 (点击复制坐标。添加文字,鼠标左键添加文字,右键删选中的文字,按加减键改字体大小)QQ345139427");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
clipboard= Toolkit.getDefaultToolkit().getSystemClipboard(); // 获取系统剪贴板
initUI();
}
private void initUI() {
imagePanel = new ImagePanel();
JScrollPane scrollPane = new JScrollPane(imagePanel);
add(scrollPane, BorderLayout.CENTER);
JToolBar toolBar = new JToolBar();
JButton openItem = new JButton("打开");
toolBar.add(openItem);
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// 设置默认打开路径为当前工作目录
fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("LabelDatas", "ld"));
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
try {
FileInputStream fileIn = new FileInputStream(fileChooser.getSelectedFile());
ObjectInputStream in = new ObjectInputStream(fileIn);
labelData = (LabelData) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("LabelData class not found");
c.printStackTrace();
return;
}
try {
if(labelData.imagePath!=null) {
setExtendedState(JFrame.MAXIMIZED_BOTH); // Set the window to open maximized
labelData.image = ImageIO.read(labelData.imagePath);
imagePanel.setImage(labelData.image);
}
System.out.println("Deserialized LabelData:");
System.out.println("Texts Size: " + labelData.texts.size());
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
});
JButton saveItem = new JButton("保存");
toolBar.add(saveItem);
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
FileOutputStream fileOut = new FileOutputStream("LabelData.ld");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(labelData);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in LabelData.ld");
} catch (IOException i) {
i.printStackTrace();
}
}
});
JButton loadImageButton = new JButton("加载模板");
loadImageButton.addActionListener(e -> loadImage());
toolBar.add(loadImageButton);
addTextButton = new JButton("添加文字");
addTextButton.addActionListener(e -> {addTextMode = !addTextMode;
if(addTextMode){ addTextButton.setText("文字:"+font.getSize());}else{addTextButton.setText("添加文字");}
setFocusable(true); // Ensure the panel can receive focus 按键才有效
requestFocus(); // Request focus for the panel // 切换添加文字模式
});
toolBar.add(addTextButton);
// Add a button to save ImagePanel as a BMP image
JButton saveImageButton = new JButton("保存为BMP");
saveImageButton.addActionListener(e -> saveImage());
toolBar.add(saveImageButton);
// Add a button to print ImagePanel
JButton printImageButton = new JButton("打印");
printImageButton.addActionListener(e -> printImage());
toolBar.add(printImageButton);
add(toolBar, BorderLayout.NORTH);
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
if (keyChar == '+' || keyChar == '=') {
font = new Font("黑体", Font.BOLD, font.getSize() + 1);
addTextButton.setText("文字:" + font.getSize());
repaint();
} else if (keyChar == '-' || keyChar == '_') {
font = new Font("黑体", Font.BOLD, font.getSize() - 1);
addTextButton.setText("文字:" + font.getSize());
repaint();
}
}
});
}
// Method to save ImagePanel as a BMP image
private void saveImage() {
EnableAuxiliary=false;
repaint();
if(labelData.image!=null)
imagePanel.setSize(labelData.image.getWidth(),labelData.image.getHeight());
BufferedImage imageToSave = new BufferedImage(imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.TYPE_INT_RGB);//模板大小
Graphics2D graphics2D = imageToSave.createGraphics();
imagePanel.paint(graphics2D);
try {
ImageIO.write(imageToSave, "bmp", new File("image.bmp"));
} catch (IOException e) {
e.printStackTrace();
}
EnableAuxiliary=true;
}
// Method to print ImagePanel
private void printImage() {
try {
saveImage();
// 加载BMP图片
File bmpFile = new File("image.bmp");
// 将图片写入到ByteArrayOutputStream
FileInputStream fis = new FileInputStream(bmpFile);
// 创建打印数据
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
Doc doc = new SimpleDoc(fis, flavor, null);
// 查找默认的打印服务
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// 创建打印任务
DocPrintJob job = printService.createPrintJob();
// 创建打印属性集合
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1)); // 设置打印份数
if(labelData.image!=null)
pras.add(new MediaPrintableArea(0, 0, (int)(labelData.image.getWidth()*25.4/600), (int)(labelData.image.getHeight()*25.4/600), MediaPrintableArea.MM)); // 设置打印区域为左上角对齐
// 执行打印操作
job.print(doc, pras);
fis.close(); // 关闭文件输入流
System.out.println("打印完成。");
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadImage() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("BMP Images", "bmp"));
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
setExtendedState(JFrame.MAXIMIZED_BOTH); // Set the window to open maximized
labelData.image = ImageIO.read(labelData.imagePath=fileChooser.getSelectedFile());
imagePanel.setImage(labelData.image);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ImagePanel extends JPanel implements Printable {
private Point mousePoint = new Point(0, 0);
@Override
public Dimension getPreferredSize() {
if (labelData.image != null) {
return new Dimension(labelData.image.getWidth(), labelData.image.getHeight());
} else {
return super.getPreferredSize();
}
}
public void setImage(BufferedImage img) {
labelData.image = img;
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
setSize(img.getWidth(), img.getHeight());
repaint();
}
public ImagePanel() {
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
//System.out.println("mouseMoved");
mousePoint = e.getPoint();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("mouseDragged");
//if (!addTextMode) {
mousePoint = e.getPoint();
// 拖动文字
for (TextItem text : labelData.texts) {
if (text.isDragging) {
text.x = e.getX();
text.y = e.getY();
}
}
repaint();
// }
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
//if (!addTextMode) {
// 检查是否点击了文字
for (TextItem text : labelData.texts) {
if (text.contains(mousePoint)) {
text.isDragging = true;
}
}
// }
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked");
if (SwingUtilities.isLeftMouseButton(e)) {
// Add text when left mouse button is clicked
if (addTextMode) {
labelData.texts.add(new TextItem(mousePoint.x, mousePoint.y, "F88888888888888", font));
repaint();
}
} else if (SwingUtilities.isRightMouseButton(e)) {
// Delete selected text when right mouse button is clicked
for (TextItem text : labelData.texts) {
if (text.contains(mousePoint)) {
labelData.texts.remove(text);
repaint();
break; // Exit loop after deleting one text item
}
}
}
// Save mouse coordinates to clipboard
String coordinates = mousePoint.x + ", " + mousePoint.y;
StringSelection selection = new StringSelection(coordinates);
clipboard.setContents(selection, null);
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
for (TextItem text : labelData.texts) {
text.isDragging = false;
}
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (labelData.image != null) {
g.drawImage(labelData.image, 0, 0, this);
}
//辅助线 及信息
if (EnableAuxiliary) {
g.setColor(Color.RED);
g.drawLine(mousePoint.x, 0, mousePoint.x, getHeight());
g.drawLine(0, mousePoint.y, getWidth(), mousePoint.y);
g.drawString("X: " + mousePoint.x + ", Y: " + mousePoint.y, mousePoint.x + 5, mousePoint.y - 5);
if (addTextMode) {
g.setFont(font);
g.drawString("F88888888888888", mousePoint.x, mousePoint.y+getFontMetrics(font).getHeight());
}
}
// 绘制所有的文字项
for (TextItem text : labelData.texts) {
g.setColor(Color.black);
g.setFont(text.font);
g.drawString(text.text, text.x, text.y+text.getHeight());
if(text.contains(mousePoint))
{
g.setColor(Color.RED);
g.drawRect(text.x,text.y,text.getWidth(),text.getHeight());
}
}
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// 计算打印区域的宽度和高度
double pageWidth = pageFormat.getImageableWidth();
double pageHeight = pageFormat.getImageableHeight();
// 获取ImagePanel中图像的宽度和高度
double imageWidth = labelData.image.getWidth(null);
double imageHeight = labelData.image.getHeight(null);
// 计算缩放比例
double scaleX = pageWidth / imageWidth;
double scaleY = pageHeight / imageHeight;
double scaleFactor = Math.min(scaleX, scaleY); // 选择较小的缩放比例以保持宽高比
// 根据缩放比例调整图像大小并绘制
AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
g2d.drawRenderedImage(labelData.image, at);
return PAGE_EXISTS;
}
}
class TextItem implements Serializable {
int x;
int y;
String text;
boolean isDragging;
Font font;
public TextItem(int x, int y, String text,Font font) {
this.x = x;
this.y = y;
this.text = text;
this.font=font;
}
public int getWidth()
{
return getFontMetrics(this.font).stringWidth(this.text);
}
public int getHeight()
{
return getFontMetrics(this.font).getHeight();
}
public boolean contains(Point point) {
return point.x >= x && point.x <= x + getWidth() && point.y >= y && point.y <= y + getHeight(); // 假设文字高度为20
}
}
class LabelData implements Serializable{
public transient BufferedImage image; //模板 暂时不序列化该字段
public File imagePath=null;
public ArrayList<TextItem> texts = new ArrayList<>(); // 存储所有的文字项
public Font font = new Font("黑体", Font.BOLD, 48);//当前字体
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LabelDesignTool tool = new LabelDesignTool();
tool.setVisible(true);
});
}
}