i have these buttons what i wanna do is when i press any of them change the button name to "Ouch!"

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class sudokou extends Applet {
    Button num[] = new Button[9];

    int x, y, i, j, n = 0, num_x = 400, num_y = 45, grid_x = 400, grid_y = 100,
            xx = 0, yy = 0;
            public void init_numSolvers() {
        for (x = 0; x < 9; x++) {
            n++;
            num[x] = new Button("" + n);
            add(num[x]);
            num[x].setBounds(num_x, num_y, 40, 40);
            setLayout(null);
            num[x].setActionCommand("" + n);
            num_x += 40;
            }

        }
    }

Recommended Answers

All 5 Replies

change the button name? you mean the text on it?

a few remarks: stop using AWT classes, use the Swing classes instead.
add an actionListener to your button, and in the perform method, call setText on the button.

yes i want to change the text on it .... there is no way to use awt classes ????

any way what is the difference between swing and awt ??

sure you can use awt, but you shouldn't. awt is very old code. Swing contains newer versions of a lot of the objects. For instance, instead of Button, there's JButton, instead of Applet, there's JApplet, ..

as for your issue, it'll be something like this:

JButton button = new JButton("TRY");
button.addActionListener(new ActionListener(){
  @Override
  public void actionPerformed(ActionEvent e){
    button.setText("Whoops");
  }
});
//.. add to panel

AWT was Sun's first try at a Java GUI and it wasn't very good. So in 1998 (yes, seventeen years ago) they released Swing to replace AWT. Since then all the development has been in Swing, which has got better and better, faster and faster, while AWT remains stuck in the 1990's. There's no way you should be using AWT today.

stultuske's sample code is correct, but is based on an old version of Java. With current Java you can simply say

JButton button = new JButton("TRY");
button.addActionListener(e -> button.setText("Whoops"));
commented: yah, still working with Java6 on my current project .. +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.