button update when clicked
Hello java programmers!
I am going to ask a simple question (doesn't seem that simple to me though). I want to make a button change its text whenever clicked and i want that to be immediately shown in my GUI. I have my button and the listener class up and running. It's just this bit that i don't know how to do.
Thanks in advance.
P.S. if you feel like posting some code that would be greatly appreciated!
Re: button update when clicked
Please post some code which demonstrates what you have done so far. It sounds like you are close to getting what you want, but without code its tough to judge. For what its worth, see the API for JButton for methods on how to set its text.
Re: button update when clicked
This is the original button
Code :
JButton b00 = new JButton(" ");
ActionListener ac = new Counter(b00);
b00.addActionListener(new Counter(b00));
panelGrid.add(b00);
And this is the listener class.
Code :
public class Counter implements ActionListener
{
private int count;
private JButton button;
public Counter(JButton b)
{
button = b;
}
public void actionPerformed(ActionEvent e)
{
count++;
if (count > 5) {
count = 0;
}
button = new JButton(""+count);
System.out.println("CLICKED "+count+" TIMES");
}
}
I am aware that it actually creates a new button with the count value as text but i don't see how can i replace the b00 button with 'button' button.
Re: button update when clicked
Quote:
but i don't see how can i replace the b00 button with 'button' button.
Has to do with references and what the reference points to at the time you create your GUI. Same thing as the following
Code :
String test1 = "test1";
String test2 = test1;
test1 = "test3";
System.out.println(test1);
System.out.println(test2);
Prints
because you've re-assigned the reference, and previous references still point to the original. As I mentioned in my previous post, get familiar with the API, and the fix to your problem is to use the setText function of JButton (see JButton (Java Platform SE 6) )
Re: button update when clicked
thank you for your time. You helped me a lot :)