You're adding both Objects to the same area in the Borderlayout. That's why the first Object gets overwritten.
Try this:
JFrame f = new JFrame("Moving");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Ballbewegung2 ball = new Ballbewegung2();
Ballbewegung3 ball1 = new Ballbewegung3();
contentPane.add(ball, BorderLayout.NORTH);
contentPane1.add(ball1, BorderLayout.CENTER);
f.getContentPane().add(contentPane);
f.getContentPane().add(contentPane1);
f.setSize(500, 500);
f.setVisible(true);
It would be nice to have Ballbewegung as a direct extension to Jpanel - that would solve 2 problems at once.
Additional:
This is a simple demonstration to show the function of the Borderlayout.
Please note that every JPanel is added to another region - except the "another South" Panel, which overwrites the original "South" Panel.
public class MultiplePanels extends JFrame {
public static void main(String[] args) {
MultiplePanels oFrame = new MultiplePanels();
oFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
oFrame.setSize(600, 300);
oFrame.setVisible(true);
oFrame.add(new MyPanel("North"), BorderLayout.NORTH);
oFrame.add(new MyPanel("Center"), BorderLayout.CENTER);
oFrame.add(new MyPanel("West"), BorderLayout.WEST);
oFrame.add(new MyPanel("East"), BorderLayout.EAST);
oFrame.add(new MyPanel("South"), BorderLayout.SOUTH);
oFrame.add(new MyPanel("another South"), BorderLayout.SOUTH);
}
}
public class MyPanel extends JPanel {
public MyPanel(String strName) {
this.setLayout(new BorderLayout());
this.add(createLabel(strName), BorderLayout.CENTER);
}
private Component createLabel(String strName) {
JLabel lblPanelnumber = new JLabel("This is the Panel " + strName);
lblPanelnumber.setHorizontalAlignment(SwingConstants.CENTER);
return lblPanelnumber;
}
}
Second Additional:
public class MultiplePanels extends JFrame {
public MultiplePanels() {
}
public static void main(String[] args) {
MultiplePanels oFrame = new MultiplePanels();
oFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
oFrame.setSize(400, 400);
oFrame.setBackground(Color.WHITE);
oFrame.setVisible(true);
oFrame.setLayout(new GridLayout(2, 1));
oFrame.getContentPane().add(new Ballbewegung(10, 40));
oFrame.getContentPane().add(new Ballbewegung(10, 80));
}
}
class Ballbewegung extends JPanel implements Runnable {
int x_pos = 10;
int y_pos = 100;
int radius = 20;
public Ballbewegung(int x_pos, int y_pos){
this.x_pos = x_pos;
this.y_pos = y_pos;
init();
}
public void init() {
this.setOpaque(false);
this.start();
}
public void start() {
Thread th = new Thread(this);
th.start();
}
@Override
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true) {
x_pos++;
if (x_pos >= 400)
x_pos = 10;
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
@Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
}