【swing】常用内容总结

一、JComboBox

1.1、初始选中列表中某一项

1.1.1、普通JComboBox

String[] strList = { "V1.1", "V1.2", "V1.3", "V2.0" };
JComboBox<String> comBox = new JComboBox<String>(softVerList);
comBox.setSelectedIndex(2); // 方法一:列表下标,从0开始
comBox.setSelectedItem("V2.0"); // 方法二:指定列表值

1.1.2、Jtable里面JComboBox

// 指定单元格为下拉列表,并且指定初期値
int row = 1;
int col = 2
String[] strList = { "V1.1", "V1.2", "V1.3", "V2.0" };
table.getColumnModel().getColumn(col).setCellEditor(new DefaultCellEditor(new JComboBox<String>(strList)));
table.setValueAt("V2.0", row, col); // 直接设定值

二、Jtable

2.1、初始化

	String[][] data;
	String[] tiltes = { "序号", "序列号", "操作" };
	JTable table = new JTable() {
		private static final long serialVersionUID = 1L;
		@Override
		public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
			super.changeSelection(rowIndex, columnIndex, true, true);
			editCellAt(rowIndex, columnIndex);
			setRowSelectionInterval(rowIndex, rowIndex);
		}

		@Override
		public boolean editCellAt(int row, int column) {
			boolean result = super.editCellAt(row, column);
			final Component editor = getEditorComponent();

			if (editor != null && (editor instanceof JTextComponent || editor instanceof JComboBox)) {
				editor.requestFocusInWindow();
			}
			return result;
		}
	};
	DefaultTableModel model = new DefaultTableModel() {
		private static final long serialVersionUID = 1L;
		@Override
		public boolean isCellEditable(int row, int column) {
			// 【序号】列不可编辑
			if (column == 0) {
				return false;
			} else {
				return true;
			}
		}
	};
	table.setModel(model);
	table.setRowHeight(20);
	JScrollPane scrollPane = new JScrollPane(table);
	scrollPane.setBounds(20, 20, 1180, 225);

2.2、JTable加背景色

  1. 统一颜色
 	table.getTableHeader().setBackground(Color.BLUE);
  1. 单列设置颜色
	DefaultTableCellRenderer headerRenderer1 = new DefaultTableCellRenderer();
	headerRenderer1.setBackground(new Color(250, 218, 222));
	table.getColumnModel().getColumn(1).setHeaderRenderer(headerRenderer1);

2.3、禁止对列进行重新排序

	table.getTableHeader().setReorderingAllowed(false);

2.4、提交时失去焦点

	table.putClientProperty("terminateEditOnFocusLost", true);

2.5、动态修改表头

	model.setDataVector(data, tiltes);
	table.setModel(model);

2.6、动态添加行(单元格内添加下拉框、按钮)

	// 新增按钮监听器
	addBut.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			Vector<Object[]> dataVector = new Vector<Object[]>();
			int count = table.getRowCount();
			((DefaultTableModel) table.getModel()).addRow(dataVector);
			table.requestFocus();
			
			// 设置追加的行的序号
			table.setValueAt(count + 1, count, 0);

			// 下拉框
			table.getColumnModel().getColumn(7).setCellEditor(new DefaultCellEditor(editVerList()));
			
			// 删除按钮
			int deleteColumn = table.getModel().getColumnCount() - 1;
			table.getColumnModel().getColumn(deleteColumn).setCellRenderer(new ButtonRenderer());
			table.getColumnModel().getColumn(deleteColumn).setCellEditor(new TableCellDeleteButton());

			// 设置选中的行
			table.setRowSelectionInterval(count, count);
			// 设置光标的位置
			table.editCellAt(count, 1);
			// 显示最后一行
			table.scrollRectToVisible(table.getCellRect(count, 0, true));
		}
	});
	
	/**
	 * JTable 下拉框
	 */
	JComboBox<String> editSoftVerList() {
		DefaultComboBoxModel<String> softVerList = new DefaultComboBoxModel<String>();
		softVerList.addElement("V2.0");
		JComboBox<String> comBox = new JComboBox<String>(softVerList);
		comBox.addFocusListener(new FocusListener() {
			@Override
			public void focusLost(FocusEvent e) {
			}
			@Override
			public void focusGained(FocusEvent e) {
				comBox.showPopup();
			}
		});
		return comBox;
	}

	/**
	 * JTable 刪除按鈕渲染器
	 */
	public class ButtonRenderer extends JButton implements TableCellRenderer {
		private static final long serialVersionUID = 1L;
		public ButtonRenderer() {
			setOpaque(true);
		}
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
				int row, int column) {
			setText("删除");
			return this;
		}
	}

	/**
	 * JTable 刪除按鈕事件
	 */
	class TableCellDeleteButton extends DefaultCellEditor {
		private static final long serialVersionUID = 1L;
		private JButton deleteBut;

		public TableCellDeleteButton() {
			super(new JTextField());
			this.setClickCountToStart(1);
		}

		@Override
		public Component getTableCellEditorComponent(JTable taqble, Object value, boolean isSelected, int row,
				int colum) {
			deleteBut = new JButton("删除");
			deleteBut.setOpaque(true);
			deleteBut.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					// 解决 AWT-EventQueue-0
					fireEditingStopped();

					for (int i = row; i < table.getRowCount(); i++) {
						// 设置删除行后面行的序号
						table.setValueAt(i, i, 0);
					}
					model.removeRow(row);
				}
			});
			return deleteBut;
		}
	}

