我想用Java創建一個Pong遊戲。我用我的paintComponent方法繪製所有的東西。在這個方法中,我調用另一個方法「initBall」。該方法在起始位置繪製球。當我死的時候,我想再次在初始位置畫我的球,並且我想在我的面板的中央添加一個按鈕,它說「按下退出繼續」,然後球開始移動。問題是我的按鈕不可見。JButton補充說,但不可見
請幫我:)
這裏是我的代碼:
public class PlayPanel extends JPanel implements ConstantesCommunes {
/**
*
*/
private static final long serialVersionUID = 1L;
private int posX;
private int posY;
private boolean newBall = true;
private JPanel pan_WestZone = new JPanel();
private JPanel pan_EastZone = new JPanel();
private JButton but_Escape = new JButton("Press escape to continue !");
Graphics2D graphics2d;
/*
* Constructeur de classe : PlayPanel.java
*/
// ==============================================
public PlayPanel() {
super(new BorderLayout());
setBackground(Color.DARK_GRAY);
pan_WestZone.setPreferredSize(WESTPANEL_SIZE);
pan_EastZone.setPreferredSize(EASTPANEL_SIZE);
pan_WestZone.setBackground(ZONE_COLOR);
pan_EastZone.setBackground(ZONE_COLOR);
add(pan_WestZone, BorderLayout.WEST);
add(pan_EastZone, BorderLayout.EAST);
}
/*
* Ajouter la balle sur la surface de jeux
*/
// ==============================================
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
posX = SCREEN_WIDTH/2;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.ORANGE);
initBall(g2);
// trait épais
g2.setColor(Color.LIGHT_GRAY);
g2.setStroke(new BasicStroke(10));
g2.drawLine((SCREEN_WIDTH/2) - 5, SCREEN_HEIGHT,
(SCREEN_WIDTH/2) - 5, 0);
}
/*
* Initialiser la balle lorsqu'un joueur perd
*/
// ==============================================
private void initBall(Graphics2D graphics2d) {
but_Escape.setPreferredSize(new Dimension(100, 30));
Graphics2D g2 = graphics2d;
g2.fillOval(SCREEN_WIDTH/2, 0, BALL_WIDTH, BALL_HEIGHT);
// The problem is here
add(but_Escape);
}
感謝
_千萬-ever_更改組件的狀態,而畫!相反,改變狀態(由任何事件觸發),然後在需要時觸發重新繪製/驗證 – kleopatra 2012-04-02 10:10:13
@kleopatra:Ahha,是的,我忘了抓住那個東西:(這是一個很好的見解:-) – 2012-04-02 10:20:53