程式無法存取擴充JPanel 類別的PaintComponent() 方法
在您的程式碼中,您已使用名為的新類別擴充了JPanel 類別繪製面板遠端控制。擴展類別有一個paintComponent()方法,它負責繪製面板的內容。但是,您沒有在程式碼中呼叫paintComponent()方法。
要解決此問題,您需要在DrawPanelRemoteControl類別的repaint()方法中呼叫paintComponent()方法。這將確保在需要刷新面板內容時呼叫paintComponent()方法。
以下是經過修復的修改後的程式碼:
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; repaint(); } }
以上是為什麼我的擴充 JPanel 類別中沒有呼叫 PaintComponent() 方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!