2.6、设置列居中

	DefaultTableCellRenderer render = new DefaultTableCellRenderer();// 设置监听器
	render.setHorizontalAlignment(SwingConstants.CENTER);
	table.getColumnModel().getColumn(0).setCellRenderer(render);

三、JTextPane

3.1、设置部分内容的颜色等

	textPane.setContentType("text/html"); // 使用html语言进行设置
	textPane.setText("<html>"
			+ "<body style='font-size: 9px;'>"
			+ "	使用说明:<br/>"
			+ "</body>"
			+ "</html>");

四、JTextField

4.1、边输入边改变大小写

	JTextField textField = new JTextField();
	textField.addKeyListener(new KeyListener() {
		@Override
		public void keyTyped(KeyEvent e) {
		}
		@Override
		public void keyPressed(KeyEvent e) {
		}
		@Override
		public void keyReleased(KeyEvent e) {
			int pos = textField.getCaretPosition();
			textField.setText(textField.getText().toUpperCase());
			textField.setCaretPosition(pos);
		}
	});

4.2、带有输入提示的 Java JTextField

// 使用方法
textField.setUI(new HintTextFieldUI("请填写8位", true, Color.GRAY));
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;

public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {

    private String hint;
    private boolean hideOnFocus;
    private Color color;

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
        repaint();
    }

    private void repaint() {
        if(getComponent() != null) {
            getComponent().repaint();          
        }
    }

    public boolean isHideOnFocus() {
        return hideOnFocus;
    }

    public void setHideOnFocus(boolean hideOnFocus) {
        this.hideOnFocus = hideOnFocus;
        repaint();
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
        repaint();
    }
    public HintTextFieldUI(String hint) {
        this(hint,false);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus) {
        this(hint,hideOnFocus, null);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
        this.hint = hint;
        this.hideOnFocus = hideOnFocus;
        this.color = color;
    }

    @Override
    protected void paintSafely(Graphics g) {
        super.paintSafely(g);
        JTextComponent comp = getComponent();
        if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
            if(color != null) {
                g.setColor(color);
            } else {
                g.setColor(comp.getForeground().brighter().brighter().brighter());              
            }
            int padding = (comp.getHeight() - comp.getFont().getSize())/2;
            g.drawString(hint, 2, comp.getHeight()-padding-1);          
        }
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(hideOnFocus) repaint();

    }

    @Override
    public void focusLost(FocusEvent e) {
        if(hideOnFocus) repaint();
    }
    @Override
    protected void installListeners() {
        super.installListeners();
        getComponent().addFocusListener(this);
    }
    @Override
    protected void uninstallListeners() {
        super.uninstallListeners();
        getComponent().removeFocusListener(this);
    }
}

五、导入导出(Excel、txt)

5.1、Excel

5.1.1、相关jar包

百度网盘 提取码: afuy

