getWidth()为面板返回0

时间:2013-02-20 23:58:16

标签: java swing jframe jpanel

我希望通过使用gamePanel的getWidth方法来定位球拍,但它返回0.它适用于框架,它也适用于面板,但我决定重写很多代码和现在我无法让它工作。感谢帮助:)

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);
    }
}

1 个答案:

答案 0 :(得分:2)

  1. 不要覆盖JFrame的paint()方法。

  2. 您将球拍和球添加到游戏面板中。游戏面板现在将自动绘制这些组件。

  3. 如果您希望能够移动这些组件,则必须将布局设置为null并初始设置组件的边界。然后,当您想要移动组件时,只需调用setLocation()方法,Swing就会将组件绘制到新的位置。