Итак, я немного изменил свой пользовательский класс canvas ( Cpanel
), и он больше не выдает ошибок (где, когда я пытался сохранить оба display
и ctx
в качестве собственных переменных, он выбросил Исключение NullPointerException
). И он ничего не отображает.
Почему он это делает?
Класс (кроме того, я исключаю некоторые методы, так что читать не так уж много):
/** * Calin Baenen's version of a canvas element. */ class CPane { // Debug variables. private boolean canCatch = true; // See if this canvas can still catch errors. private final JPanel canvas; // Canvas. private BufferedImage buffer; // Buffer. private final Graphics ctx; // Graphics. // Constructor. public CPane(int width, int height) { this(0, 0, width, height); } public CPane(int width, int height, Color initialColor) { this(0, 0, width, height, initialColor); } public CPane(int x, int y, int width, int height) { this(x, y, width, height, Color.WHITE); } public CPane(int x, int y, int width, int height, Color initialColor) { this(x, y, width, height, initialColor, Color.WHITE); } public CPane(int x, int y, int width, int height, Color initialColor, Color baseColor) { this.canvas = new JPanel(); // Make an element to display the drawing on. canvas.setBounds(x, y, width, height); // Set the bounds of the canvas. canvas.setBackground(baseColor); // Make the canvas white. canvas.setDoubleBuffered(true); // Make the canvas double buffered. buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // Set the buffer. ctx = buffer.getGraphics(); // Get the graphics for the buffer. // Paint the image with an initisl color. ctx.setColor(initialColor); // Set color. ctx.drawRect(0, 0, width, height); // Draw. } /** * Draws a rectangle to the screen by filling an area with color. */ public void drawRect(int x, int y, int width, int height, Color color) { ctx.setColor(color); // Set the context's color. ctx.fillRect(x, y, width, height); // Draw a rectangle. this.update(); // Update the canvas. } /** * Draw an image to the canvas. */ public void drawImage(Image image, int x, int y, int width, int height) { Image shot = image.getScaledInstance(width, height, Image.SCALE_FAST); // Get the scaled image to draw. ctx.drawImage(shot, x, y, null); // Draw the image. this.update(); // Update the canvas. } /** * Update the graphics, and log the error if it fails. */ public void update(boolean catcherror) { Graphics display = canvas.getGraphics(); // Get the canvas' display. try { display.drawImage(buffer, 0, 0, null); // Draw the buffer to the canvas. } catch(Exception error) { if(catcherror && canCatch) {Book.eog(error); canCatch = false;} // Log the error and disable error catching. } display.dispose(); // Dispose of the display. } }
Спасибо!Ваше здоровье!
Оригинал: “https://dev.to/baenencalin/why-doesn-t-my-custom-canvas-display-when-using-the-same-graphics-context-1f0g”