JApplet 和调用paint/paintComponent 的问题 [英] Trouble with JApplets and calling paint/paintComponent
问题描述
所以我只是在这里为期末考试做一些学习,但我无法让它发挥作用.我以前一直做的是调用paintComponent(Graphics g)事情进展顺利.但是现在我在编译时收到paintComponent has protected access in JComponent"错误.我可以让它编译的唯一方法是告诉它调用paint.但即使它编译,paint 也永远不会在小程序窗口中被调用.我在这里没有看到什么?
So I'm just doing some studying for finals here, and I'm having trouble getting this to work. What I have always done previously is call paintComponent(Graphics g) and things have worked just peachy. But now I'm getting a "paintComponent has protected access in JComponent" error when I go to compile. The only way I could get it to compile was to tell it to call paint. But even if it compiles, paint never gets called in the applet window. What am I not seeing here?
public class LineDraw extends JComponent
{
private final Point p1;
private final Point p2;
private final JApplet callingWindow;
private final ArrayList<Line2D.Double> lines;
public LineDraw(JApplet callingWindow)
{
this.p1 = new Point();
this.p2 = new Point();
this.callingWindow = callingWindow;
this.lines = new ArrayList<Line2D.Double>();
MouseListener mouse = new MouseHandler();
callingWindow.addMouseListener(mouse);
}
public class MouseHandler extends MouseAdapter
{
private boolean firstClick;
public MouseHandler()
{
firstClick = true;
}
public void mouseClicked(MouseEvent e)
{
if(firstClick)
{
p1.setLocation(e.getPoint());
firstClick = false;
}
else
{
p2.setLocation(e.getPoint());
lines.add(new Line2D.Double(p1, p2));
p2.setLocation(p1.getLocation());
callingWindow.repaint();
}
}
public void paintComponent(Graphics2D g2)
{
for(Line2D.Double e: lines)
{
g2.draw(e);
}
}
}
}
和小程序类本身
public class AppletWin extends JApplet
{
private LineDraw lineDrawer;
public void init()
{
setBackground(Color.white);
lineDrawer = new LineDraw(this);
}
public void paint(Graphics h)
{
Graphics2D g = (Graphics2D)h;
//Clear background
g.setColor(getBackground());
g.fillRect(1, 1, getWidth(), getHeight());
lineDrawer.paintComponent(g);
}
}
推荐答案
这段代码的问题是LineDraw中的paintComponent方法在内部类MouseHandler里面.
Problem with this code is that the paintComponent method in LineDraw is inside the inner class MouseHandler.
这篇关于JApplet 和调用paint/paintComponent 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!