簡體   English   中英

JButton是否自動更新?

[英]Do JButtons automatically update?

假設我有一個名為b的JButton,我:

b.setText(""+someIntVariable)

然后add()到適當的JFrame中。 如果以后我的程序更改了someIntVariable的值,JButton的文本會在我的GUI中自動更新嗎? 還是我需要做一些更新?

將按鈕添加到JFrame后,它將顯示您作為參數提供給它的原始文本。 如果要更改文本,則需要再次調用b.setText(""+someIntVariable) 但是,您不必將其add到JFrame。

這是因為您引用的是存儲在someIntVariable ,而不是變量本身。 因此,如果值更改,它將不會自動更新。

JButton的文本不會自動更新。 它獲取使用""+someIntVariable創建的字符串表示""+someIntVariable 即使您僅傳遞了int變量本身(這不可能,但假設是這樣),它也將是整數的副本,而不是原始值。 現在有一種方法可以獲取指向整數的指針,以查看原始值是否已更改,即使有辦法,該整數也無法通知JButton它已更改。

可能存在創建此類按鈕的方法。 我不認為使用JButton就是其中一種方法,但是其他框架中可能存在可以處理類似內容的按鈕類。 但是您需要使用更復雜的數據類型作為傳入的變量。

您可以像這樣更改按鈕的標簽:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class demoframe extends JFrame implements ActionListener {

    String label=new String("Init Label");
    JButton b1=new JButton(label);
    JButton b2=new JButton("Action");
    demoframe()
    {
        this.add(b1);
        this.add(b2);
        b2.addActionListener(this);
    }
    public static void main(String arg[])
    {
        demoframe d=new demoframe();
        d.setSize(200, 200);
        d.setVisible(true);
        d.setLayout(new FlowLayout());
    }
    public void actionPerformed(ActionEvent e) 
    {
        label="New Label";
        b1.setText(label);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM