我希望使用 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);
}
}