您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用getGraphics()绘制对象而不扩展JFrame

使用getGraphics()绘制对象而不扩展JFrame

如果要更改组件的绘制方式(添加矩形),则需要paintComponent()在该组件中重新定义。在你的代码中,你正在使用 getGraphics()

你不应该调用getGraphics()组件。你所做的任何绘画(Graphics退还给你的绘画)都是暂时的,并且在Swing下次确定需要重新绘画组件时将丢失。

相反,你应该覆盖paintComponent(Graphics)(``JComponent或的JPanel方法,并使用Graphics接收到的对象作为参数在此方法中进行绘制。

检查此链接以进一步阅读。

下面是你的代码,已更正。

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

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(600, 400);

        JPanel panel = new JPanel() {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.BLUE);
                g.fillRect(0, 0, 100, 100);
            }
        };
        frame.add(panel);

        // Graphics g = panel.getGraphics();
        // g.setColor(Color.BLUE);
        // g.fillRect(0, 0, 100, 100);

        frame.validate(); // because you added panel after setVisible was called
        frame.repaint(); // because you added panel after setVisible was called
    }
}

一个版本执行完全相同的操作,但可能对你更清楚:

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

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(600, 400);

        JPanel panel = new MyRectangleJPanel(); // changed this line
        frame.add(panel);

        // Graphics g = panel.getGraphics();
        // g.setColor(Color.BLUE);
        // g.fillRect(0, 0, 100, 100);

        frame.validate(); // because you added panel after setVisible was called
        frame.repaint(); // because you added panel after setVisible was called
    }
}

/* A JPanel that overrides the paintComponent() method and draws a rectangle */
class MyRectangleJPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.fillRect(0, 0, 100, 100);
    }
}
其他 2022/1/1 18:17:35 有622人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