Reputation: 33
I'm trying to use the following class as a racket for a simple pinpong game
public class Racket extends JLabel{
int up, down;
int x, y;
public Racket(int up, int down, int x, int y){
this.setBackground(Color.BLACK);
this.setForeground(Color.BLACK);
this.up = up;
this.down = down;
this.x = x;
this.y = y;
setLocation(x,y);
setOpaque(true);
}
}
When I add the Racket to the main frame via
p1 = new Racket(KeyEvent.VK_W, KeyEvent.VK_S, 0, (windowSize.height/2)-10);
window.add(p1);
the racket isn't showing up, could anyone point out what's wrong?
The container is just a simple JFrame with no layout manager
window = new JFrame("Ping Pong");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);
Upvotes: 1
Views: 245
Reputation: 285405
And there's your problem:
window.setLayout(null);
When you use null
layouts you are fully responsible for the complete layout including the size and location of all added components, and in your code, while you're setting the JLabel's location, you aren't setting the size. The correct solution is not to set its size but to avoid using null layouts. While null layouts and setBounds()
might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Upvotes: 2