how to print selected rows JTable
我尝试使用 Main JTable 的选定行以及相同的头部和单元格渲染来做一个临时 JTable,但是当我尝试打印它时,我只得到一个带有线条边框的空矩形,我在如何打印中看到JTable 的特定行/列?另一种使用矩形和单元格边界的方法,但我不明白,我需要一些帮助以使其更清晰
对我来说似乎工作正常...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.PrinterException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; public class TestPrint { public static void main(String[] args) { new TestPrint(); } public TestPrint() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } DefaultTableModel model = new DefaultTableModel(0, 26); for (int row = 0; row < 26; row++) { Vector data = new Vector(26); for (int col = 0; col < 26; col++) { String value = row +"x" + ((char) (col + 'A')); data.add(value); } model.addRow(data); } JTable table = new JTable(model); JButton print = new JButton("Print"); print.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { DefaultTableModel viewModel = (DefaultTableModel) table.getModel(); DefaultTableModel printModel = new DefaultTableModel(0, viewModel.getColumnCount()); for (int row : table.getSelectedRows()) { printModel.addRow((Vector) viewModel.getDataVector().get(row)); } JTable toPrint = new JTable(printModel); toPrint.setSize(toPrint.getPreferredSize()); JTableHeader tableHeader = toPrint.getTableHeader(); tableHeader.setSize(tableHeader.getPreferredSize()); toPrint.print(JTable.PrintMode.FIT_WIDTH); } catch (PrinterException ex) { ex.printStackTrace(); } } }); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new JScrollPane(table)); frame.add(print, BorderLayout.SOUTH); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } |