從JComponent派生類並重寫paintComponent方法。它傳遞一個Graphics對象,可以將其轉換爲Graphics2D對象。後者支持改變座標系。
對於繪製精靈:在循環中加載單個像素非常緩慢。 Graphics2D中有一個drawImage方法,它支持所有你需要的blitting小精靈。
下面是一個例子設置在一個自包含例如一箇中心起源Graphics2D對象:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Draw2D extends JFrame {
public Draw2D() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new DrawPane(), BorderLayout.CENTER);
pack();
}
public static void main(String[] args) {
Draw2D drawing = new Draw2D();
drawing.setVisible(true);
}
}
class DrawPane extends JComponent {
public DrawPane() {
setPreferredSize(new Dimension(640, 640));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// use anti-aliasing for smooth lines
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// move origin to center
g2.translate(getWidth()/2, getHeight()/2);
// scale as you need. Using negative y so that y points upward
// note that non-square window sizes will cause a different aspect ratio,
// you probably want to use Math.min(width, height) or something
g2.scale(getWidth()/2, -getHeight()/2);
// set color and thickness
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(0.001f));
// draw coordinate lines
g2.draw(new Line2D.Float(-1f, 0f, 1.0f, 0f));
g2.draw(new Line2D.Float(0, -1.0f, 0.0f, 1.0f));
// draw a vector
g2.draw(new Line2D.Float(0f, 0f, 0.25f, 0.25f));
}
}
來源
2013-11-27 20:01:41
fpw
是啊,圖形對象的這種整體思路,並JPanels等我沒有一個線索。我可以閱讀在線文檔,嘗試一下,複製出所有我想要的東西,我從來沒有得到任何東西出現。 –
如果你願意舉一個例子,我將不勝感激,是否需要上傳我的源代碼,或者我是否已經足夠清楚地解釋了我的內容? –
添加了示例。適合你的需求? – fpw