Home > Java > javaTutorial > body text

How to Capture the Table Header in a Rendered JTable Image?

Susan Sarandon
Release: 2024-11-07 18:04:02
Original
654 people have browsed it

How to Capture the Table Header in a Rendered JTable Image?

Capturing JTable Header in Rendered Image

Issue:

When capturing an image of a JTable, the table header does not appear in the resulting image.

原因:

The JTable header is not part of the hierarchy by the time the panel is painted to the image, as it has been removed when the JOptionPane was closed.

kleopatra's Solution:

  1. Add p.addNotify(); before creating the BufferedImage to add the header back to the hierarchy.
  2. Validate the panel with p.validate(); to force a recursive re-layout of all containers, ensuring that they believe they have a peer.

camickr's Solution:

  1. Use ScreenImage.createImage(p); to capture the image, which handles the header removal and addition.
  2. If using this method, set table.setPreferredScrollableViewportSize(table.getPreferredSize()); to prevent the JScrollPane from interfering with the rendering.

Updated Code:

...
// Without having been shown, fake a all-ready
p.addNotify();

// Manually size to preferred
p.setSize(p.getPreferredSize());

// Validate to force recursive doLayout of children
p.validate();

BufferedImage bi = new BufferedImage(p.getWidth(), p.getHeight(), BufferedImage.TYPE_INT_RGB);

Graphics g = bi.createGraphics();
p.paint(g);
g.dispose();
...
Copy after login

Conclusion:

Both solutions effectively render the JTable header in the resulting image. kleopatra's solution utilizes core J2SE, while camickr's leverages the ScreenImage API for additional functionality. The choice depends on the specific requirements of the application.

The above is the detailed content of How to Capture the Table Header in a Rendered JTable Image?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template