如何在Java中更新和刷新JTextField?(含相关代码片段)
Hey there! The issue here is that you’ve initialized your BalanceTextField with the starting balance, but you aren’t updating its content when the button is clicked. Let’s fix that—it’s super straightforward!
The Core Fix: Use setText() in the Button’s Action Listener
When the CoinTossPlayButton is clicked, you just need to call BalanceTextField.setText() with the updated balance value. Here’s how to adjust your code:
// Initialize your text field as you already did JTextField BalanceTextField = new JTextField("Balance:" + cointoss.GetBalance()); BalanceTextField.setBounds(500,170,100,15); BalanceTextField.setBorder(null); BalanceTextField.setOpaque(false); BalanceTextField.setVisible(true); CoinTossLabel.add(BalanceTextField); // Update the button's action listener to refresh the text field CoinTossPlayButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent CoinTossPlayButtonClicked){ System.out.print('\u000C'); // Get the updated balance after your coin toss logic runs Balance = cointoss.GetBalance(); WagerText = WagerTextField.getText(); Wager = ...; // Your existing wager calculation logic here // THIS IS THE KEY LINE TO UPDATE THE TEXT FIELD BalanceTextField.setText("Balance:" + Balance); // Note: Swing usually handles repainting automatically after setText(), // but if you ever see glitches, you can explicitly call: // BalanceTextField.repaint(); } });
Why This Works
setText()directly replaces the text displayed in theJTextField. Swing automatically triggers a repaint of the component once this method is called, so you rarely need to callrepaint()explicitly.- Make sure
Balanceholds the updated value fromcointoss.GetBalance()—you’ll want to run your coin toss logic first to modify the balance before updating the text field.
Quick Best Practices
- For consistency with Java naming conventions, use camelCase for variables (e.g.,
balanceTextFieldinstead ofBalanceTextField). - If your coin toss logic runs on a separate thread (not the Swing Event Dispatch Thread), wrap the
setText()call inSwingUtilities.invokeLater()to avoid UI glitches:SwingUtilities.invokeLater(() -> { BalanceTextField.setText("Balance:" + Balance); });
内容的提问来源于stack exchange,提问作者BigDaddySam
相关产品推荐
相关产品推荐

