gpt4 book ai didi

Java:无法显示paintComponent

转载 作者:行者123 更新时间:2023-12-02 13:11:20 25 4
gpt4 key购买 nike

我一直在尝试开发一个带有带箭头的人物简笔画的程序。所以这里的问题是,当添加 ImageIcon 作为背景时,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,有人可以帮助解决这个问题吗?谢谢。

最佳答案

如果您想在 Swing 应用程序中使用不同的层,则应该使用 LayeredPane 而不是 JPanel。并且您应该避免设置不同的 LayoutManager。这段代码设置了最后一个LayoutManager,所以第一行没用:

f.setLayout(new BorderLayout());
f.setContentPane(new JLabel(new ImageIcon("/Users/marian/NetBeansProjects/Drawing/src/drawing/wall.jpg")));
f.setLayout(new FlowLayout());

这里有一篇关于如何使用 LayeredPanes 的文章 Tutorial

关于Java:无法显示paintComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43936020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com