1

I want the racket to be positioned by using the getWidth method for the gamePanel, but it returns 0. It works fine for the frame, and it worked for the panel as well, but I decided to rewrite alot of the code and now I cant get it to work. Help is appreciated :)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Oppgave1 extends JFrame {

    public static void main(String[] args) {
        JFrame frame = new Oppgave1();
        frame.setTitle("Oppgave 1");
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private JLabel jlbBallCount = new JLabel("Ballcount");
    private JLabel jlbTimer = new JLabel("Timer");
    private JButton jbtNewBall = new JButton("New Ball");

    private Racket racket;
    private Ball ball;

    public Oppgave1() {

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(jlbBallCount);
        buttonPanel.add(jlbTimer);
        buttonPanel.add(jbtNewBall);

        JPanel gamePanel = new JPanel();    
        gamePanel.add(racket = new Racket (100, 60));
        gamePanel.add(ball = new Ball(10, 3, racket));

        this.add(gamePanel, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }

    public void paint(Graphics g){
        racket.draw(g);
        ball.draw(g);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    Where do you call `getWidth()`? – Code-Apprentice Feb 21 '13 at 01:54
  • 1
    @Code-Guru I was just wondering the same thing. I was also wondering ***why*** the need to ever know the size of the panel. Rely on layout managers and it typically becomes irrelevant. – Andrew Thompson Feb 21 '13 at 01:55
  • @AndrewThompson Looks like this might be for a game. With custom painting that is often required, getting a component's size can certainly be useful. Of course, a sophisticated solution would hide these details in a appropriate linear transformations. – Code-Apprentice Feb 21 '13 at 01:58
  • This question seems relevant http://stackoverflow.com/questions/8336262/why-cant-i-access-my-panels-getwidth-and-getheight-functions – swilliams Feb 21 '13 at 02:35

1 Answers1

2
  1. Don't override the paint() method of a JFrame.

  2. You added the racket and ball to the game panel. The game panel will now paint these components automatically.

  3. If you want to be able to move these components then you must set the layout to null and initially set the bounds of the components. Then when you want to move the component you just invoke the setLocation() method and Swing will paint the component in its new position.

camickr
  • 321,443
  • 19
  • 166
  • 288