You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中更新和刷新JTextField?(含相关代码片段)

How to Update and Refresh a JTextField in Java on Button Click

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 the JTextField. Swing automatically triggers a repaint of the component once this method is called, so you rarely need to call repaint() explicitly.
  • Make sure Balance holds the updated value from cointoss.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., balanceTextField instead of BalanceTextField).
  • If your coin toss logic runs on a separate thread (not the Swing Event Dispatch Thread), wrap the setText() call in SwingUtilities.invokeLater() to avoid UI glitches:
    SwingUtilities.invokeLater(() -> {
        BalanceTextField.setText("Balance:" + Balance);
    });
    

内容的提问来源于stack exchange,提问作者BigDaddySam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:30