Графика JPanel мерцает при использовании метода getGraphics () - PullRequest
0 голосов
/ 30 мая 2020

Я пытаюсь создать класс, похожий на знаменитую Processing, но вскоре я обнаружил проблему, так как в Processing есть функции setup () и draw (), в которых можно выполнять определенные функции, например, square (10,10,50), я попытался имитировать его, создав класс, в котором есть объект Graphics с именем "gfx", к которому добавляются различные фигуры. Если вы читаете этот папирус ... спасибо, и я поместил ниже класс PFrame (это тот, который имитирует обработку) и класс BohClass, который будет тестовым классом.

package PFrame.com;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PFrame {
    private JFrame frame = new JFrame();
    private DPane pane = new DPane(); //DPane is a class that extends JPanel

    private Graphics2D gfx;
    private Color selColor = new Color(255,255,255); //selected color
    private boolean fill = true; //the shapes are filled?

    public int width = 200, height = 200; //starting frame dimensins

    public PFrame() {
        //SKY
        pane.setPreferredSize(new Dimension(width,height));

        //HEAD
        title(); //this functions give to the frame the name of the class (in this case "BohClass")
        frame.setResizable(false);

        //BODY
        frame.add(pane);
        pane.addComponentListener(new ResizeListener());

        //TAIL
        size(width,height); //function that setting size
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gfx = (Graphics2D) pane.getGraphics();

        pane.paint(); //DPane function
    }

    //--|METHODS|--//
    //FRAME CONFIG
    public final void size(int x, int y) {
        width = x;
        height = y;
        pane.setPreferredSize(new Dimension(width,height));
        frame.pack();
        frame.setLocationRelativeTo(null);
        gfx = (Graphics2D) pane.getGraphics();
    }
    public final void exit() {
        System.exit(0);
    }
    public final void hide() {
        frame.setVisible(false);
    }
    public final void show() {
        frame.setVisible(true);
    }
    public final void location(int XY) {
        frame.setLocation(XY,XY);
    }
    public final void location(int X, int Y) {
        frame.setLocation(X,Y);
    }
    public final void title() {
        frame.setTitle((getClass() + "").split(" ")[1]);
    }
    public final void title(Object title) {
        frame.setTitle(title.toString());
    }
    public final void resizable() {
        frame.setResizable(!frame.isResizable());
    }
    public final void resizable(boolean resizable) {
        frame.setResizable(resizable);
    }

    //2D CONFIG
    public final void fill(boolean fill) {
        this.fill = fill;
    }
    public final void color(int RGB) {
        selColor = new Color(RGB,RGB,RGB);
    }
    public final void color(int R, int G, int B) {
        selColor = new Color(R,G,B);
    }

    //2D
    public final void square(int X, int Y, int L) {
        rect(X,Y,L,L);
    }
    public final void square(int X, int Y, int L, int A) {
        rect(X,Y,L,L,A);
    }
    public final void square(int X, int Y, int L, int Ax, int Ay) {
        rect(X,Y,L,L,Ax,Ay);
    }
    public final void rect(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRect(X, Y, W, H);
        else gfx.drawRect(X, Y, W, H);
    }
    public final void rect(int X, int Y, int W, int H,int A) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, A, A);
        else gfx.drawRoundRect(X, Y, W, H, A, A);
    }
    public final void rect(int X, int Y, int W, int H,int Ax, int Ay) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, Ax, Ay);
        else gfx.drawRoundRect(X, Y, W, H, Ax, Ay);
    }
    public final void circle(int X, int Y, int d) {
        ellipse(X,Y,d,d);
    }
    public final void ellipse(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillOval(X, Y, W, H);
        else gfx.drawOval(X, Y, W, H);
    }
    public final void triangle(int Ax, int Ay, int Bx, int By, int Cx, int Cy) {
        gfx.setColor(selColor);
        if(fill) gfx.fillPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
        else gfx.drawPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
    }

    //PANEL CONFIG
    public final void background(int RGB) {
        pane.setBackground(new Color(RGB,RGB,RGB));
    }
    public final void background(int R, int G, int B) {
        pane.setBackground(new Color(R,G,B));
    }
    public final void clear() {
        gfx.clearRect(0, 0, width, height);
    }

    //PUBLIC METHODS
    public void setup() {}
    public void loop() {}

    //PRIVATE CLASS PANEL
    private class DPane extends JPanel {
        private static final long serialVersionUID = 57423L;

        public void paint() {
            setup();

            while(true) {
                loop();
            }
        }
    }

    //LISTENERS
    class ResizeListener implements ComponentListener {
        public void componentResized(ComponentEvent e) {
            width = pane.getWidth();
            height = pane.getHeight();
        }
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public void componentHidden(ComponentEvent e) {}
    }
}

и ...

import PFrame.com.*;

public class BohClass extends PFrame {
    public void setup() {
        size(800,600);
        background(100);
    }
    public void loop() {
        color(72,28,47);
        triangle(60,10,10,60,110,60);
        color(255);
        square(12,12,123);
    }

    public static void main(String[] args) {
        new BohClass();
    }
}

1 Ответ

2 голосов
/ 31 мая 2020

Как уже говорили другие, у вас не должно быть while(true) l oop внутри вашей функции рисования.

Бесстыдная самореклама: здесь - это руководство по индивидуальной окраске в Swing, исходящий из фона обработки. В основном вам нужно создать Timer, который запускает перерисовку.

...