剪刀石头布游戏功能异常问题及相关Java Swing代码咨询
First, let's clean up the partial code you shared to make it easier to analyze:
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class stensax extends JFrame implements ActionListener{ JPanel p1=new JPanel(); JPanel p2=new JPanel(); JPanel p3=new JPanel(); int x; int y; JButton knapp[] = new JButton [6]; public stensax(){ p1.setLayout(new GridLayout(2,1)); setBackground(Color.lightGray); p2.setLayout(new GridLayout(2,4,6,6)); p3.setLayout(new BorderLayout()); JLabel label1 = new JLabel("Ditt val"); JLabel label2 = new JLabel("Datorns val"); JLabel la... } }
Since your code cuts off mid-line, it's tricky to pinpoint the exact failure, but here are the most common issues that would break a Swing app like this:
Unfinished UI Setup: The code stops mid-label creation—if you don't complete adding all UI elements (labels, buttons) to their parent panels, and those panels to the main frame, nothing will render. Double-check you're calling
add()for every component (e.g.,p1.add(label1);,add(p3);).Missing Critical Frame Configuration: Your constructor doesn't set basic JFrame essentials. Add these lines to the end of your
stensax()constructor to make the window appear and behave correctly:setSize(450, 300); // Tweak size to fit your UI setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);Unregistered Action Listeners: You implement
ActionListener, but if you don't attach the listener to yourknappbuttons (e.g.,knapp[0].addActionListener(this);), clicking the buttons will do nothing.Undefined Game Logic: Variables
xandyare declared but unused in the snippet. You need code to generate the computer's choice (y), capture the user's choice (x), compare them, and update the UI to show the result.Minor (But Important) Naming Issue: Java conventions require class names to start with a capital letter—renaming
stensaxtoStenSaxwon't fix functionality, but it'll make your code easier to read and maintain.
If you can share the full, complete code (including the rest of the constructor, actionPerformed() method, and main method), I can give you a precise fix for whatever's causing the game to fail.
内容的提问来源于stack exchange,提问作者FårHäst

