-1

I have this JFrame with JLabel label1 but I cant make it display the image. How do I display the updated buffered image in the label every time the showScreenShot() is called by another class?

I'm using Eclipse WindowBuilder.

Here's the code:

public class TeacherDashBoard extends JFrame {

    private JPanel contentPane;
    private BufferedImage img;
    private static TeacherDashBoard frame;
    private static JLabel label1;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame = new TeacherDashBoard();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void showScreenShot(byte[] bytes) throws IOException {
        img = ImageIO.read(new ByteArrayInputStream(bytes));
        label1.getGraphics().drawImage(img, 0, 0, label1.getWidth(), label1.getHeight(), null);
    }

    public TeacherDashBoard() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 424);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        label1 = new JLabel();

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(29)
            .addComponent(label1, GroupLayout.PREFERRED_SIZE, 210, GroupLayout.PREFERRED_SIZE)
            .addContainerGap(591, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(96)
            .addComponent(label1, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
            .addContainerGap(333, Short.MAX_VALUE))
        );
        getContentPane().setLayout(layout);

        pack();
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

4

This is wrong on at least two different levels:

label1.getGraphics().drawImage(img, 0, 0, label1.getWidth(), label1.getHeight(), null);
  1. Don't call getGraphics() on components. The changes to the component will be ephemeral, as Swing components need to paint themselves when and as told to do so.
  2. Don't use null as the image observer. Every component in AWT/Swing implements ImageObserver.

Instead use:

label1.setIcon(new ImageIcon(img));
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433