commons-collections4-4.4.jar
commons-compress-1.18.jar
poi-4.1.2.jar
poi-ooxml-4.1.2.jar
poi-ooxml-schemas-4.1.2.jar
xmlbeans-3.1.0.jar

5.1.2、模板导出

	templateBut.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			// 导出Excel文件
			JFileChooser fc = new JFileChooser();
			fc.setDialogTitle("请选择导出路径");
			fc.setSelectedFile(new File("导入模板"));
			fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
				public boolean accept(File f) { // 设定可用的文件的后缀名
					if (f.isDirectory()) {
						return true;
					}
					return false;
				}

				public String getDescription() {
					return ".xlsx";
				}
			});
			int result = fc.showSaveDialog(AuthApplyDialog.this);
			if (result != JFileChooser.APPROVE_OPTION) {
				return;
			}
			if (fc.getName(fc.getSelectedFile()).length() > 32) {
				JOptionPane.showMessageDialog(AuthApplyDialog.this, "文件名称不能大于32位!", "提示",
						JOptionPane.INFORMATION_MESSAGE);
				return;
			}

			// 创建工作簿对象
			XSSFWorkbook workbook = new XSSFWorkbook();
			// 创建工作表对象
			XSSFSheet sheet = workbook.createSheet("一览");
			String[] heads = { "姓名", "联系方式", "公司名称", "业务名称", "注册码", "操作系统版本", "设备名称" };

			// 设置共同格式
			XSSFCellStyle cellStyle = workbook.createCellStyle();
			for (int c = 0; c < heads.length; c++) {
				// 设置为文本格式
				XSSFFont font = workbook.createFont();
				font.setFontName("宋体");
				cellStyle.setFont(font);
				// 49为文本格式
				cellStyle.setDataFormat((short) 49);
				// c为列,一整列设置为文本格式
				sheet.setDefaultColumnStyle(c, cellStyle);
			}

			// 说明内容
			XSSFRow row = sheet.createRow(0);
			XSSFCell cell = row.createCell(0);
			cellStyle = workbook.createCellStyle();
			XSSFFont font = workbook.createFont();
			font.setFontName("宋体");
			font.setColor(XSSFFont.COLOR_RED);
			font.setBold(false);
			cellStyle.setFont(font);
			cellStyle.setDataFormat((short) 49);
			cell.setCellStyle(cellStyle);
			cell.setCellValue("*前四列是基本信息,同一个文件中必须统一!");

			// 列名
			cellStyle = workbook.createCellStyle();
			font = workbook.createFont();
			font.setFontName("宋体");
			font.setBold(true);
			cellStyle.setFont(font);
			cellStyle.setDataFormat((short) 49);
			row = sheet.createRow(1);
			for (int i = 0; i < heads.length; i++) {
				if (i == 0) {
					sheet.setColumnWidth(i, 12 * 256);
				} else if (i == 1 || i == 2) {
					sheet.setColumnWidth(i, 16 * 256);
				} else if (i == 3 || i == 6) {
					sheet.setColumnWidth(i, 10 * 256);
				} else if (i == 4) {
					sheet.setColumnWidth(i, 15 * 256);
				} else if (i == 5) {
					sheet.setColumnWidth(i, 15 * 256);
				}
				cell = row.createCell(i);
				cell.setCellStyle(cellStyle);
				cell.setCellValue(heads[i]);
			}

			FileOutputStream outputStream;
			try {
				outputStream = new FileOutputStream(fc.getSelectedFile().getAbsolutePath() + ".xlsx");
				workbook.write(outputStream);

				workbook.close();
				outputStream.close();
				JOptionPane.showMessageDialog(AuthApplyDialog.this, "模板导出成功!");
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(AuthApplyDialog.this, e1.getMessage());
				return;
			}
		}
	});

