如何通过JButton设置数值并确认?音符测验软件原型开发问询
Solution for Your Note Knowledge Test Proof-of-Concept
Got it, let's build this step by step with a complete, runnable Java Swing example that fits exactly what you need. Here's how to implement the functionality you described:
Core Components & Logic Breakdown
We'll need:
- A
JLabelto display the random 1/2 value - Two number
JButtons (for 1 and 2) for user selection - A confirmation
JButtonto submit the user's choice - An instance variable to track the user's selected number
- A
Randominstance to generate the random target value each round
Complete Working Code
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class NoteKnowledgePoC extends JFrame { private JLabel numberDisplay; private Integer userSelection; // Tracks choice (null = no selection made) private Random randomGenerator; public NoteKnowledgePoC() { // Initialize core tools and components randomGenerator = new Random(); numberDisplay = new JLabel("", SwingConstants.CENTER); JButton btn1 = new JButton("1"); JButton btn2 = new JButton("2"); JButton confirmBtn = new JButton("Confirm My Choice"); // Set up main window properties setTitle("Note Knowledge Test - PoC"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20)); setSize(320, 200); // Generate first random number and display it refreshRandomNumber(); // Add action listeners for number buttons btn1.addActionListener(e -> { userSelection = 1; JOptionPane.showMessageDialog(null, "You picked 1! Click Confirm to submit."); }); btn2.addActionListener(e -> { userSelection = 2; JOptionPane.showMessageDialog(null, "You picked 2! Click Confirm to submit."); }); // Add action listener for confirmation button confirmBtn.addActionListener(e -> { if (userSelection == null) { JOptionPane.showMessageDialog(null, "Wait, you haven't picked a number yet!"); return; } // Get the target number from the display label int targetNumber = Integer.parseInt(numberDisplay.getText()); // Compare selection to target and show result if (userSelection.equals(targetNumber)) { JOptionPane.showMessageDialog(null, "Perfect! That's correct."); } else { JOptionPane.showMessageDialog(null, "Oops, wrong choice. The correct number was " + targetNumber); } // Reset for next round userSelection = null; refreshRandomNumber(); }); // Add all components to the window add(numberDisplay); add(btn1); add(btn2); add(confirmBtn); } // Helper method to generate and display a new random number (1 or 2) private void refreshRandomNumber() { int randomNum = randomGenerator.nextInt(2) + 1; // Gives 1 or 2 numberDisplay.setText(String.valueOf(randomNum)); numberDisplay.setFont(new Font("Arial", Font.BOLD, 28)); } public static void main(String[] args) { // Launch GUI on Swing's event thread (best practice) SwingUtilities.invokeLater(() -> new NoteKnowledgePoC().setVisible(true)); } }
Key Details Explained
- Tracking User Selection: We use
Integer userSelectioninstead of a primitiveintso we can easily check if the user has made a choice (null means no selection yet). - Random Number Generation:
randomGenerator.nextInt(2)produces 0 or 1; adding 1 shifts this to the desired 1 or 2 range. - Event Handling: Each number button sets the user's selection and gives quick feedback. The confirm button validates the selection, compares it to the target, shows a result, and resets the test for the next round.
- Swing Best Practice: We launch the GUI with
SwingUtilities.invokeLaterto ensure it runs on Swing's dedicated event thread, preventing UI glitches.
Quick Customization Tips
- Replace the
JOptionPanepop-ups with in-GUI labels if you prefer a cleaner interface. - Adjust the layout (try
GridLayoutorBorderLayout) to match your desired UI design. - Add score tracking or timer features later as you expand toward your full application.
内容的提问来源于stack exchange,提问作者Jonathan Rada
相关产品推荐
相关产品推荐

