货币兑换 API Java GUI

Currency Exchange API Java GUI

我对这个级别的编程还很陌生,我想知道是否有人可以帮助我。

所以我尝试使用 Java 创建一个货币兑换应用程序,但我在更新 GUI 上的值以反映 API 上的新值时遇到了问题。本质上,值经常更改并显示在控制台上,但是,GUI 值永远不会更新并保持不变。

我认为 ActionListener 会帮助解决这个问题,但要么我没有正确实施它,要么我没有用谷歌搜索并提出正确的解决方案。

提前感谢您的帮助:)

这是我的代码: GUI.java

public class GUI extends JFrame {
    
    static Arb arb = new Arb();

    private JPanel contentPane;
  public static void main(String[] args) throws IOException, InterruptedException {
        
        ActionListener taskPerformer = new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 try {
                    arb.runUpdate_fx("anAPI");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             }
         };
         Timer timer = new Timer(100 ,taskPerformer);
         timer.setRepeats(true);
         timer.start();
 
         Thread.sleep(5000);
        
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public GUI() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setBounds(100, 100, 1121, 765);
      contentPane = new JPanel();
      contentPane.setBackground(Color.BLACK);
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      contentPane.setLayout(new BorderLayout(0, 0));
      setContentPane(contentPane);

      JTextPane FXRate = new JTextPane();
      FXRate.setForeground(new Color(255, 255, 255));
      FXRate.setBackground(new Color(0, 0, 0));
      FXRate.setEditable(false);
      FXRate.setFont(new Font("Tahoma", Font.BOLD, 11));
      panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
      FXRate.setText("FX Rates\r\n\r\nEUR-AUD FX Rate: " + arb.fxEURAUD + "\r\nEUR-USD FX Rate: " + arb.fxEURUSD);
      panel_1.add(FXRate);
    }
}

结果: 欧元兑澳元:1.646659 一段时间后 欧元兑澳元:1.646659

预期结果: 欧元兑澳元:1.646659 一段时间后 欧元兑澳元:1.80102

您的计时器和事件处理程序看起来不错,但更新方法仅将新值提取到 Arb 对象中;没有什么可以获取这些值并将它们放入 GUI 中。您可以在事件 handler.after 更新方法 returns 中明确执行此操作。要启用它,您可能希望将 FXRate 设为成员变量,以便您可以从动作侦听器访问它。

引用在Java中按值传递。

JTextField textField = new JTextField();
String text = "Initial text";
textField.setText(text); // no displays "Initial text";
text = "Updated text"; // doesn't change what the panel displays
// the panel still holds a reference to the old text
textField.setText(text); // updates the reference the panel holds to your new text

在您的事件侦听器中,您需要使用更新后的字符串调用setText才能真正让文本字段显示它。