1

I would like to do some drawing into a large BufferedImage and later show that in a JFrame with a JScrollPane. I tried the following approach

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class FrameImage {
    private static void createAndShowGUI() {
       BufferedImage image;
       Graphics bufG;
       JFrame frame;
       JPanel panel;
       JLabel picLabel;

       frame = new JFrame("FrameTest");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       image=new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
       bufG=image.createGraphics();
       bufG.setColor(Color.red);
       bufG.drawString("Testing",100,100);

       panel = new JPanel();
       panel.setBackground(Color.BLUE);
       panel.setPreferredSize(new Dimension(1500, 1500));
       panel.setLayout(null);
       picLabel = new JLabel(new ImageIcon(image));
       panel.add(picLabel);

       frame.add(new JScrollPane(panel));
       frame.setVisible(true);
       frame.setSize(800, 500);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

But the text "Testing" does not show up in my JFrame. What am I missing here?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174

1 Answers1

3

If I comment out the line

panel.setLayout(null);

I see your JLabel with the image show up. You will need to play around with the layout to get it to show up.

skynet
  • 9,898
  • 5
  • 43
  • 52
  • 1
    OP - In addition to the excellent advice above. Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Oct 26 '13 at 23:13
  • Disagree - dependent on requirements. Layout managers are only useful when you want your UI to be flexible and take up all the space made available. If you're designing a GUI meant to stay a fixed dimension (maybe it's too complex to bother with dynamic layouts) or your UI is already compressed to take up as little space as possible (and no more), layouts offer nothing AFAIK. Using a manager to position a few control panels is fine but with a quite complex UI, at some point you're usually better off sticking to absolute positions. Admittedly, the LAF issue is a major exception to this. – Manius Dec 24 '13 at 23:43