在 JFrame 上的 JPanel 上绘制 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3673056/
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
Java drawing on JPanel which on a JFrame
提问by extremecoder
Hi I have a JFrame and there are two JPanels on top of it. My intention is to draw on the JPanels. Can anyone please share any Java code?
嗨,我有一个 JFrame,上面有两个 JPanel。我的意图是利用 JPanels。任何人都可以分享任何Java代码吗?
回答by OscarRyz
All the JComponents ( of which JPanel inherits from ) have a paintComponent(Graphics g )
method that you can override.
所有 JComponents(其中 JPanel 继承自)都有一个paintComponent(Graphics g )
可以覆盖的方法。
Basically... oh.. well, I think this would be more appropiate:
基本上......哦......好吧,我认为这会更合适:
http://java.sun.com/developer/technicalArticles/GUI/java2d/java2dpart1.html
http://java.sun.com/developer/technicalArticles/GUI/java2d/java2dpart1.html
Naive sample:
天真样本:
Source code:
源代码:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class X {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.add( new JPanel() {
public void paintComponent( Graphics g ) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Line2D line = new Line2D.Double(10, 10, 40, 40);
g2.setColor(Color.blue);
g2.setStroke(new BasicStroke(10));
g2.draw(line);
}
});
frame.setVisible( true );
}
}
回答by camickr
Check out the Java tutorialspage. Start with the 2D Graphics tutorial.
查看Java 教程页面。从 2D 图形教程开始。