0

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;
            }

        }
    }

Edited by Ahmed_62

3
Contributors
5
Replies
15
Views
1 Year
Discussion Span
Last Post by JamesCherrill
1

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.

0

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

1

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
2

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"));
Votes + Comments
yah, still working with Java6 on my current project ..
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.