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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 6 years ago.
回答1:
All the JComponents ( of which JPanel inherits from ) have a paintComponent(Graphics g )
method that you can override.
Basically... oh.. well, I think this would be more appropiate:
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 );
}
}
回答2:
Check out the Java tutorials page. Start with the 2D Graphics tutorial.