如何在JLabel或JPanel中显示缓冲图像?

时间:2017-01-22 12:40:53

标签: java image swing jframe jlabel

我有JFrame JLabel label1,但我不能让它显示图像。每当另一个类调用showScreenShot()时,如何在标签中显示更新的缓冲图像?

我正在使用Eclipse WindowBuilder。

以下是代码:

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();
    }
}

1 个答案:

答案 0 :(得分:2)

这至少在两个不同的层面上是错误的:

label1.getGraphics().drawImage(img, 0, 0, label1.getWidth(), label1.getHeight(), null);
  1. 不要在组件上调用getGraphics()。对组件的更改将是短暂的,因为Swing组件需要在告知时自行绘制。
  2. 不要使用null作为图像观察者。 AWT / Swing中的每个组件都实现ImageObserver
  3. 改为使用:

    label1.setIcon(new ImageIcon(img));