Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Do not call paintComponent() or paint() from the outside. Instead, let your image be created within those (overwritten) methods. Then you can be sure that your image will actually contain the painted content of the component. </p> <p>Here is an example application. The ImagePanel will actually grab the graphics contents of the component every time it is painted, which might be a bit wasteful, so you may want to adjust the frequency with which this is done.</p> <pre><code>public class SomeApp extends JFrame { private static class ImagePanel extends JPanel { private BufferedImage currentImage; public BufferedImage getCurrentImage() { return currentImage; } @Override public void paint(Graphics g) { Rectangle tempBounds = g.getClipBounds(); currentImage = new BufferedImage(tempBounds.width, tempBounds.height, BufferedImage.TYPE_INT_ARGB); super.paint(g); super.paint(currentImage.getGraphics()); } } public SomeApp() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setSize(800,600); int matrixSize = 4; setLayout(new BorderLayout()); add(new JLabel("Wonderful Application"), BorderLayout.NORTH); final ImagePanel imgPanel = new ImagePanel(); imgPanel.setLayout(new GridLayout(matrixSize,matrixSize)); for(int i=1; i&lt;=matrixSize*matrixSize; i++) { imgPanel.add(new JButton("A Button" + i)); } add(imgPanel, BorderLayout.CENTER); final JPanel buttonPanel = new JPanel(); buttonPanel.add(new JButton(new AbstractAction("get image") { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(SomeApp.this, new ImageIcon(imgPanel.getCurrentImage())); } })); add(buttonPanel, BorderLayout.SOUTH); } public static void main(String[] args) { System.setProperty("swing.defaultlaf", UIManager.getSystemLookAndFeelClassName()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SomeApp().setVisible(true); } }); } } </code></pre> <p>Like Martijn said, your image was probably black because the component wasn't even painted/displayed yet. You could add a ComponentListener to be notified when it is displayed. Your "solution" with getSubimage has nothing to do with the actual problem. I recommend you remove it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload