java 使用paintComponent()在JFrame中绘制矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13404398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using paintComponent() to draw rectangle in JFrame
提问by priboyd
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.
我正在尝试创建一个使用 JPanel 的paintComponent() 绘制形状(下例中的矩形)的程序,但我无法让它工作,也无法发现问题所在。
The code is as follows:
代码如下:
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.
对此的任何帮助将不胜感激。
Thank you.
谢谢你。
*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.
*更新*问题已解决!将 go() 方法移出 main 方法,添加 frame.add(panel) 并将 frame.setVisible(true) 移动到 go() 方法的底部(更具体地说,将面板添加到框架)已对问题进行了排序。谢谢你。
采纳答案by Reimeus
Your class DrawPanel
is confined to the scope of your main
method and is not visible to your constructor.
你的类DrawPanel
被限制在你的main
方法范围内,对你的构造函数不可见。
You need to move DrawPanel
out of your main
method, then add it to your JFrame
:
您需要DrawPanel
退出您的main
方法,然后将其添加到您的JFrame
:
frame.add(panel);
Also, better to call frame.setVisible(true)
after all components have been added.
此外,最好frame.setVisible(true)
在添加所有组件后调用。
回答by John Gardner
you're never actually adding the panel to the frame, so it is never visible. you need something like
您实际上从未将面板添加到框架中,因此它永远不可见。你需要类似的东西
frame.getContentPane().add( panel );
why are you defining the drawpanel class inside the main method? that's rather odd.
为什么要在 main 方法中定义 drawpanel 类?这很奇怪。