5.1.3、导入Excel

	// 批量导入按钮监听器
	importBut.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			JFileChooser fileChooser = new JFileChooser();
			int option = fileChooser.showDialog(AuthApplyDialog.this, "选择");
			if (option == JFileChooser.APPROVE_OPTION) {
				File file = fileChooser.getSelectedFile();
				osImport(file);
			}
		}
	});
	
	/**
	 * 读Excel内容
	 */
	private void osImport(File file) {
		String fileName = file.getAbsolutePath();
		if (fileName.endsWith(".xlsx")) {
			InputStream inputStream = null;
			try {
				inputStream = new FileInputStream(fileName);
				XSSFWorkbook xwb = new XSSFWorkbook(inputStream);
				XSSFSheet sheet = xwb.getSheet("一览");
				if (sheet == null) {
					JOptionPane.showMessageDialog(AuthApplyDialog.this, "excel文件中找不到此sheet:一览");
					return;
				}

				int rowStart = sheet.getFirstRowNum() + 2;
				int rowEnd = sheet.getPhysicalNumberOfRows() - 1;
				boolean isBasicSet = false;
				String ssr = "";
				String ssrTelNo = "";
				String ssrCompany = "";
				String businessName = "";
				List<EquipmentInfo> equipmentInfoList = new ArrayList<>();

				for (int rowNo = rowStart; rowNo <= rowEnd; rowNo++) {
					XSSFRow row = sheet.getRow(rowNo);
					if (row == null) {
						continue;
					}
					// 基本信息check与保存
					if (!isBasicSet) {
						// 姓名
						ssr = getCellValue(row.getCell(0));
						// 联系方式
						ssrTelNo = getCellValue(row.getCell(1));
						// 公司名称
						ssrCompany = getCellValue(row.getCell(2));
						// 业务名称
						businessName = getCellValue(row.getCell(3));
						isBasicSet = true;
					} else {
						// 实施人
						if (!ssr.equals(getCellValue(row.getCell(0)))) {
							JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入的【姓名】信息不统一!");
							return;
						}
						// 实施人联系方式
						if (!ssrTelNo.equals(getCellValue(row.getCell(1)))) {
							JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入的【联系方式】信息不统一!");
							return;
						}
						// 实施人公司名称
						if (!ssrCompany.equals(getCellValue(row.getCell(2)))) {
							JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入的【公司名称】信息不统一!");
							return;
						}
						// 业务名称
						if (!businessName.equals(getCellValue(row.getCell(3)))) {
							JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入的【业务名称】信息不统一!");
							return;
						}
					}

					EquipmentInfo equipmentInfo = new EquipmentInfo();
					equipmentInfo.setEquipmentId(getCellValue(row.getCell(4)));
					equipmentInfo.setOsVersion(getCellValue(row.getCell(5)));
					equipmentInfo.setDeviceName(getCellValue(row.getCell(6)));
					equipmentInfoList.add(equipmentInfo);
				}

				// 基本信息
				ssrName.setText(ssr);
				ssrTel.setText(ssrTelNo);
				ssrgsmc.setText(ssrCompany);
				businessSystem.setText(businessName);
				// 序列号信息
				for (EquipmentInfo equipmentInfo : equipmentInfoList) {
					Vector<Object[]> dataVector = new Vector<Object[]>();
					int count = table.getRowCount();
					((DefaultTableModel) table.getModel()).addRow(dataVector);
					table.requestFocus();
					table.setValueAt(count + 1, count, 0); // 设置追加的行的序号
					table.setValueAt(equipmentInfo.getEquipmentId(), count, 1); // 注册码
					table.setValueAt(equipmentInfo.getOsVersion(), count, 2); // 操作系统版本
					table.setValueAt(equipmentInfo.getDeviceName(), count, 3); // 设备名称

					// 删除按钮
					table.getColumnModel().getColumn(4).setCellRenderer(new ButtonRenderer());
					table.getColumnModel().getColumn(4).setCellEditor(new TableCellDeleteButton());

					// 设置选中的行
					table.setRowSelectionInterval(count, count);
					// 设置光标的位置
					table.editCellAt(count, 1);
					// 显示最后一行
					table.scrollRectToVisible(table.getCellRect(count, 0, true));
				}
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(AuthApplyDialog.this, e1.getMessage());
			} finally {
				try {
					if (inputStream != null) {
						inputStream.close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} else {
			JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入文件失败,仅支持xlsx类型的Excel文件导入!");
			return;
		}
	}

	/**
	 * 读Excel单元格内容
	 */
	private String getCellValue(XSSFCell cell) {
		return cell == null ? "" : cell.getStringCellValue();
	}

5.2、txt导入

	private void txtImport(File file) {
		String fileName = file.getAbsolutePath();
		if (fileName.endsWith(".txt")) {
			try {
				InputStream inputStream = new FileInputStream(fileName);
				byte[] head = new byte[3];
				inputStream.read(head);
				
				// 对应不同编码格式
				String charsetName = "GBK";// 或GB2312,即ANSI
				if (head[0] == -1 && head[1] == -2) {
					charsetName = "UTF-16";
				} else if (head[0] == -2 && head[1] == -1) { // 0xFEFF
					charsetName = "Unicode";// 包含两种编码格式:UCS2-Big-Endian和UCS2-Little-Endian
				} else if (head[0] == -27 && head[1] == -101 && head[2] == -98) {
					charsetName = "UTF-8"; // UTF-8(不含BOM)
				} else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
					charsetName = "UTF-8"; // UTF-8-BOM
				} else {
					byte[] text = new byte[(int) file.length()];
					System.arraycopy(head, 0, text, 0, 3);
					inputStream.read(text, 3, text.length - 3);
					for (int i = 0; i < text.length - 1; i++) {
						int a = text[i] & 0xFF;
						int b = text[i + 1] & 0xFF;
						if (a > 0x7F) {// 排除开头的英文或者数字字符
							if (0xE3 < a & a < 0xE9 && b > 0x7F && b < 0xC0) {// 符合utf8
								charsetName = "UTF-8";
								break;
							} else {
								break;
							}
						}
					}
				}

				inputStream.close();

				FileInputStream in = new FileInputStream(fileName);
				InputStreamReader inReader = new InputStreamReader(in, charsetName);
				BufferedReader bufReader = new BufferedReader(inReader);
				boolean haveDataFlg = false;
				String line = null;
				String importFileName = file.getName().substring(0, file.getName().length() - 4);
				while ((line = bufReader.readLine()) != null) {
					String str[] = line.split(",");
					if (str.length != 7) {
						bufReader.close();
						inReader.close();
						in.close();
						JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入文件失败,文件格式有误!");
						return;
					}
					haveDataFlg = true;
				}
				bufReader.close();
				inReader.close();
				in.close();
				if (!haveDataFlg) {
					JOptionPane.showMessageDialog(AuthApplyDialog.this, "文件内容为空!");
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			JOptionPane.showMessageDialog(AuthApplyDialog.this, "导入文件失败,仅支持txt文件导入!");
			return;
		}
	}

六、JTextArea

6.1、设置输入提示(通过FocusListener实现)

	String commnetHint = "请填写备注";
	JTextArea comment = new JTextArea(2, 200);
	comment.setLineWrap(true);
	// 设置边距
	comment.setMargin(new Insets(10, 10, 10, 10));
	// 设置边框颜色
	Border border = BorderFactory.createLineBorder(Color.GRAY);
	comment.setBorder(border);
	// 设置输入提示
	comment.addFocusListener(new FocusListener() {
		@Override
		public void focusLost(FocusEvent e) {
			if ("".equals(comment.getText())) {
				comment.setText(commnetHint);
				comment.setForeground(Color.GRAY);
			}
		}
		@Override
		public void focusGained(FocusEvent e) {
			if (commnetHint.equals(comment.getText())) {
				comment.setText("");
				comment.setForeground(Color.BLACK);
			}
		}
	});

七、读Xml

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class XMLDao {
	/**
	 * 获取当前可信软件版本下拉框初始值
	 * 
	 * @return
	 */
	public static List<String> getKXSoftVerList() {
		List<String> list = new ArrayList<String>();
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(new File("xml/SoftVerList.xml"));
			Element rootElement = document.getRootElement();
			for (Iterator<Element> it = rootElement.elementIterator(); it.hasNext();) {
		        Element element = it.next();
		        List<Node> list1 = element.content();
		        if (list1.size()>0) {
		        	list.add(list1.get(0).getText());
				}else {
					list.add(null);
				}
		    }
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return list;
	}
}

八、使用免安装数据库(org.sqlite.JDBC)

8.1、创建数据库

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils {
	private static final String DRIVER="org.sqlite.JDBC";
    private static final String URL="jdbc:sqlite:C:\\ProgramData\\TscPrinter\\TscPrinter.db";
    private static Connection conn=null;
    private static Statement statement = null;

    public static Statement getStatement(){
    	if (statement == null){
            try {
        		// 加载SQLite驱动程序
                Class.forName(DRIVER);
                // 创建目录
                File file = new File("C:\\ProgramData");
                if(!file.exists()){
                	file.mkdir();
                }
                file = new File("C:\\ProgramData\\TscPrinter");
                if(!file.exists()){
                	file.mkdir();
                }
        		// 创建数据库连接
                conn = DriverManager.getConnection(URL);
        		// 创建Statement对象
        		statement = conn.createStatement();
            } catch (Exception e) {
                e.printStackTrace();
            }
    	}
        return statement;
    }

    public static void closeAll(ResultSet resultSet) {
    	try {
    		if (resultSet != null) {
    			resultSet.close();
    		}
    		if (statement != null){
    			statement.close();
    		}
            if (conn != null){
            	conn.close();
            }
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }

    public static void closeAll() {
    	try {
    		if (statement != null){
    			statement.close();
    		}
            if (conn != null){
            	conn.close();
            }
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}

8.2、操作数据库

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import lombok.Data;

public class SQLiteExample {
	static Statement statement = null;
	static ResultSet resultSet = null;
	// 新增打印标签(注意:sql文中如果有单引号,需要使用双单引号,否则无效!)
	static String savePrintType = "INSERT INTO print_type (type, sort, labelwidth, labelheight) VALUES (''{0}'', {1}, ''{2}'', ''{3}'')";

	/**
	 * 打印种类list
	 * 
	 * @param sql
	 * @return
	 */
	public static List<PrintType> getPrintTypeList() {
		List<PrintType> printTypeList = new ArrayList<>();
		try {
			statement = JdbcUtils.getStatement();

			// 查询打印种类list
			String sqlCount = "select count(*) sum from print_type;";
			resultSet = statement.executeQuery(sqlCount);
			while (resultSet.next()) {
				if (resultSet.getInt("sum") == 0) {
					initTable();
				}
				String sqlList = "select * from print_type order by sort;";

				resultSet = statement.executeQuery(sqlList);
				while (resultSet.next()) {
					PrintType printType = new PrintType();
					printType.setType(resultSet.getString("type"));
					printType.setSort(resultSet.getInt("sort"));
					printType.setLabelwidth(resultSet.getString("labelwidth"));
					printType.setLabelheight(resultSet.getString("labelheight"));
					printTypeList.add(printType);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return printTypeList;
	}

	/**
	 * 创建表
	 * 
	 * @throws SQLException
	 */
	private static void createTable() throws SQLException {
		statement = JdbcUtils.getStatement();
		// 创建表
		String createTableSQL1 = "CREATE TABLE IF NOT EXISTS print_type (" + "type VARCHAR PRIMARY KEY NOT NULL, "
				+ "sort INTEGER NOT NULL, " + "labelwidth VARCHAR NOT NULL," + "labelheight VARCHAR NOT NULL)";
		statement.executeUpdate(createTableSQL1); // 打印种类
	}

	/**
	 * 初始化数据库
	 * 
	 * @throws SQLException
	 */
	private static void initTable() throws SQLException {
		statement = JdbcUtils.getStatement();
		String insertSQL = "";
		// print_type
		insertSQL = "INSERT INTO print_type (type, sort, labelwidth, labelheight) VALUES "
				+ "('小标签', 1, '67.5', '24.9')," + "('大标签', 3, '104', '80');";
		statement.executeUpdate(insertSQL);
	}

	public static String initDB() {
		statement = JdbcUtils.getStatement();
		String result = "数据库初始化成功!";
		try {
			statement.executeUpdate("drop table print_type;");
			createTable();
			initTable();
		} catch (SQLException e) {
			result = "数据库初始化失败!";
		}
		return result;
	}

	public static void closeJDBC() {
		JdbcUtils.closeAll(resultSet);
	}
}

/**
 * 打印种类
 */
@Data
class PrintType {

	private String type;
	private int sort;
	private String labelwidth;
	private String labelheight;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值