簡體   English   中英

如何在JLabel或JPanel中顯示緩沖的圖像?

[英]How to display buffered image in JLabel or JPanel?

我有帶有JLabel label1 JFrame ,但是我無法使其顯示圖像。 每次由另一個類調用showScreenShot()時, 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();
    }
}

在至少兩個不同級別上這是錯誤的:

label1.getGraphics().drawImage(img, 0, 0, label1.getWidth(), label1.getHeight(), null);
  1. 不要在組件上調用getGraphics() 組件的更改將是短暫的,因為Swing組件需要在需要時以及按照要求進行繪制。
  2. 不要使用null作為圖像觀察者。 AWT / Swing中的每個組件都實現ImageObserver

而是使用:

label1.setIcon(new ImageIcon(img));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM