绘画由RepaintManager
. Swing 中的绘画是通过一系列方法完成的,当RepaintManager
决定您的组件需要更新时,这些方法会代表您调用(当然,您可以请求重绘,但RepaintManager
意志决定何时、什么和多少)。
为了在 Swing 中执行自定义绘制,您需要重写作为绘制周期的一部分调用的方法之一。
建议您覆盖paintComponent
你可以签出
更多细节。
在你的例子中,你Graphics
是null
......Graphics g = null;
这无济于事......
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimplePloy {
public static void main(String[] args) {
new SimplePloy();
}
public SimplePloy() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PloyPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PloyPane extends JPanel {
private int[] xPoints;
private int[] yPoints;
public PloyPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
public void invalidate() {
xPoints = null;
yPoints = null;
super.invalidate();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (xPoints == null || yPoints == null) {
int width = getWidth() - 1;
int height = getHeight() - 1;
int halfWidth = width / 2;
int halfHeight = height / 2;
int innerWidth = width / 8;
int innerHeight = height / 8;
xPoints = new int[9];
yPoints = new int[9];
xPoints[0] = halfWidth;
yPoints[0] = 0;
xPoints[1] = halfWidth - innerWidth;
yPoints[1] = halfHeight - innerHeight;
xPoints[2] = 0;
yPoints[2] = halfHeight;
xPoints[3] = halfWidth - innerWidth;
yPoints[3] = halfHeight + innerHeight;
xPoints[4] = halfWidth;
yPoints[4] = height;
xPoints[5] = halfWidth + innerWidth;
yPoints[5] = halfHeight + innerHeight;
xPoints[6] = width;
yPoints[6] = halfHeight;
xPoints[7] = halfWidth + innerWidth;
yPoints[7] = halfHeight - innerHeight;
xPoints[8] = halfWidth;
yPoints[8] = 0;
}
g2d.drawPolygon(xPoints, yPoints, xPoints.length);
g2d.dispose();
}
}
}