I am taking a class that is teaching Java and we have a problem I can not solve. We need to move two rectangles in opposite directions. I have the code completed that will do this but the problem is I can only get either one or none of the rectangles to appear. I have tried varying solutions, such as adding the rectangles to a JPanel, as well as different layouts with no success.
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();
}}