我正在尝试制作一个石头、剪刀、布游戏,并且我在框架中添加了 3 个按钮,但是当我启动程序时,其中两个按钮只有将鼠标悬停在它们上方才会出现,任何人都知道为什么?
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.FlowLayout;
import javax.swing.JOptionPane;
public class RPSFrame extends JFrame {
public static void main(String [] args){
new RPSFrame();
}
public RPSFrame(){
JFrame Frame1 = new JFrame();
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Rock, Paper or Scissors game");
this.setLocationRelativeTo(null);
ClickListener cl1 = new ClickListener();
ClickListener cl2 = new ClickListener();
ClickListener cl3 = new ClickListener();
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Result:");
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
this.add(panel1);
this.setVisible(false);
JPanel panel2 = new JPanel();
JButton Rock = new JButton("Rock");
Rock.addActionListener(cl1);
panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
panel2.add(Rock);
this.add(panel2);
this.setVisible(true);
JPanel panel3 = new JPanel();
JButton Paper = new JButton("Paper");
Paper.addActionListener(cl2);
panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
panel3.add(Paper);
this.add(panel3);
this.setVisible(true);
JPanel panel4 = new JPanel();
JButton Scissors = new JButton("Scissors");
Scissors.addActionListener(cl3);
panel4.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel4.add(Scissors);
this.add(panel4);
this.setVisible(true);
}
private class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == "Rock"){
int AI = new Random().nextInt(3) + 1;
JOptionPane.showMessageDialog(null, "I have been clicked!");
}
}
}
}
最佳答案
应在所有组件添加到框架之后
调用setVisible(true)
语句。
您当前有两个 setVisible(...) 语句,因此您需要删除第一个。
编辑:
再次查看代码。您有多个 setVisible(...) 语句。除了最后一个之外,把它们全部处理掉。
不要为每个按钮创建单独的面板。相反,您为所有按钮创建一个面板(称为
buttonPanel
)。在您的情况下,您可能会使用水平 BoxLayout。向面板添加一个按钮,然后添加glue
,然后添加一个按钮,然后添加glue
,然后添加最终的按钮。然后将此buttonPanel
添加到框架的北部。 IE。this.add(buttonPanel, BorderLayout.NORTH)
。阅读 Swing 教程中关于 How to Use Box Layout 的部分了解有关布局如何工作以及glue
是什么的更多信息。
关于java - 当我运行此 JFrame 时,为什么我的按钮不会出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297845/