在事件中使用Applet中的paintComponent绘图 [英] Drawing with paintComponent in Applet Upon Event

查看:190
本文介绍了在事件中使用Applet中的paintComponent绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小程序,它将生成与文本框中指定的数字一样多的椭圆。出现文本框,但在按Enter键时,我的paintComponent不会绘制。提前谢谢。

I'm trying to create an applet that will produce as many ovals as the number specified within a textbox. The textbox appears, but upon hitting enter, my paintComponent does not draw. Thank you in advance.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.miginfocom.layout.*;
import net.miginfocom.swing.MigLayout;
import java.awt.geom.*;

public class OvalDrawer extends JApplet
{
private JLabel numberL;
private JTextField numberTF;

private NumHandler numHandler;

public static final int WIDTH = 500;
public static final int HEIGHT = 500;

//Create Layout
public void init()
{
    setLayout(new MigLayout("wrap 2"));
    numberL = new JLabel("Enter number of ovals to draw:");
    numberTF = new JTextField(7);

    add(numberL);
    add(numberTF);

    numHandler = new NumHandler();
    numberTF.addActionListener(numHandler);

    setSize(500, 500);
}

//Event Handler
public class NumHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        repaint();
    }

}

//Draw Ovals
public void paintComponent (Graphics g)
{
    super.paintComponents(g);
    int number;
    int x = 10;
    int y = 30;
    int width = 20;
    int height = 10;

    number = Integer.parseInt(numberTF.getText());

    for (int i = 0; i < number; i++)
    {
        g.drawOval(x, y, width, height);

        x += 5;
        y += 5;
        width += 5;
        height += 5;
    }
}
}


推荐答案

JApplet类没有要覆盖的paintComponent方法。请注意,您的编译器不会让您调用实际的超级方法(您认为您可能正在执行此操作,但实际上您正在调用 super.paintComponents(...) ,一种完全不同的方法)。

A JApplet class does not have a paintComponent method to override. Note that your compiler won't let you call the actual super method (you think you may be doing this, but you're actually calling super.paintComponents(...), a completely different method).

一个糟糕的解决方案是覆盖JApplet的paint方法,但我强烈建议你不要这样做。相反,您应该绘制JPanel的paintComponent方法,然后让JApplet显示JPanel。此外,你会想养成使用 @Override 注释的习惯,以确保你实际上覆盖了你认为的方法。

A bad solution is to override the JApplet's paint method, but I strongly advise you not to do this. Instead you should draw in the paintComponent method of a JPanel and then have the JApplet display that JPanel. Also, you'll want to get into the habit of using the @Override annotation to be sure that you're actually overriding methods you think are.

这篇关于在事件中使用Applet中的paintComponent绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