JButton 上的 setVisible() 在构造函数之外不起作用
setVisible() on JButton doesnt work outside constructor
我想了 2 天,但没有任何帮助。我尝试了 100 多种组合,但一无所获。这是我最后的机会。我正在写一个简单的游戏。
1 个 JFrame,几个 JPanel。经过一些操作后,我需要 "a play again button" 会出现。在 JPanel 构造函数中添加一个按钮(默认可见性)始终显示它,添加 setVisible(false) 然后在其他方法中调用(true)不起作用。我已经尝试过 revalidate()、rapaint() 等
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 ;/
}
函数 showButton() 不会改变可见性。这只是代码中有问题的部分,而不是全部。谢谢
尽量放
playAgain = new JButton();
在您的构造函数中,例如:
public class Game extends JPanel implements ActionListener{
private JButton playAgain;
public Game(){
playAgain = new JButton();
}
}
我找到了!将 JButton 更改为 "static" 并将 showButton() 更改为 static void。该按钮现在可见。谁能告诉为什么? :) 也许对其他人有帮助 :) 谢谢大家。
private static JButton playAgain();
private static showButton();
我想了 2 天,但没有任何帮助。我尝试了 100 多种组合,但一无所获。这是我最后的机会。我正在写一个简单的游戏。 1 个 JFrame,几个 JPanel。经过一些操作后,我需要 "a play again button" 会出现。在 JPanel 构造函数中添加一个按钮(默认可见性)始终显示它,添加 setVisible(false) 然后在其他方法中调用(true)不起作用。我已经尝试过 revalidate()、rapaint() 等
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 ;/
}
函数 showButton() 不会改变可见性。这只是代码中有问题的部分,而不是全部。谢谢
尽量放
playAgain = new JButton();
在您的构造函数中,例如:
public class Game extends JPanel implements ActionListener{
private JButton playAgain;
public Game(){
playAgain = new JButton();
}
}
我找到了!将 JButton 更改为 "static" 并将 showButton() 更改为 static void。该按钮现在可见。谁能告诉为什么? :) 也许对其他人有帮助 :) 谢谢大家。
private static JButton playAgain();
private static showButton();