我有问题。单击我的按钮后,将jTable添加到PDF并保存后,表格消失,当我清除它时,表格变大并破坏UI。 MainTable1是我的UI上存在的表。
以下是代码:
String path = "";
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath();
getContentPane().setLayout(new BorderLayout());
JTable table = mainTable1;
JPanel tPanel = new JPanel(new BorderLayout());
tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
tPanel.add(table, BorderLayout.CENTER);
getContentPane().add(tPanel, BorderLayout.CENTER);
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfWriter writer;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(500, 500);
Graphics2D g2;
g2 = tp.createGraphicsShapes(500, 500);
table.print(g2);
g2.dispose();
cb.addTemplate(tp, 30, 300);
document.close();
tableToPDFButton.setEnabled(false);
} catch (FileNotFoundException | DocumentException ex) {
Logger.getLogger(HealthApplicationUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:0)
保存后,表格消失
JTable table = mainTable1;
JPanel tPanel = new JPanel(new BorderLayout());
tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
tPanel.add(table, BorderLayout.CENTER);
Swing组件只能有一个父级。在我看来,你正在将桌子从一个GUI移动到另一个GUI。
如果要复制表,请使用TableModel创建第二个表:
JTable table = new JTable( mainTable1.getModel() );