我想用Graphics在窗口上画图形  但是重载paint函数的话 这个窗口只能是继承JFrame类。如果不想用继承  怎么才能画图形呢?
代码如下:import java.awt.*;
import javax.swing.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class test extends JFrame{
   
    //private JFrame frame;
    private JLabel date_display;
    private JLabel name_display;
    private JLabel map_display;    public test() {
       
        //frame = new JFrame("test");
        Container c = this.getContentPane();
        c.setLayout(null);
       
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        String str_Date = format.format(date);
       
        date_display = new JLabel();
        date_display.setBounds(30,20,400,30);
        date_display.setText("Today's Date is: " + str_Date);
        date_display.setFont(new Font("", Font.PLAIN, 25));
        date_display.setForeground(Color.red);
        c.add(date_display);
       
        name_display = new JLabel();
        name_display.setBounds(140,90,200,30);
        name_display.setText("Time Zone");
        name_display.setFont(new Font("", Font.PLAIN, 25));
        name_display.setForeground(Color.red);
        c.add(name_display);
       
        ImageIcon image = new ImageIcon("map.gif");
        map_display = new JLabel(image);
        map_display.setBounds(10,130,image.getIconWidth(),image.getIconHeight());
        c.add(map_display);
       
        this.setSize(390,370);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
   
    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawLine(0,100,390,100);
    }
   
    public static void main(String args[])
    {
        new test();
    }
}
还有一个问题,那个super.paint(g); 是干什么用的,为什么去掉以后就只显示一条线 其他组件不显示?

解决方案 »

  1.   

    谁说一定得继承JFrame类?思路:专门定义一个画板类,继承JPanel或者JComponent实现paint方法。将实现类的对象像添加按钮一样添加到JFrame中。本质就是自定义组件,类似sun公司的程序员自定义一个JButton出来。他们能这样做,我们为什么不能这样做!发挥你的想象力,你可以定义任何你想要的组件。比如坦克,人物,障碍物,子弹……建议楼主看看帮助文档,搞清楚JFrame的派生层次结构图,找到最原始最适合你的类来实现。JFrame是在基础类上继承后,又加入了自己特有的东西进一步的进行了封装,所以不太适合做画板之类的事情。由此可以说继承是一种遗传,多态就是变异。扯远了……