0

J2D.java

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class J2D extends JFrame {
    int x, y = 0;

    public J2D() {
        setTitle("2D");
        setSize(613, 253);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
            add(new panel ());
            add(new panel2());
            Thread th = new Thread(){
                @Override
                public void run() {
                    while(true){
                        x++;y++;
                        repaint();
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            th.start();
    }


    private class panel extends JPanel{
        public void paintComponent(Graphics g){
            //super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setColor(Color.DARK_GRAY);
            g2d.drawString("Fear", x, y);

        }
    }

    private class panel2 extends JPanel{
        public void paintComponent(Graphics g){
            //super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setColor(Color.RED);
            g2d.drawString("Fear2", x + 15, y);
        }
    }
}

当我运行此代码时,它只显示Fear2标签。我需要 2 个类并想添加两个类,但它如何正常工作?我应该写paint()paintComponent()方法吗?

4

0 回答 0