我无法在JFrame的屏幕上显示2个对象

时间:2019-03-23 09:30:14

标签: java swing jframe

我试图使用JFrame在屏幕上显示2个对象,并且试图将它们移动。我有1个对象出现在屏幕上,然后尝试在其中显示2个对象,但我无法使其正常工作

这是我的主音

package animate;

import javax.swing.*;
import java.awt.*;

public class Main {
    public static void main(String[] args){
        //Square s = new Square(50, 100, 2);
        //Square s2 = new Square(300, 50, 1);
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        frame.setSize(700, 350);

        panel.setLayout(new FlowLayout());
        panel.add(new Square(50, 100, 2));
        panel.add(new Square(300, 50, 1));

        frame.add(panel);
        frame.setResizable(false);
        frame.setTitle("hi");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);
    }
}

这是我的正方形课(应该画一个正方形,但现在我正使用圆进行测试)

package animate;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class Square extends JPanel implements ActionListener {
    Timer t = new Timer(5, this);
    double x, y, vel;

    public Square(int x, int y, int vel){
        this.x = x;
        this.y = y;
        this.vel = vel;
    }
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        Ellipse2D circ = new Ellipse2D.Double(this.x, this.y, 40, 40);
        g2.fill(circ);
        t.start();
    }
    public void actionPerformed(ActionEvent e){
        x += 0;
        y += 0;
        repaint();
    }
    @Override
    public Dimension getPreferredDimension(){
        return new Dimension(100, 540);
    }
}

0 个答案:

没有答案