Reputation: 719
I want to use the print Method of a JTable. In a first approach everything works fine, table can be printed. But now I'd like to change some attributes like font and colors for the print out, but without changing the JTable on the screen. What is the best way to do this? Is there an easy way to create a copy of the existing table to adjust it's parameter and use the new table for printout ? :thinkingface:
thanks for any ideas! Thorsten
Upvotes: 1
Views: 77
Reputation: 4382
Instead of cloning just create a copy with shared model. Below is working example. You can edit values by double-clicking. Changes are reflected in both tables. In your case you should use 'clone' with modified styles for printing.
import javax.swing.*;
import java.awt.*;
public class CloningTablesExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(CloningTablesExample::runApp);
}
static void runApp(){
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setLayout(new GridLayout(2,1));
window.setSize(400, 300);
window.setVisible(true);
JTable original = new JTable(new Object[][]{
{"v1", "v2", "v3"},
{"v4", "v5", "v6"}
},
new String[]{"col1", "col2", "col3"}
);
JTable clone = cloneTable(original);
clone.setFont(clone.getFont().deriveFont(Font.BOLD));
window.getContentPane().add(new JScrollPane(original));
window.getContentPane().add(new JScrollPane(clone), BorderLayout.SOUTH);
}
private static JTable cloneTable(JTable original) {
JTable clone = new JTable();
clone.setModel(original.getModel());
return clone;
}
}
Upvotes: 1