java - 向相反方向移动两个矩形

标签 java swing

我正在上一门教授 Java 的类(class),但我们有一个无法解决的问题。我们需要向相反的方向移动两个矩形。我已经完成了执行此操作的代码,但问题是我只能显示一个矩形,或者不能显示任何矩形。我尝试了不同的解决方案,例如将矩形添加到 JPanel 以及不同的布局,但没有成功。

public class RectTimer {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 300);
    frame.setTitle("An animated rectangle");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final RectangleComponent component = new RectangleComponent();
    final RectangleComponent component2 = new RectangleComponent(290,290);
    JPanel container = new JPanel();
    container.add(component);
    container.add(component2);
    frame.add(container);
    frame.setVisible(true);
    class TimerListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {
        component.moveBy(5, 5);

        }

    }
    class TimerListener2 implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent arg0) {
            component2.moveBy(-5, -5);

        }

    }
    ActionListener l = new TimerListener();
    Timer t = new Timer(100, l);
    t.start();
    ActionListener l2 = new TimerListener2();
    Timer t2 = new Timer(100, l2);
    t2.start();}


public class RectangleComponent extends JComponent{

private Rectangle box;

public RectangleComponent(){
    box = new Rectangle(10,10,20,30);
}

public RectangleComponent(int x, int y){
    box = new Rectangle(x,y,20,30);
}


@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.draw(box);
    g2.dispose();
}

public void moveBy(int dx, int dy){
    box.translate(dx, dy);
    if(box.getX() > 300 && box.getY() > 300){
        box.setLocation(10, 10);
    }
    if(box.getX() < 0 && box.getY() < 0){
        box.setLocation(290, 290);
    }
    repaint();
}

public void moveTo(int x, int y){
    box.setLocation(x, y);
    repaint();
}}

最佳答案

but the problem is I can only get either one or none of the rectangles to appear.

这可能是因为您仍在使用框架的默认 BorderLayout 并将组件添加到 CENTER。仅显示最后添加的组件。

I just used the OverlayLayout

我建议您不要使用 OverlayLayout。

因为您使用的是随机运动,所以您只想将组件添加到同一面板。然后,您将使用空布局,以便您可以手动控制每个组件的位置。您还将负责设置组件的大小,这是其首选大小。

此外,您还需要重写组件的 getPreferredSize() 以返回您希望组件达到的大小。首选尺寸将基于您的定制绘画。因此,在您的情况下,首选大小是 (20, 30);。盒子总是被绘制在 (0, 0) 处。要移动该框,您需要设置该框的位置。

关于java - 向相反方向移动两个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668163/

相关文章:

java - Android 相机,内部列表选项?

java - Jackson - 反序列化 JSON 字符串 - TypeReference 与 TypeFactory.constructCollectionType

java - Java 中的内部类必须是静态的吗?

java - 重叠 AWT 行和 Swing JLabel

java - 在 jfilechooser 中包含图像缩略图

java - 调整大小时 JFrame 图像干净

java - Maven 目标文件夹中没有依赖文件夹。无法访问jetty-runner.jar

java - Jtable中只显示数据库表的一行

java - 强制 JLabel 在昂贵的操作之前显示文本

java - Maven:运行程序的生命周期阶段?