栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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    }}class MyRectangleJPanel extends JPanel {    @Override    public void paintComponent(Graphics g) {        super.paintComponent(g);        g.setColor(Color.BLUE);        g.fillRect(0, 0, 100, 100);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441921.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号