如何编写这个匿名类的版本?

时间:2015-04-18 17:18:09

标签: java

是否可以将MyComponent类定义为frame.add()方法的参数列表中的匿名类?怎么样?

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Scratch {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Frame");
        frame.setSize(750,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MyComponent());
        frame.setVisible(true);
    }

}

class MyComponent extends JComponent {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g.drawString("Hello", 100, 100);
    }
}

2 个答案:

答案 0 :(得分:1)

是的,根据您的需要,您可以使用

frame.add(new JComponent() {//anonymous class will extend JComponent 
                            //in same way MyComponent does
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g.drawString("Hello", 100, 100);
    }
});

frame.add(new MyComponent(){//anonymous class which will extend MyComponent
    //you can add more code/members here 
});

答案 1 :(得分:0)

是的,确实如此。只需在匿名类的主体内添加方法:

frame.add(new JComponent() {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g.drawString("Hello", 100, 100);
    }
});