Say I have a JButton called b and I:
b.setText(""+someIntVariable)
And I add()
it to the appropriate JFrame. If later my program changes the value of someIntVariable
will the JButton's text automatically be updated in my 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. If you want to change the text, you will need to call b.setText(""+someIntVariable)
again. However, you will not have to add
it to the JFrame.
This is because you're referring to the value stored in someIntVariable
, not to the variable itself. So if the value changes, it will not automatically update.
JButton's text will not automatically update. It gets a string representation that you created with the ""+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. 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.
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. 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.