如果移動和調整大小,下列組件將正確繪製,但如果從屏幕中拖出,則不會正確繪製。這個JComponent爲什麼不能正確繪製?
爲什麼?
public class Test_ShapeDraw {
public static class JShape extends JComponent {
private Shape shape;
private AffineTransform tx;
private Rectangle2D bounds;
public JShape() {
}
public void setShape(Shape value) {
this.shape = value;
bounds = shape.getBounds2D();
setPreferredSize(new Dimension((int) bounds.getWidth(), (int)bounds.getHeight()));
tx = AffineTransform.getTranslateInstance(-bounds.getMinX(), -bounds.getMinY());
}
public Shape getShape() {
return shape;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(shape != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.setTransform(tx);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D)g).draw(shape);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
Shape shape = new Ellipse2D.Double(0,0,300,300);
JShape jShape = new JShape();
jShape.setShape(shape);
JFrame f = new JFrame("Shape Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jShape);
f.pack();
f.setVisible(true);
}
}
你是什麼意思「拖出屏幕」?我無法用您的代碼重現您的問題。 –