setVisible() on JButton doesnt work outside constructor

时间:2016-08-31 18:24:27

标签: java swing jpanel jbutton

I'm trying to figure it out for 2 days and nothing helps. I Tried over 100 combinations and nothing. This is my last chance. I'm writing a simple game. 1 JFrame, few JPanels. After some action I need "a play again button" will show up. Adding a button(default visibility) in JPanel constructor shows it all-time, adding with setVisible(false) and then call (true) in other method doesnt work. I've tried revalidate(), rapaint() etc.

public class Game extends JPanel implements ActionListener{

private JButton playAgain = new JButton();

public Game(){

    setFocusable(true);
    requestFocus();
    this.setPreferredSize(new Dimension(800,600));
    this.setLayout(null);
    addButton();
    this.setVisible(true);
}

private void addButton() {

    playAgain.setBounds(600, 550, 200, 50);
    playAgain.addActionListener(this);
    playAgain.setBorder(null);
    playAgain.setCursor(new Cursor(Cursor.HAND_CURSOR));
    playAgain.setContentAreaFilled(false);
    playAgain.setVisible(false);
    this.add(playAgain);
}

private void showButton() {

    playAgain.setVisible(true);
}

public void actionPerformed(ActionEvent e){

        if(king1.isKingStopped()){
            gameFinished = true;
            addButton();
            //showButton(); // doesnt work ;/
}

Function showButton() doesnt change visibility. This is only problematic part of code, not all. Thanks.

2 个答案:

答案 0 :(得分:0)

Try to put

playAgain = new JButton();

in side your constructor like :

public class Game extends JPanel implements ActionListener{

private JButton playAgain;

public Game(){
playAgain = new JButton();
}
}

答案 1 :(得分:0)

我找到了!将JButton更改为" static"和showButton()到静态void。现在可以看到按钮了。有谁能说出原因? :)也许它可以帮助别人:)谢谢你们。

private static JButton playAgain();

private static showButton();