简体   繁体   English

JButton是否自动更新?

[英]Do JButtons automatically update?

Say I have a JButton called b and I: 假设我有一个名为b的JButton,我:

b.setText(""+someIntVariable)

And I add() it to the appropriate JFrame. 然后add()到适当的JFrame中。 If later my program changes the value of someIntVariable will the JButton's text automatically be updated in my GUI ? 如果以后我的程序更改了someIntVariable的值,JButton的文本会在我的GUI中自动更新吗? Or do I have to do something to update it ? 还是我需要做一些更新?

Once a button is added to the JFrame, it will show the original text that you gave it as a parameter. 将按钮添加到JFrame后,它将显示您作为参数提供给它的原始文本。 If you want to change the text, you will need to call b.setText(""+someIntVariable) again. 如果要更改文本,则需要再次调用b.setText(""+someIntVariable) However, you will not have to add it to the JFrame. 但是,您不必将其add到JFrame。

This is because you're referring to the value stored in someIntVariable , not to the variable itself. 这是因为您引用的是存储在someIntVariable ,而不是变量本身。 So if the value changes, it will not automatically update. 因此,如果值更改,它将不会自动更新。

JButton's text will not automatically update. JButton的文本不会自动更新。 It gets a string representation that you created with the ""+someIntVariable . 它获取使用""+someIntVariable创建的字符串表示""+someIntVariable Even if you passed just the int variable itself (which isn't possible, but let's suppose it was), it would be a copy of the integer, not the original value. 即使您仅传递了int变量本身(这不可能,但假设是这样),它也将是整数的副本,而不是原始值。 There's now way for it to get a pointer to the integer to see that the original has changed, and even if there was a way, the integer would have no way of notifying the JButton that it had changed. 现在有一种方法可以获取指向整数的指针,以查看原始值是否已更改,即使有办法,该整数也无法通知JButton它已更改。

There may be ways to create buttons like this. 可能存在创建此类按钮的方法。 I don't think using a JButton is one of those ways, but there may be button classes in other frameworks that can handle something like this. 我不认为使用JButton就是其中一种方法,但是其他框架中可能存在可以处理类似内容的按钮类。 But you'd need to use a more complicated data type as the variable that you passed in. 但是您需要使用更复杂的数据类型作为传入的变量。

You can change the label of a button like this : 您可以像这样更改按钮的标签:

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