我一直在試圖開發一個帶有箭頭的人類簡筆畫的程序。所以這裏的問題是,添加了ImageIcon作爲背景後,paintComponent下的圖形不會顯示。我如何在背景圖片上顯示繪畫。我的編碼如下。Java:無法顯示paintComponent
public class Drawing
{
public Drawing()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.getContentPane().setBackground(new Color(204,229,255));
f.getContentPane().add(new ArrowPanel());
f.setSize(1000,600);
//f.setLocation(200,200);
f.setLayout(new BorderLayout());
f.setContentPane(new JLabel(new ImageIcon("/Users/marian/NetBeansProjects/Drawing/src/drawing/wall.jpg")));
f.setLayout(new FlowLayout());
f.setVisible(true);
}
public static void main(String[] args)
{
new Drawing();
}
}
class ArrowPanel extends JPanel
{
double phi;
int barb;
public ArrowPanel()
{
phi = Math.toRadians(40);
barb = 30;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
Point sw = new Point(w/8, h*7/8);
Point ne = new Point(w*7/8, h/8);
g2.draw(new Line2D.Double(sw, ne));
//drawArrowHead(g2, sw, ne, Color.red);
drawArrowHead(g2, ne, sw, Color.blue);
Ellipse2D.Double head = new Ellipse2D.Double(90,60,20,20);
g2.draw(head);
Line2D.Double body=new Line2D.Double(100,80,100,120);
g2.draw(body);
Line2D.Double arm1=new Line2D.Double(100,100,80,100);
g2.draw(arm1);
Line2D.Double arm2=new Line2D.Double(100,100,120,75);
g2.draw(arm2);
Line2D.Double leg1=new Line2D.Double(100,120,85,135);
g2.draw(leg1);
Line2D.Double leg2=new Line2D.Double(100,120,115,135);
g2.draw(leg2);
}
private void drawArrowHead(Graphics2D g2, Point tip, Point tail, Color color)
{
g2.setPaint(color);
double dy = tip.y - tail.y;
double dx = tip.x - tail.x;
double theta = Math.atan2(dy, dx);
//System.out.println("theta = " + Math.toDegrees(theta));
double x, y, rho = theta + phi;
for(int j = 0; j < 2; j++)
{
x = tip.x - barb * Math.cos(rho);
y = tip.y - barb * Math.sin(rho);
g2.draw(new Line2D.Double(tip.x, tip.y, x, y));
rho = theta - phi;
}
}
}
我還在學習Java,有人可以幫助解決這個問題。謝謝。