程式無法存取擴展JPanel 類別的PaintComponent() 方法
出現此問題的原因是DrawPanelRemoteControl 類別的PaintCompon(>出現此問題的原因是DrawPanelRemoteControl 類別的PaintComponent) 方法被調用。 PaintComponent() 方法負責繪製面板的內容,但在這種情況下,它不會被執行,因為 imageLabel 沒有被重新繪製。
要解決此問題,您需要確保 imageLabel 是每當 byteArray 更改時都會重新繪製。您可以透過呼叫 DrawPanelRemoteControl 類別的 setNewImageGrayscale() 方法中的 imageLabel.repaint() 方法來完成此操作。這將確保執行paintComponent()方法並繪製新影像。
這是DrawPanelRemoteControl類別的更新程式碼:
import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.MemoryImageSource; import java.awt.image.Raster; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; class DrawPanelRemoteControl extends JPanel { private byte[] byteArray=null; private Image image; private JLabel imageLabel=new JLabel(); private Dimension imageDimension; public DrawPanelRemoteControl(Dimension imageDimension) { this.imageDimension=imageDimension; add(imageLabel); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); System.out.println("."); if(byteArray!=null) { image=getGrayscaleImageFromArray(byteArray,imageDimension.width,imageDimension.height); imageLabel.setIcon(new ImageIcon(image)); } } private Image getGrayscaleImageFromArray(byte[] buffer, int width, int height) { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true,Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(width, height); DataBufferByte db = new DataBufferByte(buffer, width * height); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); return result; } void setNewImageGrayscale(byte[] array) { this.byteArray=array; this.intArray=null; imageLabel.repaint(); } }
透過呼叫imageLabel.repaint() setNewImageGrayscale(),您可以確保每當 byteArray 變更時都重新繪製 imageLabel。這將導致執行paintComponent()方法並繪製新影像。
以上是為什麼我的 JPanel 的 PaintComponent() 方法沒有被調用,我該如何修復它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!