JButton补充说,但不可见

时间:2012-04-01 17:57:00

标签: java swing panel jbutton paintcomponent

我想用Java创建一个Pong游戏。我用paintComponent方法绘制所有东西。在这个方法中,我调用另一个方法“initBall”。此方法将球拉到起始位置。当我去世时,我想再次在初始位置抽出球,我想在我的面板中央添加一个按钮,说“按下逃生继续”,然后球开始移动。问题是我的按钮不可见。

请帮帮我:)。

这是我的代码:

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

谢谢

2 个答案:

答案 0 :(得分:3)

inItBall(...) revalidate() JPanel中添加按钮后,{/ 1}}

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

答案 1 :(得分:0)

尝试添加setVisible(true);