我正在自学Java,我想用GUI创建一个石头、纸、剪刀游戏。我已经用扫描仪创建了一个基于文本的版本,但我还有很多工作要做。
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
public class RPS extends JFrame {
JRadioButton rock, paper, scissors;
ButtonGroup choices;
public static void main(String[] args) {
new RPS();
}
public RPS() {
super("Rock, Paper, Scissors");
setSize(400,300);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p=new JPanel();
rock = new JRadioButton("Rock");
paper = new JRadioButton("Paper");
scissors = new JRadioButton("Scissors");
choices = new ButtonGroup();
choices.add(rock);
choices.add(paper);
choices.add(scissors);
p.add(rock);
p.add(paper);
p.add(scissors);
add(p);
setVisible(true);
}
}
这是我的密码。我已经创建了一个窗口,并显示3个单选按钮,只允许选择一个选项。从这里开始,我想实现下一个按钮,并创建基于这两个选项的逻辑来生成答案。我相信我需要一个卡片布局,但Oracle文档对我没有帮助。我也不知道如何实现逻辑。感谢您的帮助,很抱歉发了这么长的邮件。再次感谢!
很抱歉我没有说清楚,我想为一个人设计一个转弯,按下嵌套按钮,然后第二个人转弯,按下finish并得到结果。我将把这个送给我八年级的同学。
在程序中实现CardLayout
非常热门。此布局的目的是对零部件进行分层。在你的情况下,你需要为每个玩家提供一个面板。所以你需要两块面板。
- 玩家1的JPanel(有自己的三个单选按钮)
- JPanel播放器2(有自己的三个单选按钮)
以上两个组成了Card(layered)Layout
(您可以将一个堆叠在另一个之上。
- 你需要一个标签来显示获胜者
- 你需要一个JPanel来按住下一个按钮
总之,你的布局应该像这个
Wrapped in JPanel(new BoderLayout())
-------------------------------------
| label to show status | BorderLayout.NORTH
-------------------------------------
| |
| CardLayout holding |
| two JPanels with RBs | BorderLayout.CENTER
|___________________________________|
|(JPanel) Next JButton | BorderLayout.SOUTH
-------------------------------------
当您点击下一个按钮时,您可以调用CardLayout
的next()
方法来显示下一个面板
示例
private CardLayout cardLayout = new CardLayout(10, 10); // hgap and vgap args
private JPanel cardPanel = new JPanel(cardLayout);
JPanel panel1 = new JPanel(); // holds first player
JPanel panel2 = new JPanel(); // holds second player
cardPanel.add(panel1);
cardPanel.add(panel2);
nextButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
cardLayout.next(cardPanel);
}
});
参见CardLayout文档了解其他移动方法
对于逻辑部分
- 正如我之前所建议的,你应该有六个单选按钮(每个玩家三个)
- 在你的逻辑中,你可以检查选择了哪些
- 您可能需要checkWinner JButton来执行该操作
示例
JRadioButton p1Scissors = new JRadioButton("Scissors");
JRadioButton p1Paper = new JRadioButton("Paper");
JRadioButton p1Rock = new JRadioButton("Rock");
// group them
JRadioButton p2Scissors = new JRadioButton("Scissors");
JRadioButton p2Paper = new JRadioButton("Paper");
JRadioButton p2Rock = new JRadioButton("Rock");
// group them
JLabel statusLabel = new JLabel(" ");
JButton checkWinner = new JButton("Check Winner"); // You can add to bottom panel
checkWinner.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (p1Scissors.isSelected() && p2Rock.isSelected()){
statusLabel.setText("Player 2 wins: Rock beats Scissors");
} else if ( ..... ) {
...
}
...
}
});