为什么我的 java awt 代码运行很慢?

Why my java awt code runs very slow?

我是一名 Android 开发人员,但现在我需要使用 awt.I 开发一个桌面套接字服务器,写一个非常小的演示来使用 Shape 显示一些线条,但是速度很慢。

public class Main {

    public static void drawLine(double x1,double y1,double x2,double y2,GeneralPath generalPath,int size){
        Line2D line2D = new Line2D.Double(x1, y1, x2, y2);
        Line2D line2D2 = new Line2D.Double(x2, y2 + size, x1, y1 + size);
        generalPath.append(line2D, false);
        generalPath.append(line2D2, true);
    }

    public static void main(String[] args) {
        SocketServer socketServer = new SocketServer(8890);
        socketServer.startListen();

        Window w = new Window(null) {
            GeneralPath generalPath = new GeneralPath();
            int i = 0;
            @Override
            public void paint(Graphics g) {
                Graphics2D g2d = ((Graphics2D) g);

                Vector<Action> v = socketServer.v;
                for (; i < v.size() - 1; i++) {
                    Action action = v.get(i);
                    if(action.type != action.ACTION_DOWN){
                        Action preAction = v.get(i-1);
                        drawLine(preAction.x,preAction.y,action.x,action.y,generalPath,1);
                    }
                }

                setShape(generalPath);
            }

            @Override
            public void update(Graphics g) {
                paint(g);
            }
        };
        w.setAlwaysOnTop(true);
        w.setBounds(w.getGraphicsConfiguration().getBounds());
        w.setVisible(true);
        while (true) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            w.repaint();
        }
    }
}

我想从套接字中绘制实时轨迹,所以我需要重新绘制所有 time.I 还需要提供点击行为所以我必须使用形状。

我对awt知之甚少。谁能告诉我为什么我的演示在画了一些线后运行很慢的问题? 非常感谢。

请注意,您正在主线程中执行多项操作。考虑使用后台任务。这将使 UI 性能更好。

我不太擅长服务器和套接字的东西,但是如果你添加选项'-Dsun.java2d.opengl=true',它可以提高渲染一点点,因为 Java2D 和 AWT general 以速度着称。

希望对您有所帮助:)