使用paintComponent()在JFrame中绘制矩形 [英] Using paintComponent() to draw rectangle in JFrame

查看:126
本文介绍了使用paintComponent()在JFrame中绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JPanel的paintComponent()创建一个绘制形状的程序(下面的例子中的一个矩形),但我无法让它工作,也无法发现错误。

I'm trying to create a program that draws shapes (a rectangle on the example below) using JPanel's paintComponent(), but I can't get it to work and can't spot what is wrong.

代码如下:

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

public class RandomRec{
    JFrame frame;

    public void go(){
        frame = new JFrame();
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DrawPanel panel = new DrawPanel();
    }

    public static void main (String[] args){
        class DrawPanel extends JPanel{
           public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(Color.orange);
              g.drawRect(20, 20, 100, 60);
           }
        }

        RandomRec test = new RandomRec();
        test.go();
    }
}

对此的任何帮助都将非常感激。

Any help on this would be much appreciated.

谢谢。

* 更新 * 问题解决!将go()方法移出main方法,添加一个frame.add(面板)并将frame.setVisible(true)移动到go()方法的底部(更具体地说,在添加面板后移动它)框架)已对问题进行了排序。谢谢。

*UPDATE* Problem solved! Moving the go() method out of the main method, adding a frame.add(panel) and moving the frame.setVisible(true) to the bottom of the go() method (more specifically, move it after the panel is added to the frame) has sorted the issue. Thank you.

推荐答案

您的班级 DrawPanel 仅限于 main 方法,对你的构造函数不可见。

Your class DrawPanel is confined to the scope of your main method and is not visible to your constructor.

你需要移动 DrawPanel 退出方法,然后将其添加到 JFrame

You need to move DrawPanel out of your main method, then add it to your JFrame:

frame.add(panel);

此外,最好调用 frame.setVisible(true)添加完所有组件后。

Also, better to call frame.setVisible(true) after all components have been added.

这篇关于使用paintComponent()在JFrame中绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